Allowance
means that we can grant approval to another contract or address to be able to transfer our ERC20 tokens. And this requirement is common in distributed applications, such as escrows, games, auctions, etc. Hence, we need a way to approve other addresses to spend our tokens. Let's say you have tether
contract and you want a DEX(Decentralized Exchange) or any other entity transfer coins from the tether
contract. So you keep track of which entity how much can transfer from tether contract in a mapping.
// my address is allowing your address for this much token
mapping(address=>mapping(address=>uint)) public allowance;
In the ERC20 standard, we have a global variable allowed
in which we keep the mapping from an "owner's address" to an "approved spender’s" address and then to the amount of tokens. Calling approve()
function can add an approval to its desired _spender
and _value
. The amount of token is not checked here and it will be checked in transfer().
Once the approval is granted, the "approved spender" can use transferFrom()
to transfer tokens. _from
is the owner address and _to
is the receiver’s address and _value
is the required number of tokens to be sent. First, we check if the owner actually possesses the required number of tokens.
假设您想向一个DEFI平台存入一些以太币。与DEFI平台交互实际上是与该平台的智能合约进行交互。在存款之前,您首先需要批准交易。这意味着您告诉该合约地址可以从我的账户中取出一些钱。然后,您调用DEFI智能合约的
deposit
函数并存入资金。以下是转移发生的顺序:
1- 在Defi内部,defi智能合约有
deposit
来获取
tether
代币。
function depositTokens(uint _amount) public{
require(_amount>0,'amount cannot be zero');
tether.transferFrom(msg.sender,address(this), _amount);
}
2- 在tether
内部,我们有transferFrom
mapping(address=>mapping(address=>uint)) public allowance;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){
require(_value <=allowance[_from][msg.sender]);
balanceOf[_to]+=_value;
balanceOf[_from]-=_value;
allowance[_from][msg.sender]-=_value;
emit Transfer(_from,_to,_value);
return true;
}
首先需要检查“津贴(allowance)”:mapping(address=>mapping(address=>uint)) public allowance
。所以在调用transferFrom
之前,tether
合约必须更新其allowance
映射,以使此过程顺利运行。
3- 使用approve
更新津贴:
function approve(address _spender, uint _value)public returns (bool success){
allowance[msg.sender][_spender]=_value;
emit Approval(msg.sender,_spender,_value);
return true;
}