[Ethereum] Whats the proper pattern for calling approve() function from ERC20

solidity

Lets say I'm trying to write some kind of exchange or escrow smart contract that handles transferring tokens for users.

I see that ERC20 tokens implement the approve function something like below:

    function approve(address delegate, uint256 numTokens) public override returns (bool) {

        allowed[msg.sender][delegate] = numTokens;

        emit Approval(msg.sender, delegate, numTokens);

        return true;

    }

With the main point that approved account is msg.sender NOT tx.origin. So if I am writing a separate smart contract that tries to call the approve function of this ERC20 token:

function handleApproval(IERC20 token, uint256 numTokens) public override returns(bool){
    IERC20.approve(address(this), numTokens);
}

This would not work as intended since it would only be doing allowed[CONTRACT_ADDRESS][CONTRACT_ADDRESS] = numTokens, since the sender of the message is my smart contract.

My question is what is the proper pattern for exchanges/escrows to get users to approve the smart contract for handling transfers? Are users supposed to have to call the approve() function of the ERC20 contract directly themselves?

Best Answer

Yes, the users have to call the approve function "themselves". (Otherwise, you would just be able to approve anything you want :) )

But they don't have to do that manually - usually how it works is that your front end website will issue for the user two transactions to sign - one for approving the ERC20, and one for executing your smart contract function.

Related Topic