Is there a way to use .call function to transfer ERC20 token?

46 Views Asked by At

I am using this function to transfer ERC20 token to target address in solidity.

IERC20(rewardToken).transfer(target, amountTo);

While compiling this, it was giving me warning below.

Warning!

So I've searched to use .call function instead of transfer. But it seems that transfer is being used only for ETH transfer. Any help? Thanks in advance!

I want something like this

(bool s,) = target.call(amountTo, IERC20(rewardToken));
1

There are 1 best solutions below

0
nikos fotiadis On

If you want to use .call you need to pass the call data yourself. This means encoding the function name and parameters of the function you are calling so that the EVM will know which function to call.

If you dont't send data the it will use the fallback function. You can see how to pass data here https://solidity-by-example.org/call/

Also note that in the code you have above (bool s,) = target.call(amountTo, IERC20(rewardToken)); the place where you are passing the amountTo is used for sending ETH, the token amount needs to be passed as parameter to the function you are calling in the encoded function data and not directly to the .call because .call knows nothing about ERC20s.

In your case it should be something like this

(bool success, bytes memory data) = rewardToken.call{
   value: msg.value,
   gas: 5000
}(abi.encodeWithSignature("transfer(address,uint256)", target, amountTo));

What this does is:

Encode the function data (abi.encodeWithSignature("transfer(address,uint256)", target, amountTo))

Send is to the contract with rewardToken.call. You may need to adjust the gas you are sending.