这是困扰我很久的问题,这里做一个解答。
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| contract ERC20 is IERC20{
mapping(address => uint256) public override balanceOf;
mapping(address => mapping(address => uint256)) public override allowance;
uint256 public override totalSupply;
string public name; string public symbol;
uint8 public decimals = 18;
constructor(string memory name_, string memory symbol_){ name = name_; symbol = symbol_; }
function transfer(address to, uint amount) external override returns (bool) { balanceOf[msg.sender] -= amount; balanceOf[to] += amount; emit Transfer(msg.sender, to, amount); return true; }
function approve(address spender, uint amount) external override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; }
function transferFrom( address sender, address recipient, uint amount ) external override returns (bool) { allowance[sender][msg.sender] -= amount; balanceOf[sender] -= amount; balanceOf[recipient] += amount; emit Transfer(sender, recipient, amount); return true; }
}
|
只看代码的话,感觉 transfer
和 transferFrom
没有一点区别。
上面的代码只是一个简单的说明,不能用于生产环境。
其实是这样的,transfer
是自己调用,transferFrom
是别人调用。
A
账号有10000
个token
代币,B
账号没有token
代币,C
账号也没有token
代币!
A
账号 委托 B
账号 转给C
账号 100
个token
代币 怎么来实现呢?
A
账号 和 B
账号建立一种委托关联,登录A
账户执行approve(b,100)
方法结果为:结果:allowance[A][B] = 100token
- 在执行登录
B
账户执行transferFrom(A,C,100)
,这里的B就是委托账号发送者,gas
从B
扣,必须确保token
数量小于allowance[A][B]
- 其实就是
A
转入C
,但是要经过B的账号来发送交易!