-1

I know this question has been asked too frequently. I apologise, but I did not understand much of the answers. I've been trying to create a Staking Contract but this error has stumped me. This is not the stake function code itself, just the transferring part. This is the code:

   function stake(uint256 _amount) public {
        stakingToken.transferFrom(msg.sender, address(this), _amount);
        stakingToken.approve(msg.sender, _amount);
    }

This is the error:

The transaction has been reverted to the initial state.
Reason provided by the contract: "ERC20: insufficient allowance".
Debug the transaction to get more information.

I've tried putting the approve function first and the TransferFrom last. Ive tried using the Transfer function but all have came up with the same exact error.

I've also increased my gas limit to 12000000, I've tried to add ether too, but nothing has worked.

I apologise if this question bothers you, I'm just foraging for an informative answer that will solve my issue.

May you reach the stars.

1 Answers1

1

The issue is putting the approve function within the stake function:

stakingToken.approve(msg.sender, _amount);

Here's the control flow to illustrate:

     stake()                  approve()
user   -->   staking contract    -->   staking token

From the staking token's perspective, the approve call is the staking contract allowing the user to spend the staking contract's tokens.

But what we wanted is the opposite: the user to allow the staking contract to spend the user's tokens.

Solution: to do the desired transfer, you must have a two separate transactions:

  1. The user calls approve directly on the staking token to allow the staking contract to spend the user's tokens.
     approve()
user    -->   staking token
  1. The user calls stake, which transfers the token from the user to the staking contract.
     stake()
user   -->   staking contract
ardislu
  • 36
  • 1
  • 3