Solidity ERC-20 – How is Approved Called from MetaMask When Transferring ERC20 Tokens

erc-20metamasksolidity

we have a game that requires the user to transfer an ERC20 from a browser to a contract address, in unit tests approve() needs to be called from user side to enable an erc20 transfer to an address, How should this work in broweser connected to metamask?
will the frontend call approve() first and then transfer() so its two transactions?
Is there a way to detect if the receiver address already has access/approved for transfer from smart contract or solidity side so we can just put the approve() in a condition and not call approve() everytime?

Best Answer

You can start with checking the allowance for your spender by the owner.

function allowance(address owner, address spender) public returns uint256;

If the allowance is below your requirement, you'll need to first perform a approve transaction. And then do the transferFrom. If you do this as two separate transactions, it'll open up the MetaMask twice and the users will have to authorise 2 transactions separately.

We could have used multi-call contract to combine these calls inside a single transaction but most approve function implementations works based on msg.sender.

ERC-777 tries to fix this by requiring a single transaction to effectively perform the equivalent of approve and transferFrom. You can check out more about ERC-777 here.

Related Topic