以下是一种实现方法,其中使用了OpenZeppelin库:
pragma solidity ^0.5.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/token/ERC20/ERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/token/ERC20/ERC20Detailed.sol";
contract MyToken is ERC20, ERC20Detailed {
constructor(string memory name, string memory symbol, uint8 decimals)
ERC20Detailed(name, symbol, decimals)
public
{
}
}
function mintOnNthLike(uint256 n) public {
require(n > 0, "n should be greater than zero");
require(balanceOf(msg.sender) >= n, "sender's balance is not enough");
// Check if the balance is divisible by n
if (balanceOf(msg.sender) % n == 0) {
// Mint 1 token
_mint(msg.sender, 1);
emit Transfer(address(0), msg.sender, 1);
}
}
MyToken token = new MyToken("My Token", "MT", 18);
token.mintOnNthLike(10); // 铸造ERC-token,每10个相似数字一个
上述代码将在每个账户的第N个相似数字上铸造1个ERC-token。该铸造功能在所有Solidity合约中都适用。