📜 [專欄新文章] 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.
👏 歡迎轉載分享鼓掌
同時也有1部Youtube影片,追蹤數超過8,320的網紅ItsGirlZeremyyy,也在其Youtube影片中提到,Oh nooo it's been awhile I haven't do any cover song hahaha but here it is just for fun. ? Jeremy Renner my favorite number 1! ❤ WeSing version. Son...
version number rule 在 黃之鋒 Joshua Wong Facebook 的最佳解答
【緊急呼籲:全球聲援泰國抗爭者 呼籲泰國皇室推行政治改革】
【Please scroll down for English version】
10月16日,過萬名泰國示威者聚集在曼谷市中心參與尋求政治改革的民主抗爭。泰國警方卻出動水炮車,暴力驅散和平的示威者。我們強烈譴責泰國政府漠視人民訴求,並呼籲有關當局保持克制,以真正的政治改革取代無休止的戒嚴惡法和政治檢控。
由七月開始的學生運動,令全球目光重新留意自1932年起,宗教、國王、政治三位一體的泰國。在面對政權強行地解散「未來前進黨」丶剝奪部分議員當選資格、限制部份民主派人士不能組織政黨,並懷疑涉及流亡異見人士的「被失蹤」事件,我們強調政權有責任保持克制,而我們絕對站在抗爭者的一方,贊成泰國人民的訴求,包括但不限於解散國會丶停止威脅人民丶釋放被拘捕人士和制定新憲法。儘管我們相信任何地方都有行使宗教自由的權利,但政權卻不能以此為理由,試圖推翻啟蒙運動以來所強調的自由和平等思想,重用像中世紀落伍的思維,用不同的教義和皇權為藉口實行暴政統治,藐視人民的自由丶尊嚴和基本公民權利。
自上世紀第三波民主化以來,全球各地仍然充滿着不民主的威權國家。這些國家更有死灰復燃之勢,嚴重侵害我們所相信的民主價值。過去一年,世界各地包括香港丶台灣丶白俄羅斯等熱愛民主自由的人,都見證了一次又一次的人民如何覺醒,並繼續追求全面民主化的改革之路。
我們深信民主改革的浪潮定會戰勝黑暗,也希望各位能夠一起起義對抗暴政,聲援泰國人民,聲援所有自由人。
就讓獨裁在我們這一代結束。
張崑陽 羅冠聰
全球聯署連結: http://chng.it/KVz8msP9Fh
【Emergency: Global Support for Thai Protests The Thai Monarch must undergo imminent reforms】
On 16th Oct, over ten thousand protestors rallied in the city center of Bangkok under the banner of pro-democratic reforms. The Thai police force responded with water-cannon trucks in a violent crackdown over peaceful protests. We condemn the Thai Government for its contempt and disrespect of the appeal from the Thai people. We call on the Government to exercise self-restraint and to advance substantial political reforms in lieu of relentless political prosecutions under inhumane laws.
Ever since July, the Student Movement had attracted global scrutiny on Thailand. A country who had upheld a trinity of nation, religion and king since 1932. The Future Forward Party was dissolved by force. Legislators had been disqualified and pro-democracy figures had been forbidden to form political parties. The Government is also suspected of puppeteering the disappearance of dissenting figures, whether or not they are in-exile. We believe that the Thai Government ought to exercise self-restraint on these infringement of rights and liberties as well. We stand in solidarity with Thai protestors, in support of their demands including but not limited to the dissolution of the Parliament, to stop ruling with terror, to release all detainees and to lay down a new constitution.
Universal religious freedom does not serve as a basis for the state to undermine and overturn the essential thoughts of peace and freedom, which are endemic to the Enlightenment. The claim by a totalitarian regime based on the divine right to rule can be interpreted as a revival of an obsolete thinking, which should have been left in medieval times. It is no excuse to repress the many freedoms the people are entitled to, as well as their dignity as human beings and the fundamental civil liberties and rights.
A great number of undemocratic authoritarian regimes had survived or sprouted after the third wave of democratization, dating back from the last century. There is indeed a new surge of authoritarian states which devours the values of democracy we hold so dearly. The year of 2019 marks a crusade of peace-loving, democratic protestors risking their all to motivate change, in hope that their homelands will embrace reforms and undergo genuine democratization. The people have spoken, from Hong Kong to Taiwan, to Belarus and many more.
We believe the wind of change is inevitable. Democracy shall prevail over the authoritarian regimes that creep in shadows. We call on every freeman to voice out against tyranny, as of duty and belief.
Democracy now.
Sunny Cheung Nathan Law
Petition Link: http://chng.it/KVz8msP9Fh
----------------------------------------------
╭──────────────────╮
╞🌐請訂閱Patreon,支持我的理念與工作
╞ https://www.patreon.com/sunnycheung
╰──────────────────╯
----------------------------------------------
version number rule 在 李怡 Facebook 的精選貼文
Exchange for Support (Lee Yee)
There was one other major world event on Jul 1, apart from the promulgation of the National Security Law for Hong Kong. A referendum was held in Russia on the revision of the country’s Constitution.
In the Newscast on the night before last, CCTV broadcast a key feature about the telephone dialogue between Xi Jinping and Russian President Putin. Putin expressed firm support from Russia for China's efforts to maintain national security in Hong Kong. Xi mentioned the Russian constitutional amendment, endorsed by a majority vote in a referendum, which will allow Putin’s term as the president to last until 2036. Xi reaffirmed China’s firm support for Russia's commitment to a development direction that is appropriate for the nation.
Not a word was uttered by China on Russia’s celebration of its 160-year occupation of Vladivostok. Instead, the compliments on Putin’s uninterrupted re-election were dished out in exchange for Russia’s support for the National Security Law.
Although there are 53 countries on the United Nations Human Rights Commission (and reportedly 20 more) that support Hong Kong National Security Law, once all the names of these countries are unfolded, it is not hard to spot that none of them are countries that would likely attract Chinese nor Hong Kong people to invest, study, or live in. There is not a single great power amongst them. However, though opposition to the law has only been voiced out by 27 countries, all of them are influential with significant leverage on world affairs. Of course, among them the most adamant is the United States, which has withdrawn from the Human Rights Commission. Now that Russia is at last joining the Chinese bandwagon, the situation looks a little less awkward for China.
On July 1, the referendum on the constitutional amendments in Russia drew to a close. 78% of the voters supported the amendments, the most important one of which is the "removal of the upper limit of the presidential term in the ‘re-election’ clause”. That is to say, all the presidential terms before the amendment takes effect will be revoked. Everything will be back to zero. Putin's term of office will start all over again. According to the new constitution, Putin can be re-elected as the president until 2036. He will have stayed in the highest power for the longest in Russian history, even surpassing the reign of Peter the Great.
Like Xi Jinping, who forced through the National Security Law for Hong Kong, Putin did not receive any blessings from other major international powers for his feat. There was no strong opposition because after all it went through a referendum. The United States and the European Union, however, were skeptical about the voting process, questioning whether there was coercion of voters, or repeated voting.
Russia's deletion of the presidential re-election regulations is analogous to China's deletion of the presidential re-election regulations in the year before last. With both world powers ruled by lifetime leaders, concerns about such a situation have been raised in international public opinion.
Despite all the twists and turns throughout history, in China as well other countries, everything boiled down to power struggles that basically stemmed from succession schemes amongst the most powerful, which in turn came with a lifetime tenure amongst top leaders. A lifetime tenure for the most powerful led to absolute power that bred absolute corruption, which is the root cause of all political complexities in human society.
All the struggles in the royal courts originated from the inheritance of power. The potential heirs, not the sons, of an emperor were the focuses. There was no place for normal family intimacies amongst sons, daughters, siblings, wives and concubines. Family relationships were built on associations with the potential heirs. For the past 70 years in the Soviet Union, the severe suppression of the people by the dictatorship, and all the brutal struggles have all been due to the inheritance of power at the highest level. During Mao Zedong’s rule, every single one of the never ending political movements of class struggles could be traced back to the inheritance of power at the top. Ordinary people were the victims as a result.
After millennia in the dark ages, it was not until 1776 when the United States became independent that the problem of inheritance of power at the highest level was basically solved. Finally, people could vote to authorize the succession of power in a legal manner, without bloodshed and contention. A system was established to ensure the separation of the three powers, a multi-party system, freedom of news reporting, speech, religion, and association, etc. as checks and balances of the highest power so as to prevent absolute corruption that came with absolute power.
In 1800, there were only three democratic countries in the world. By 2015, the number of countries authorized by the peoples’ votes increased to 130. According to Churchill, ‘democracy is the worst form of government except for all those other forms that have been tried from time to time.’ In all those that have been tried, plebs were inevitably victimized in the power struggles.
Deng Xiaoping might also have understood that power inheritance is the root cause of all political complexities. That was why he laid down the system for naming the heir for the generation after the immediate next. This system achieved a certain period of social stability. What is the impact of abandoning this approach? Putting China aside, what we saw in Hong Kong was the changes in the period from the Causeway Bay Bookstore incident to the implementation of the Hong Kong version of National Security Law.
version number rule 在 ItsGirlZeremyyy Youtube 的最佳解答
Oh nooo it's been awhile I haven't do any cover song hahaha but here it is just for fun. ? Jeremy Renner my favorite number 1! ❤
WeSing version.
Song: Main Attraction by Jeremy Renner
?SUBSCRIBE TO JUICES SQUAD!!?
???
❤?? ITSBOYWUZERYYY [WUZERE]
▶ https://www.youtube.com/channel/UC4yS7kB6L4CvU0NmWSRIGcQ
??? ITSGIRLJINXYYY [JINX]
▶ https://www.youtube.com/c/ItsGirlJinxyyy
??? ITSBOYJEFRYYY [JEFF]
▶ https://www.youtube.com/c/ItsBoyJefryyy
??? ITSGIRLTIARYYY [TIARA]
▶ https://www.youtube.com/c/ItsGirlTiaryyy
⚡?? ITSBOYZAMNYYY [ZAMN]
▶ https://www.youtube.com/channel/UCJNm3jwk1zuvGr97ttlrqJA
?SECOND CHANNEL?
▶https://www.youtube.com/c/ZKRenner
THIRD CHANNEL
▶https://www.youtube.com/c/DevilMischievous
⚠RULE OF THIS CHANNEL⚠
Comments will be removed if you…
1: "First", and spamming
2: Ask for the song/music
3: Cancerous, hate, annoying, sexual related and underestimate
4: Speak different languages (non Malay/Eng languages)
5: Rude comments (REASON: To avoid arguments and fights.)
6: No SFM related requests
?MY SOCIAL MEDIA?
INSTAGRAM
▶ https://www.instagram.com/itsgirlzoeyyy/
STEAM ACCOUNT
▶ https://steamcommunity.com/id/Itsgirlzoeyyy
DEVIANTART
▶ https://www.deviantart.com/itsgirlzoeyyy