📜 [專欄新文章] Gas Efficient Card Drawing in Solidity
✍️ Ping Chen
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium
Assign random numbers as the index of newly minted NFTs
Scenario
The fun of generative art NFT projects depends on randomness. The industry standard is “blind box”, where both the images’ serial number and the NFTs’ index are predetermined but will be shifted randomly when the selling period ends. (They call it “reveal”) This approach effectively solves the randomness issue. However, it also requires buyers to wait until the campaign terminates. What if buyers want to know the exact card right away? We’ll need a reliable onchain card drawing solution.
The creator of Astrogator🐊 isn’t a fan of blind boxes; instead, it thinks unpacking cards right after purchase is more interesting.
Spec
When initializing this NFT contract, the creator will determine the total supply of it. And there will be an iterable function that is randomly picking a number from the remaining pool. The number must be in range and must not collide with any existing ones.
Our top priority is accessibility/gas efficiency. Given that gas cost on Ethereum is damn high nowadays, we need an elegant algorithm to control gas expanse at an acceptable range.
Achieving robust randomness isn’t the primary goal here. We assume there’s no strong financial incentive to cheat, so the RNG isn’t specified. Implementers can bring their own source of randomness that they think is good enough.
Implementation
Overview
The implementation is pretty short and straightforward. Imagine there’s an array that contains all remaining(unsold) cards. When drawIndex() is called, it generates a (uniform) random seed to draw a card from the array, shortens the array, and returns the selected card.
Algorithm
Drawing X cards from a deck with the same X amount of cards is equal to shuffling the deck and dealing them sequentially. It’s not a surprise that our algorithm is similar to random shuffling, and the only difference is turning that classic algo into an interactive version.
A typical random shuffle looks like this: for an array with N elements, you randomly pick a number i in (0,N), swap array[0] and array[i], then choose another number i in (1,N), swap array[1] and array[i], and so on. Eventually, you’ll get a mathematically random array in O(N) time.
So, the concept of our random card dealing is the same. When a user mints a new card, the smart contract picks a number in the array as NFT index, then grabs a number from the tail to fill the vacancy, in order to keep the array continuous.
Tweak
Furthermore, as long as the space of the NFT index is known, we don’t need to declare/initialize an array(which is super gas-intensive). Instead, assume there’s such an array that the n-th element is n, we don’t actually initialize it (so it is an array only contains “0”) until the rule is broken.
For the convenience of explanation, let’s call that mapping cache. If cache[i] is empty, it should be interpreted as i instead of 0. On the other hand, when a number is chosen and used, we’ll need to fill it up with another unused number. An intuitive method is to pick a number from the end of the array, since the length of the array is going to decrease by 1.
By doing so, the gas cost in the worst-case scenario is bound to be constant.
Performance and limitation
Comparing with the normal ascending index NFT minting, our random NFT implementation requires two extra SSTORE and one extra SLOAD, which cost 12600 ~ 27600 (5000+20000+2600) excess gas per token minted.
Theoretically, any instantly generated onchain random number is vulnerable. We can restrict contract interaction to mitigate risk. The mitigation is far from perfect, but it is the tradeoff that we have to accept.
ping.eth
Gas Efficient Card Drawing in Solidity was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.
👏 歡迎轉載分享鼓掌
同時也有2部Youtube影片,追蹤數超過9萬的網紅Shiney,也在其Youtube影片中提到,Watch Dogs ไทย ซื้อเกมได้ที่ https://store.epicgames.com/legendaus... Watch Dogs is an action-adventure game, played from a third-person view. The ...
if array is empty 在 Shiney Youtube 的最佳貼文
Watch Dogs ไทย
ซื้อเกมได้ที่ https://store.epicgames.com/legendaus...
Watch Dogs is an action-adventure game, played from a third-person view. The player controls hacker Aiden Pearce, who uses his smartphone to control trains and traffic lights, infiltrate security systems, jam cellphones, access pedestrians' private information, and empty their bank accounts. System hacking involves the solving of puzzles. The game is set in a fictionalized version of Chicago ("Windy City"), an open world environment which permits free-roaming. It has a day-night cycle and dynamic weather system, which changes the behavior of non-player characters (NPCs). For melee combat, Pearce has an extensible truncheon; other combat uses handguns, shotguns, sniper rifles, machine guns, and grenade launchers. There is a slow motion option for gunplay, and the player can use proximity IEDs, grenades, and electronic lures. Lethal and non-lethal mission approaches can be enacted.
Pearce can scale vertical surfaces, hack forklifts and aerial work platforms to reach places otherwise unreachable, and can crouch behind walls to hide from enemies. The player has an array of vehicles with which to navigate the setting, including motorcycles, muscle cars, off-road vehicles, SUVs, luxury vehicles, sports cars, and speedboats.
The car radio is customizable, with about fifty songs.
If the player steals a car, its driver can summon the police;
if the player has a good reputation, the driver may acquiesce. A good reputation may be gained by detecting (and stopping) crimes, and a bad reputation results from committing crimes.
The skill tree is upgraded with points earned from hacking, combat, driving, and crafted items.
Money can be used to purchase guns, outfits, and vehicles.
There are several minigames, ranging from killing aliens to controlling a large, robotic spider.
if array is empty 在 Umi Kun Youtube 的最讚貼文
■■■■Vocal■■■■■■■■■■
Umikun Twitter : @Umibabe
Piko Twitter : @piko_niconico
■■■■■■■■■■■■■■■■■■
Camera By Sam (Home Sessions)
https://www.youtube.com/user/homesessionsjapan
Mix and Sound arrangement By Toshihiro
@Toshihiro1120
Video Edit By Umikun
Umikun Instagram : http://instagram.com/umi_kun_
FaceBook : https://www.facebook.com/umikunnopage
■■■■■■■■■English Lyrics By frost@_xfrostx■■■■■■■■■■■■■■■
Too many times I have lied and now it’s where I can no longer hide
With no law to excuse me this time, there’s no grace to save me from my crime
Things won’t get better today, everything is simply going array
Slipping into depravity, without knowing what had disappeared from me
Come here
Don’t go away
Stay
“I’ve hidden it away”
Mayday! Even if it comes down to me, don’t even hold me tight just set me free
Mayday! Once it all comes down to me, all I’ll ever need is for you to laugh at me
(Say Whoaa…)
I know I’m nothing but the shell of an empty ghost
(Say Whoaa…)
I know my forsaken lies will never leave me so
Hey
NO is the answer I’ve tried, but somehow YES is all I replied
Behind all the regrets I’ve had, I’ve learned innocence’s only another scam
Acting the victim’s fine too, just cover it up with a prayer, we’re through
No control over how much I say, not realising I was digging my grave
And guilt is clear as day
So grey
With my act I’ll go astray
Mayday! Don’t stop, just chide away! Honesty’s a trait that’s just a dream to me
Mayday! Don’t stop, just judge away! Until the end I’ll remain with my selfish ways
(Say Whoaa…)
I know I’m nothing but the shell of a deviant ghost
(Say Whoaa…)
I know my life is a blank void left empty so
Hey
Wishing for everything I didn’t own, I met a me that wasn’t me I’ve ever known
Even then I continued moving on, a forever never-ending night without a dawn
Love me for everything I’ll never own, Me with all my ego-selfishness I’ve shown
Can you really see who I’ve truly been
A lone poisoned clown behind a screen
Mayday! Even if it comes down to me, don’t even hold me tight just set me free
Mayday! Once it all comes down to me, all I’ll ever need is for you to laugh at me
Mayday! Don’t stop, just chide away! Honesty’s a trait that’s just a dream to me
Mayday! Don’t stop, just judge away! Until the end I’ll remain with my selfish ways
Mayday! Show the world for who I am, for my world’s just about to meet its end
Mayday! Dance with me this one last time, did you realise from the start I’m not who I really am?
Ah…
I know I’m nothing but the shell of an empty ghost
I know my forsaken lies will never leave me so
I know I’m nothing but the shell of a deviant ghost
I know my life is a blank void left empty so
Too many times I have lied and now it’s where I can no longer hide
With no law to excuse me this time, there’s no grace to save me from my crime
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
