approve is required in ERC20 for a Dex?

Viewed 455

According to the take advantage function, it is used to use your tokens in an external contract based on the permissions and the amount that you indicate

But: When implementing an ERC20 is it necessary to implement approve? To use it on a Dex? With the ethereum fees high enough to make a simple swap. If I don't implement it, what can happen?

2 Answers

The approve function allows an external address to spend tokens from a specific address on its behalf. If you do not implement it, then transferFrom function will not work, since you always need to approve the token usage for an specific spender. Thus, the only way to transfer tokens will be calling the function 'transfer', which won't be accepted by a DEX. DEXes use the transferFrom function in order to interact with an address’s tokens on its behalf.

Let's say Dex contract has a staking functionality:

function stakeTokens(uint256 _amount,address _token) public{
        require(_amount>0,"Amount must be more than 0");
    
        /*call transferFrom from erc20. transfer only works if it is being called from the wallet who owns the tokens. If we dont own the token we use transferFrom. We have to have abi to call the transferFrom. so we need IERC20 interface*/
        // In order to interact with a contract we need abi
        // IERC20(_token) initilaizes the contract
        IERC20(_token).transferFrom(msg.sender,address(this),_amount);
       // ... more logic down here
    }

approve is used to authorize the DEX to make transfers on behalf of the token owner up to the approved amount. How DEX contract will withdraw from your contract? You have to first give permission with approve

Related