简体   繁体   中英

ehtereum smart contract approve spender from another contract

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.

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

Can you please tell me how you eventually solved this problem? Im needing this for a really nice project. If you want you could even join in on it. You can also reach me disc here Viveraah#5948

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM