I understand that an ERC20's approve() function has to be run before the token can be sent to another contract. But is this a one-time approval for msg.sender to be granted an approval status or does it need to be executed before each relevant transaction?
3 Answers
It's common for dApps that interact with tokens to specify the maximum uint256
value as allowance (2^256 - 1 or 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
), in which case you only need to run it once basically. The advantage is that the user won't have to constantly send two transactions, but the disadvantage is that there could be some kind of vulnerability in your contract, allowing someone to transfer all user's tokens. It's a trade-off between user exprience and security.
You only have to run it if there is not enough allowance for a given transaction to succeed. If you approve an amount say 100,000 XYZ tokens to a spender then you do not have to call approve
again until the spender the spent 100,000 XYZ tokens.
-
I find this helpful because it seems to clarify my sub-question: "if the user approves 100 tokens, they can send 2 transactions of 50 tokens but not a third transaction of 1 token". Jan 2 at 4:51
for getting unlimited Approval for ERC20 token (web3.js)
let approve_amount = '115792089237316195423570985008687907853269984665640564039457584007913129639935'; //(2^256 - 1 )
await ERC20tokenContractObj.methods.approve("SPENDER CONTRACT ADDRESS", approve_amount).send({from:ethereum.selectedAddress});
-
1It depends on the contract, some contracts do not support such feature.– Ismael ♦Sep 2, 2021 at 6:09