Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

blockchain - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...