Solidity | ERC20 中 transfer 和 transferFrom 的区别

255 阅读1分钟

Difference between transfer and transfer-from

the declarations:

function transfer(address to, uint256 amount) external returns (bool);
function transferFrom( address from, address to, uint256 amount ) external returns (bool);

and the common member variables:

mapping(address account => uint256) private balances; // easy to understanding

// uint256 amount = allowance[A][B], means that
// B can transfer `amount` of token from A's balance  to another one,
// will reduce the allowance[A][B] each time the same amount that transfered
mapping(address account => mapping(address spender => uint256)) private allowances;

address msg_sender; // just who call the contracts function.

Assume that I'm the B , want to transfer tokens to C.

If I call the contract.transfer(C, 1)

It means that reduce my(A) balance and add C's balance:

address B = msg.sender; // me
address C = to;
balances[B] -=1;
balance[C] +=1;

If I call the contract.transferFrom(A, C, 1)

It means that I will use the allowance that A approve to me, then direct transfer tokens from A to C:

address B = msg.sender; // me
address C = to;
address A = from; 
allowance[A][B] -=1;
balance[A]-=1;
balacne[C]+=1;