0
votes

I am trying to send ERC20 tokens from a contract to an account . This is the code that I have

IERC20 testToken = IERC20(tokenAddress);
testToken.transfer(accountAddress,amount);

The function to intitate the trasfer should ideally be called by someone else, lets call him "C" So

msg.sender != accountAddress
  • Is there a way I can make the msg.sender for the transfer function to be the contract itself instead of "C" ?

  • Also this function somehow works if I i call it from the account address ,i.e when msg.sender == accountAddress . How does that happen ,in this case the from and to fields should both be the same ,and no change in balance should happen ?

1
As written, your contract will transfer its own testToken to accountAddress, no matter who calls it. That sounds like what you want : "I am trying to send ERC20 tokens from a contract to an account". no ?SimonR
Yeah That is what I want , but if its a third person calling this smart contract , the transfer does not happen .Tanmay Bhattacharya
So you wanna transfer the token from smart contract -> msg.sender?tpikachu

1 Answers

2
votes

You'll need the transferFrom function and not transfer. The transfer function automatically uses the msg.sender as a parameter. You will also have to have that address have allowance of the tokens to transfer. The approve method takes care of this. Assuming that is all set, here is the code.

 IERC20 tcontract = IERC20(tokenAddress);
    require(tcontract.transferFrom(address(this), msg.sender, amount), "Don't have enough balance");