0

if my farm contract has a staking function, do I need to call approve before calling transferFrom?

Sample function:

StakeToken stakingToken;
...
function depositTokens(uint256 amount) public {
    require(amount > 0, "Must be more than 0");
    //Do I need to call stakingToken.approve(...) here?
    stakingToken.transferFrom(msg.sender, address(this), amount);

Is this needed because the farm contract must be approved to make the transfer on the msg.sender's behalf?

code_learner93
  • 571
  • 5
  • 12
  • https://stackoverflow.com/questions/48664570/what-approve-and-allowance-methods-are-really-doing-in-erc20-standard/68820999#68820999 – Yilmaz Jun 18 '22 at 21:52

1 Answers1

2

The approve() is needed, but you cannot call it from within your contract. The user needs to call it directly from their address.

So transfering tokens from the user effectively requires two transactions. First one to token.approve() and the second to yourContract.depositTokens().

Reasoning: The token contract approves spending msg.sender's tokens to the address specified in the approve() function first argument. With that said, when you invoke token.approve() from your contract, the msg.sender within the approve() function is your contract - not the user. So in that case, you would be approving tokens to be spent from your contract to whichever address is passed as the argument.

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100