功能設計:
添加一個lockTokens函數來允許持有者設定鎖定期,修改transfer函數來檢查是否達到解鎖時間,若未達到則拒絕轉移。
pragma solidity ^0.8.0;
contract MyToken {
string public name = "My Token";
string public symbol = "MTK";
uint8 public decimals = 18;
uint256 public totalSupply;
address public owner;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
mapping(address => uint256) public lockTime; // 新增鎖定時間
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(uint256 _initialSupply) {
totalSupply = _initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply; // 初始化代幣
owner = msg.sender; // 設定合約擁有者
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value, "餘額不足");
require(block.timestamp > lockTime[msg.sender], "代幣被鎖定中");
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
// 設置鎖定時間
function lockTokens(uint256 _time) public {
lockTime[msg.sender] = _time;
}
}
測試與驗證: