如何随机铸造一个静态数量的NFT



我想铸造这些数量的代币:

200超级300稀有500普通

但铸造过程需要是随机的,你可以得到一个(超级、稀有或普通(,但在过程结束时,它应该铸造相同数量的200个超级、300个稀有和500个普通。

以下代码进行随机操作,但代币的最终数量将与开始时不同:

function safeMint(address to) public onlyOwner {
require(_tokenIdCounter.current() < totalSupply(), "There's no token to mint.");
require(mintCnt[msg.sender] < maxMintCntPerAddress, "One address can mint 1 tickets.");
if(mintPrice > 0) {
require(mintPrice == msg.value, "Mint price is not correct.");
address payable _to = payable(serviceAddress);
_to.transfer(mintPrice);
}
uint randomNumber = random(expectedTokenSupply - _tokenIdCounter.current());
for (uint256 i = 0; i < _tokenMetadata.length; i++) {
if(_tokenMetadata[i].amount <= randomNumber) {
_safeMint(to, _tokenIdCounter.current());
_setTokenURI(_tokenIdCounter.current(), _tokenMetadata[i].uri);
_tokenIdCounter.increment();
break;
}
}
}
function random(uint maxValue) internal returns (uint) {
return uint(keccak256(abi.encodePacked(block.timestamp, msg.sender, _tokenIdCounter.current()))) % maxValue;
}

首先不要使用block.timestamp或任何块或区块链数据作为随机性的来源,因为这会导致"随机性";可以预测或可能被minner操纵,尝试将chainlink作为随机性的来源,他们的文档中有一个很好的例子,如果你想固定供应每种类型的代币,你可以有3个变量来知道每种代币的铸造量,当你得到随机数和所有你需要的东西时,你只需要应用一些数学,在这种情况下,你希望代币是20%的超级代币,30%的稀有代币和50%的普通代币,你只需要做你需要的数学运算,就可以决定铸造哪一个,如果这种类型的代币已经达到最大供应量,会发生什么?

相关内容

最新更新