简体   繁体   English

如何随机铸造一个 static 数量的 NFT?

[英]How to random mint a static number of NFT?

I'd like to mint these amount of tokens:我想铸造这些数量的代币:

200 super 300 rare 500 common 200 超 300 稀有 500 普通

But the mint process needs to be random, you can get a (super, rare, or common) but at the end of the process, it should be minted the same amount of 200 super, 300 rare, and 500 common.但是铸造过程需要是随机的,你可以得到一个(超级、稀有或普通),但在过程结束时,应该铸造相同数量的 200 超级、300 稀有和 500 普通。

The following code does the random but the final amount of tokens will be different from the beginning:以下代码是随机的,但最终的令牌数量将与一开始不同:

  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;
    }

First don't use block.timestamp or any block or blockchain data as a source of randomness, because it will cause the "randomness" be predictable or possible to be manipulated by minners, try with chainlink as a source of randomness, they have a good examples in their docs, if you want to have a fixed supply of each type of tokens you can have 3 variables to know how much of each one have been minted, and when you got the random number and all that you need you just need to apply some math, in this case you want the tokens to be 20% of super, 30% of rare and 50% of common, you only have to do the math you need to decide wich one will be minted, and in case of that type has already reach is max supply what will happend?首先不要使用 block.timestamp 或任何区块或区块链数据作为随机性来源,因为它会导致“随机性”可预测或可能被矿工操纵,尝试使用 chainlink 作为随机性来源,他们有他们的文档中有很好的例子,如果你想固定供应每种类型的代币,你可以有 3 个变量来了解每种代币的铸造量,以及何时获得随机数和你需要的所有东西应用一些数学运算,在这种情况下,您希望代币是超级代币的 20%,稀有代币 30% 和普通代币 50%,您只需要进行数学运算来决定将铸造哪个代币,以防万一该类型已经达到最大供应量会发生什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM