📜 [專欄新文章] 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.
👏 歡迎轉載分享鼓掌
同時也有19部Youtube影片,追蹤數超過9萬的網紅Shiney,也在其Youtube影片中提到,ซื้อเกมได้ที่ https://store.epicgames.com/legendauser/metro-last-light-redux Metro Last Light Redux พากย์ไทย Metro: Last Light takes place in 2034, o...
「gas constant」的推薦目錄:
- 關於gas constant 在 Taipei Ethereum Meetup Facebook 的精選貼文
- 關於gas constant 在 孫怡琳 Facebook 的精選貼文
- 關於gas constant 在 Taipei Ethereum Meetup Facebook 的最讚貼文
- 關於gas constant 在 Shiney Youtube 的最佳貼文
- 關於gas constant 在 Shiney Youtube 的最佳解答
- 關於gas constant 在 Shiney Youtube 的最佳解答
- 關於gas constant 在 Universal Gas Constant R - YouTube 的評價
- 關於gas constant 在 MathType - Facebook 的評價
- 關於gas constant 在 What is the physical significance of the universal gas constant ... 的評價
gas constant 在 孫怡琳 Facebook 的精選貼文
跟著怡琳看世界 36
Animals are changing their body shapes to cope with climate change
動物正在改變牠們的身形以應對氣候變遷
warm-blooded 溫血的
constant 穩定的/連續不斷的
heatstroke 中暑
breeding 繁殖
migration 遷徙
appendage 附屬器官
gang-gang cockatoo 紅冠灰鳳頭鸚鵡
red-rumped parrot 紅腰鸚鵡
emission 排放
Global warming is a big challenge for warm-blooded animals, which must maintain a constant internal body temperature. As anyone who’s experienced heatstroke can tell you, our bodies become severely stressed when we overheat.
全球暖化對溫血動物來說是一大挑戰,牠們必須保持穩定的內部體溫。任何經歷過中暑的人都會告訴你,當我們過熱時,我們的身體會感受到嚴重的壓力。
Animals are dealing with global warming in various ways. Some move to cooler areas, such as closer to the poles or to higher ground. Some change the timing of key life events such as breeding and migration, so they take place at cooler times. And others evolve to change their body size to cool down more quickly.
動物正在以各種方式應對全球暖化。有些會遷移到較冷的區域,例如更靠近兩極或是地勢較高的地方。有些改變關鍵生命事件的時間,如繁殖和遷徙,讓它們在較冷的時候發生。而其他透過演化來改變牠們的體型,以便更快地降溫。
Our new research examined another way animal species cope with climate change: by changing the size of their ears, tails, beaks and other appendages.
我們的新研究,考察了動物物種應對氣候變遷的另一種方式:透過改變耳朵、尾巴、喙以及其他附屬器官的大小。
We found most documented examples of shape-shifting involve birds – specifically, increases in beak size. This includes several species of Australian parrots. Studies show the beak size of gang-gang cockatoos and red-rumped parrots has increased by between 4% and 10% since 1871. We found clear evidence that birds with smaller beaks are also less likely to survive hotter summers.
我們發現大多數記錄在形狀的例子都涉及鳥類-特別是鳥喙尺寸的增加。這包含好幾種的澳洲鸚鵡。研究顯示,從1871年以來,紅冠灰鳳頭鸚鵡和紅腰鸚鵡的喙大小增加4%到10%。我們發現明確的證據顯示,喙較小的鳥類比較不可能在炎熱的夏天存活。
So while predicting how wildlife will respond to climate change is important, the best way to protect species into the future is to dramatically reduce greenhouse gas emissions and prevent as much global warming as possible.
雖然預測野生動物如何應對氣候變遷很重要,但保護物種可以存活到未來最好的方式,就是大幅減少溫室氣體排放,並盡可能防止全球暖化。
資料來源:
https://www.weforum.org/agenda/2021/09/climate-change-animals-global-warming-shape?utm_source=ig&utm_medium=social_video&utm_campaign=social_video_2021&utm_content=23775_Carousel_animal_shapeshift_global_warming
gas constant 在 Taipei Ethereum Meetup Facebook 的最讚貼文
📜 [專欄新文章] 可升級合約介紹 - 鑽石合約(EIP-2535 Diamond standard)
✍️ Kimi Wu
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium
Photo by Evie S. on Unsplash
前言
可升級合約簡單來說是透過 proxy contract(代理合約)來達成,藉由代理合約去呼叫欲執行的合約,若要升級,則把代理合約中的指向的地址換為新的合約地址即可。而執行的方式則是透過 delegateCall,但 delegateCall 不會更動目標合約的狀態。所以要怎麼處理變數,就是一門學問了。
舉例來說,contract B 有個變數 uint256 x,初始值為 0, 而 function setX(uint256),可以改變 x 的值。proxy contract A 使用 delegatecall 呼叫 contract B 的 setX(10),交易結束後,contract B中的 x 依然還是 0。
OpenZeppelin 提出了三種實作方式,可以做到可升級合約,細節可參考 Proxy Patterns,而最終的實作選用了 Unstructured Storage的這個方式,這種方式對於開發較友善,開發時不需特別處理 state variables(不過升級時就需要特別注意了)。而這篇主要是介紹 Diamond standard,OpenZeppelin 的可升級合約就不多做介紹。
USDC V2 : Upgrading a multi-billion dollar ERC-20 token 詳細地介紹代理合約跟變數儲存之間的關係,不了解升級合約的原理,建議先看看。
鑽石合約
名詞介紹
diamond:合約本體,是一個代理合約,無商業邏輯
facet:延伸的合約(實際商業邏輯實作的合約)
loupe:也是一個 facet,負責查詢的功能。可查詢此 diamond所提供的 facet與facet所提供的函式
diamondCut:一組函式,用來管理(增加/取代/減少)此 diamond合約所支援的功能
Loupe
直接來看 loupe的介面,從宣告就能很清楚暸解 diamond合約的實作方式,loupe宣告了一個結構 Facet,Facet結構包含一個地址及 function selector 陣列,所以我們只需要記錄一個 Facet陣列就可以得知這個 diamond 合約有多少個延伸合約及所支援的功能(loupe只定義結構,而實際變數是存在diamon合約中的)。也就是 diamond合約中只記錄延伸合約的地址及其支援的 function selectors,及少數 diamond合約的管理邏輯,並無商業邏輯,因此可以外掛非常非常多的合約上去(就像一個Hub),也就可以突破一個合約只有24K的限制。
// A loupe is a small magnifying glass used to look at diamonds.interface IDiamondLoupe { struct Facet { address facetAddress; bytes4[] functionSelectors; } function facets() external view returns (Facet[] memory facets_); function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); function facetAddresses() external view returns (address[] memory facetAddresses_); function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);}
DiamondCut
至於 facet在 diamond合約上的註冊或是修改,就由 diamondCut負責,從以下程式碼可以清楚瞭解其功能(EIP中有規範,每次改變都需要發送DiamondCut事件)
interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);}
Diamond合約
接下來就是最核心的部分 — diamond本體合約。以下是官方的範例,方法上跟 OpenZeppelin 一樣使用 fallback 函式跟 delegateCall 。
呼叫合約所不支援的函式,就會去執行 fallback 函式,fallback 函式中再透過 delegateCall 呼叫 facet 合約相對應的函式
fallback() external payable { address facet = selectorTofacet[msg.sig]; require(facet != address(0)); // Execute external function from facet using delegatecall and return any value. assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} }}
主要的差異在於變數的處理,OpenZepplin 是針對單一合約設計的代理合約(也就是每個合約都有自己的代理合約),所以無法處理單一代理合約儲存多個合約的變數(state variables)的狀況(後有圖例)。先由官方的範例程式來了解是怎麼處理變數的
在官方的範例中,都是以更改合約 owner 為例子
首先看到 DimaondStorage這個結構,結構中的前面三個變數都是在維持 diamond合約的運作(同上面loupe的範例),最後一個變數 contractOwner就是我們商業邏輯中所需的變數。
接著看到 function diamondStorage(),取變數的方式就跟OpenZeppelin 儲存特定變數方式一樣(EIP-1967),是把變數存到一個遠方不會跟其他變數碰撞到的位置,在這裡就是從 DIMOND_STORAGE_POSITION 這個 storage slot 讀取。
在實作上就可以有 LibDiamond1 ,宣告DIMOND_STORAGE_POSITION1=keccak256("diamond.standard.diamond.storage1") ,負責處理另一組的變數。藉由這種方式讓每個 facet合約有屬於自己合約的變數, facet合約間就不會互相影響。而最下方的 setContractOwner 是實際使用的範例。
library LibDiamond {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct FacetAddressAndSelectorPosition { address facetAddress; uint16 selectorPosition; }
struct DiamondStorage { mapping(bytes4 => FacetAddressAndSelectorPosition) facetAddressAndSelectorPosition; bytes4[] selectors; mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; }
function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } }
function setContractOwner(address _newOwner) internal { DiamondStorage storage ds = diamondStorage(); address previousOwner = ds.contractOwner; ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); }
每個 library 處理了一組或多組變數的存取, facet 合約透過 library 對變數做操作。也就是把變數存在diamond主體合約,延伸的 facet合約只處理邏輯,是透過 library 去操作變數。
下面圖中清楚地解釋了 facet合約,function selectors 與變數之間的關係,從最左上這邊有個 facets 的 map,紀錄了哪個 selector 在哪個合約中,例如func1, func2是 FacetA的函式。左下角宣告了變數,每組變數的存取如同上述 library 的方式處理。
https://eips.ethereum.org/EIPS/eip-2535#diagrams
在 diamond的設計中,每個 facet合約都是獨立的,因此可以重複使用(跟library 的概念一樣)
https://eips.ethereum.org/EIPS/eip-2535#diagrams
小結
diamond合約使用不同的設計來達成合約的可升級性,藉由這種Hub方式可隨時擴充/移除功能,讓合約不再受限於24KB的限制,此外充分的模組化,讓每次升級的範圍可以很小。最後,因為跟library一樣只處理邏輯,並無狀態儲存,所以可以重複被不同的diamond合約所使用。
雖然又不少好處,也是有些缺點。首先,術語名詞太多,facet, diamondCut, loupe等等(其實還有好幾個,不過沒有介紹到那些部分,所以沒有寫出來)。開發上不直覺,把變數跟邏輯拆開,若要再加上合約之間的繼承關係,容易搞混,不易維護。最後,gas的花費,在函式的讀取、呼叫,變數的存取、傳遞都會有不少的額外支出。Trail of Bits 專欄中有點出更多的缺陷 Good idea, bad design: How the Diamond standard falls short,不過作者也有反擊 Addressing Josselin Feist’s Concern’s of EIP-2535 Diamond Standard,有興趣的讀者可以自行看看、比較。
為了模組化及彈性,diamond合約在設計上有點太複雜(over engineering),會造成可讀性越差(這點也是Vyper誕生的原因之一),而可讀性越差就越容易產生bug、也越不容易抓到bug,而在defi專案中,一個小小的bug通常代表著大筆金額的損失 😱😱😱。
雖然如此,筆者還是覺得很酷,有些設計的思維仍然可以使用在自己的專案
ref:
EIP 2535
Diamond 實作
Addressing Josselin Feist’s Concern’s of EIP-2535 Diamond Standard
OpenZeppelin upgradeable contract
可升級合約介紹 - 鑽石合約(EIP-2535 Diamond standard) was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.
👏 歡迎轉載分享鼓掌
gas constant 在 Shiney Youtube 的最佳貼文
ซื้อเกมได้ที่ https://store.epicgames.com/legendauser/metro-last-light-redux
Metro Last Light Redux พากย์ไทย
Metro: Last Light takes place in 2034, one year after the events of Metro 2033, following the ending of the original novel in which Artyom's missile strike against the Dark Ones — mysterious beings that seemingly threatened the survivors of a nuclear war living in the Moscow Metro — occurred. The Rangers, a neutral peacekeeping force that operates throughout the system, have since occupied the D6 military facility Artyom visited during the first game. This is a huge, and not fully explored pre-war bunker, and Artyom, now a Ranger himself, remains unsure whether killing the Dark Ones was the correct decision. Rumors of D6's discovery and its great riches have spread around the Metro; rival factions, such as the Soviet Red Line and Nazi Fourth Reich, hope to seize the bunker and its contents.
Metro Redux is a post-apocalyptic first-person shooter, and a two-part remake of Metro 2033 and Metro Last Light for next-generation consoles. It was developed by 4A Games and published by Deep Sliver. The enhanced versions of both games can be bought together as a bundle or separately.
Metro Redux features remakes of both games in an improved 4A Engine. While Metro Last Light Redux includes general improvements, Metro 2033 Redux has been completely remade in the Last Light engine and updated to include the same features as Metro Last Light. Metro Redux has been released for the next-generation consoles, the Xbox One and PS4, as well as PC.
This game is based on Dmitry Glukhovsky's book Metro 2033.
In 2013, nuclear war had devastated the Earth, wiping out billions of lives. Among the affected nations is Russia, including the now-desolate wasteland of Moscow. A handful of survivors manage to hide in the Metro system, salvaging spare parts and growing mushrooms for food. Animals such as rats, bears, and others are mutated into horrific monsters, while the air in many areas that humans breathe becomes heavily irradiated and impossible to survive in without a gas mask. While there is a constant state of war between the Communists and the Nazis both trying to promote their radical ideologies, bandits are stealing, killing and looting in the metro tunnels, even keeping hostages to gain bullets, which are used as currency.
Twenty years later, in 2033, the northern station of VDNKh, now called Exhibition, falls under attack by a group of mysterious creatures referred to as the Dark Ones. Artyom (Russian: Артём), a 24-year-old male survivor born before the bombs fell and the adopted son of the station commander, is persuaded to leave his home there and seek help from the rest of the Metro by Hunter, an elite soldier of the Spartan Order. Hunter gives Artyom his dog tags and tells him to present them to his superiors in Polis, the "capital" of the Metro, before disappearing while tracking the Dark Ones.
gas constant 在 Shiney Youtube 的最佳解答
ซื้อเกมได้ที่ https://store.epicgames.com/legendauser/metro-exodus
Metro Last Light Redux พากย์ไทย
Metro: Last Light takes place in 2034, one year after the events of Metro 2033, following the ending of the original novel in which Artyom's missile strike against the Dark Ones — mysterious beings that seemingly threatened the survivors of a nuclear war living in the Moscow Metro — occurred. The Rangers, a neutral peacekeeping force that operates throughout the system, have since occupied the D6 military facility Artyom visited during the first game. This is a huge, and not fully explored pre-war bunker, and Artyom, now a Ranger himself, remains unsure whether killing the Dark Ones was the correct decision. Rumors of D6's discovery and its great riches have spread around the Metro; rival factions, such as the Soviet Red Line and Nazi Fourth Reich, hope to seize the bunker and its contents.
Metro Redux is a post-apocalyptic first-person shooter, and a two-part remake of Metro 2033 and Metro Last Light for next-generation consoles. It was developed by 4A Games and published by Deep Sliver. The enhanced versions of both games can be bought together as a bundle or separately.
Metro Redux features remakes of both games in an improved 4A Engine. While Metro Last Light Redux includes general improvements, Metro 2033 Redux has been completely remade in the Last Light engine and updated to include the same features as Metro Last Light. Metro Redux has been released for the next-generation consoles, the Xbox One and PS4, as well as PC.
This game is based on Dmitry Glukhovsky's book Metro 2033.
In 2013, nuclear war had devastated the Earth, wiping out billions of lives. Among the affected nations is Russia, including the now-desolate wasteland of Moscow. A handful of survivors manage to hide in the Metro system, salvaging spare parts and growing mushrooms for food. Animals such as rats, bears, and others are mutated into horrific monsters, while the air in many areas that humans breathe becomes heavily irradiated and impossible to survive in without a gas mask. While there is a constant state of war between the Communists and the Nazis both trying to promote their radical ideologies, bandits are stealing, killing and looting in the metro tunnels, even keeping hostages to gain bullets, which are used as currency.
Twenty years later, in 2033, the northern station of VDNKh, now called Exhibition, falls under attack by a group of mysterious creatures referred to as the Dark Ones. Artyom (Russian: Артём), a 24-year-old male survivor born before the bombs fell and the adopted son of the station commander, is persuaded to leave his home there and seek help from the rest of the Metro by Hunter, an elite soldier of the Spartan Order. Hunter gives Artyom his dog tags and tells him to present them to his superiors in Polis, the "capital" of the Metro, before disappearing while tracking the Dark Ones.
gas constant 在 Shiney Youtube 的最佳解答
Metro Last Light Redux พากย์ไทย
Metro: Last Light takes place in 2034, one year after the events of Metro 2033, following the ending of the original novel in which Artyom's missile strike against the Dark Ones — mysterious beings that seemingly threatened the survivors of a nuclear war living in the Moscow Metro — occurred. The Rangers, a neutral peacekeeping force that operates throughout the system, have since occupied the D6 military facility Artyom visited during the first game. This is a huge, and not fully explored pre-war bunker, and Artyom, now a Ranger himself, remains unsure whether killing the Dark Ones was the correct decision. Rumors of D6's discovery and its great riches have spread around the Metro; rival factions, such as the Soviet Red Line and Nazi Fourth Reich, hope to seize the bunker and its contents.
Metro Redux is a post-apocalyptic first-person shooter, and a two-part remake of Metro 2033 and Metro Last Light for next-generation consoles. It was developed by 4A Games and published by Deep Sliver. The enhanced versions of both games can be bought together as a bundle or separately.
Metro Redux features remakes of both games in an improved 4A Engine. While Metro Last Light Redux includes general improvements, Metro 2033 Redux has been completely remade in the Last Light engine and updated to include the same features as Metro Last Light. Metro Redux has been released for the next-generation consoles, the Xbox One and PS4, as well as PC.
This game is based on Dmitry Glukhovsky's book Metro 2033.
In 2013, nuclear war had devastated the Earth, wiping out billions of lives. Among the affected nations is Russia, including the now-desolate wasteland of Moscow. A handful of survivors manage to hide in the Metro system, salvaging spare parts and growing mushrooms for food. Animals such as rats, bears, and others are mutated into horrific monsters, while the air in many areas that humans breathe becomes heavily irradiated and impossible to survive in without a gas mask. While there is a constant state of war between the Communists and the Nazis both trying to promote their radical ideologies, bandits are stealing, killing and looting in the metro tunnels, even keeping hostages to gain bullets, which are used as currency.
Twenty years later, in 2033, the northern station of VDNKh, now called Exhibition, falls under attack by a group of mysterious creatures referred to as the Dark Ones. Artyom (Russian: Артём), a 24-year-old male survivor born before the bombs fell and the adopted son of the station commander, is persuaded to leave his home there and seek help from the rest of the Metro by Hunter, an elite soldier of the Spartan Order. Hunter gives Artyom his dog tags and tells him to present them to his superiors in Polis, the "capital" of the Metro, before disappearing while tracking the Dark Ones.
gas constant 在 MathType - Facebook 的推薦與評價
The gas constant “R” is defined as the Avogadro constant “NA“ multiplied by the Boltzmann constant “k”. It is mostly known for appearing in the ideal gas... ... <看更多>
gas constant 在 What is the physical significance of the universal gas constant ... 的推薦與評價
It may be helpful to look at a related value kB, the Boltzmann constant, which is widely used in thermodynamics. ... <看更多>
gas constant 在 Universal Gas Constant R - YouTube 的推薦與評價
... <看更多>