0
votes

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.

1

1 Answers

2
votes

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);
}