- 添加Approval和TransferFrom功能
ERC-20標準中的approve和transferFrom是用於允許第三方(如智能合約)代表代幣持有者進行交易的功能,對於應用場景去中心化金融(DeFi)中的代幣托管與自動化交易很重要。
mapping(address => mapping(address => uint256)) public allowance;
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= balanceOf[_from], "Insufficient balance");
require(_value <= allowance[_from][msg.sender], "Allowance exceeded");
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
- SafeMath防止溢出問題
在Solidity中進行數學運算時,整數溢出問題可能導致安全漏洞,引入SafeMath可以防止溢出問題。
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract MyToken {
using SafeMath for uint256;
}