I was trying this tutorial that implements a simple DEX. I am specially interested in the non payable function sell, that exchange custom tokens for ETH.

function sell(uint256 amount) public {
    require(amount > 0, "You need to sell at least some tokens");
    uint256 allowance = token.allowance(msg.sender, address(this));
    require(allowance >= amount, "Check the token allowance");
    token.transferFrom(msg.sender, address(this), amount);
    emit Sold(amount);

It is always mandatory for the user to call the approve function of the ERC20 Smart Contract to be sold? Is there any way to do both steps (approve/sell) in a single transaction?

1 Answer 1


It is mandatory to invoke approve() for a contract if it uses transferFrom().

Some tokens support a special value of token.approve(spender, uint256(-1)) to indicate approval for every operation.

There's a draft EIP 2612 - permit – 712-signed approvals the introduces permit() which is a sort of approve that can be combined with transferFrom() in a single call. It is recent so not every token has support for it, Uniswap and Dai has something similar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.