2

I have a erc20 token and in another contract I want to create a token swap function. So very easily, one send a usdc token and swap my erc20 token in 1:1 ratio. Problem is how to approve to spend my erc20 token. I tried several times but can't find a way.

interface IERC20 {...} 

contract AnotherContract {

function approve(address _spender, uint256 _amount) public returns(bool) {
    return IERC20(MyToken).approve(_spender, _amount);
}

I deployed this another contract and when I call approve function from it. So When I set '_spender' to this contract address. The result is weird. So this contract is owner and spender both.. As I think a user should be as a owner and this contract should be a spender. But function calling from onchain. the msg.sender is going to be this contract address self.

I don't understand and am confusing. anybody knows or have some rescoures? Thank you.

sung chul
  • 39
  • 1
  • 7

1 Answers1

5

When your AnotherContract executes the approve() function in MyToken, the msg.sender in MyToken is AnotherContract - not the original transaction sender.

Which effectively approves AnotherContract's tokens to be spent by _spender.


Unless the MyToken has a way to delegate the approval (e.g. by using a deprecated tx.origin instead of msg.sender, which introdues a security flaw), the user will have to execute the approval manually, and not through your external contract.

Many ERC-20 implementations use this approach for security purposes. For example to prevent a situation, where a scammer would persuade a user to execute their malicious function, because the user would think they are getting an airdrop.

// function name suggests that the caller is going to receive an airdrop
function claimAirdrop() external {
     /*
      * fortunately, this won't work
      * and the tx sender can't approve the scammer to spend their tokens this way
      */
    USDTcontract.approve(scammer, 1000000);
}
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
  • 2
    Thank you~. To be honest I don't understand the smart contract logics well now. I solved my problem like one time request an approve outside of the contract and request a transaction to spend user token (in allowances). – sung chul May 06 '21 at 05:07
  • @Seong how did you do it? Can you a example code? – Crazy Nov 03 '21 at 09:03
  • @seongcheolryu how did you do it? Can you a example code? – YNX Jan 06 '22 at 12:25