when a user approves a spender to spend tokens on his behalf via the approve function, how does the spender transfer these tokens? Also how can the spender access other tokens in the wallet? Does the spender have to call the approve function for each erc20 token?? Is it possible to use the transfer from function for native assets like ETH?
1 Answer
How does the spender transfer these tokens?
They can use the transferFrom(from, to, amount)
function. Lets assume we have addresses A and B. If A has approved B to use an amount X then B can call transferFrom(A, anyAddress, X or less than X)
.
Also how can the spender access other tokens in the wallet?
If you are referring to other token Standards they work in a similar manner. Each one has its own "approve" function though. For example ERC721 has approve(to, tokenId)
and setApprovalForAll(operator, _approved)
. The first approves an address to transfer a specific token with tokenId and the latter approves all tokens to be transferred by the operator address. Both of these methods are called by the owner of the tokens. Similarly ERC1155 has the setApprovalForAll(operator, _approved)
method.
Does the spender have to call the approve function for each erc20 token?
An ERC20 contract has a total supply. Addresses owning ERC20 tokens own some or all of that supply. The contract holds the balances of everyone that owns any amount of tokens. When someone approves their tokens to be used by another address, they do so by providing an amount. They don't have to do it one by one but it is possible, although not practical. For example if address A has 2000 tokens and wants to approve B to use 1000 of them, A can call approve(B, 1000)
. Then B is authorized to transfer to any address 1000 tokens of A's balance.
Is it possible to use the transfer from function for native assets like ETH?
A smart contract called WETH has been created for that exact purpose. You can check how it works here
A very good resource to study in detail all of the above functions mentioned, is the documentation provided by OpenZeppelin.
-
Thank you for the response, it was quite informative. Concerning the WETH....if i use this smart contract in my project, do i still need my users to wrap their ETH before interacting with my DAPP or this process happens automatically? Commented Jun 8, 2022 at 10:46
-
Most networks already have a WETH contract deployed to them. If you are working on a private network you made, you can deploy one for your chain. Once that is done the way to obtain WETH is simple. You just send ETH to the contract and it automatically registers in your WETH balance in the contract. After that, WETH can be used like an ERC20 token and can always be converted back to ETH. Commented Jun 8, 2022 at 11:20