0

I created a contract that acts as my entry contract and gets an address for my second contract that would then call UniSwap exactInputSingle(). for the token that I'm sending to the first contract, I called the approved method of the ERC20 and gave approval to the first contract. in the first contract, I call

ERC20 myToken = ERC20(_tokenIn);
myToken.approve(market, _amountIn);

I was thinking that this would move the approve() from the first contract to the second contract. However, this is not working. How can I move the approval from one contract to a contract that the first contract is calling?

1
  • when you call approve, the msg.sender in the approve() is the smart contract itself, your entry contract.
    – Adam Boudj
    Dec 20, 2022 at 19:12

1 Answer 1

2

To move an approved ERC20 token from one contract to another, you can use the transferFrom function of the ERC20 contract.

The transferFrom function allows you to transfer tokens from one address (the from address) to another address (the to address) on behalf of the from address. This can be useful when you want to transfer tokens from one contract to another, but the contract does not have direct control over the tokens.

Here's how you can do it:

1️⃣ In your first contract, call the approve function of the ERC20 contract to give the first contract permission to transfer a certain amount of tokens on behalf of the owner. For example:

function transferTokens(address _to, uint256 _amount) public {
            ERC20 myToken = ERC20(_tokenIn);
            myToken.approve(address(this), _amount);
        }

2️⃣ In your second contract, call the transferFrom function of the ERC20 contract to transfer the approved tokens from the from address (the first contract) to the to address (the second contract). For example:

function receiveTokens(address _from, uint256 _amount) public {
    ERC20 myToken = ERC20(_tokenIn);
    myToken.transferFrom(_from, address(this), _amount);
}

3️⃣ In your first contract, call the receiveTokens function of the second contract to transfer the approved tokens to the second contract. For example:

function moveTokens(address _to, uint256 _amount) public {
    SecondContract sc = SecondContract(_to);
    sc.receiveTokens(address(this), _amount);
}

Keep in mind that the transferFrom function can only be called if the from address has previously given permission to the contract calling transferFrom by calling the approve function.

Your Answer

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

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