Solidity

如何在隨機鑄造 ERC721 NFT 時跟踪已經鑄造的 NFT?

  • August 31, 2022

我正在研究 ERC721 代幣的隨機鑄造……我正在使用 Chainlink VRF 進行隨機化。

我的困惑是如何跟踪已經鑄造的 NFT…因為 VRF 可以生成已經鑄造的數字(NFT ID)…一種選擇是使用 while 循環或使用數組這太貴了

請問還有其他優化的解決方案嗎???

設置這樣的東西有點貴,但鑄幣很便宜,所以我認為這符合你想做的事情。

它不是跟踪已經鑄造的內容,而是保留一組尚未鑄造的 ID 並從中進行選擇。隨著 NFT 的鑄造,該集合變得更小。

   pragma solidity ^0.8.7

   import "hardhat/console.sol";

   contract RandomMints {

   uint[] notMinted;

   function createSet() external {
       // this is a bit expensive but a one off
       // txn gas 2282618 in remix
       for(uint i; i < 100; ++i){
           notMinted.push(i);
       }
   }

   function pickId() external returns (uint) {
       // txn gas 37430 in remix
       uint numLeft = notMinted.length;
       console.log("num of NFTs not minted:", numLeft);

       // pick a number between 0 - num of unminted NFTs -1
       uint rand = block.timestamp % (numLeft - 1);  //not really random
       uint idSelected = notMinted[rand];

       // now reduce the set. it doesn't matter if we mix up the order as it adds more entropy
       // get rid of the picked id by overwriting it with the last id/element
       notMinted[rand] = notMinted[numLeft -1];
       // pop the last (now duplicated) id/element off the array
       notMinted.pop();

       console.log("id selected:", idSelected);
       return idSelected;
   }
}

引用自:https://ethereum.stackexchange.com/questions/134618