【Solidity】Lock 锁
锁在开发产品的过程中还是比较常会用到,例如特定的时间段内不能进行交易,等到特定的时间之后才能继续进行交易。也可以根据特定的账户加锁,加锁了之后就无法再交易。
代码范例
- 代币发行者上错上锁,继承了openzeppelin ownable判断是否是发行者,无需写而外的代码。
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract TimeLock is ERC20, Ownable { bool isLock = false; constructor() ERC20("testCoin", "TSC") { //初始发行10万代币,然后打入作者的户口中 _mint(msg.sender, 100000 * 10 ** decimals()); } function setLock()public onlyOwner returns(bool){ //只有合作发行者才能够把合作封锁 isLock = true; return true; } function transfer(address _to, uint256 _amount) public override returns(bool){ //如果发现锁着了就会报错 require(isLock==false,"Contact was lock!"); return super.transfer(_to,_amount); } }
2. 一分钟内只能发行一次交易
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract TimeLock is ERC20, Ownable { bool isLock = false; /** 1 == 1 seconds 1 minutes == 60 seconds 1 hours == 60 minutes 1 days == 24 hours 1 weeks == 7 days */ uint public timeLock = block.timestamp; constructor() ERC20("testCoin", "TSC") { //初始发行10万代币,然后打入作者的户口中 _mint(msg.sender, 100000 * 10 ** decimals()); } function transfer(address _to, uint256 _amount) public override returns(bool){ //一分钟只能交易一次,否则就报错 require(block.timestamp > timeLock,"It's not time yet"); bool success = super.transfer(_to,_amount); timeLock = block.timestamp + 1 minutes; return success; } }
3. 代币发行者能够设定任何的地址为黑名单,所以黑名单户口当中的代币将无法转账给其他户口。
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract BlacklistLock is ERC20, Ownable { mapping(address=>uint8) blacklistAccount; constructor() ERC20("testCoin", "TSC") { //初始发行10万代币,然后打入作者的户口中 _mint(msg.sender, 100000 * 10 ** decimals()); } function setBlackList(address _address)public onlyOwner{ //发行者无法把自己的地址给黑名单掉 require(_address!=owner(),"cannot blacklist owner address"); blacklistAccount[_address] = 1; } function removeBlackList(address _address)public onlyOwner{ //发行者无法把自己的地址给黑名单掉 require(_address!=owner(),"cannot remove blacklist owner address"); delete blacklistAccount[_address]; } function transfer(address _to, uint256 _amount) public override returns(bool){ //黑名单就无法转账 require(blacklistAccount[msg.sender]==0,"your account is blacklisted"); bool success = super.transfer(_to,_amount); return success; } }
Facebook评论