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.
approve
, themsg.sender
in theapprove()
is the smart contract itself, your entry contract.