PatrickAlphaC / defi-stake-yield-brownie-freecode

53 stars 63 forks source link

Error : Reason provided by the contract: "ERC20: transfer amount exceeds allowance". #2

Closed PGCodehub closed 2 years ago

PGCodehub commented 2 years ago

Hi , @PatrickAlphaC

I have deployed a token farm contact and try to stake the custom token , I am getting this error

Reason provided by the contract: "ERC20: transfer amount exceeds allowance". But I have the tokens In that address , minted when deploying the token from same address

I am just learning all this , I try to approve the token receiver address, increase the allowance in the token address, not this is working

Please help me with this

Thank you

PatrickAlphaC commented 2 years ago

What are you using to approve?

PGCodehub commented 2 years ago

HI

I am using this

 IERC20(_token).approve(msg.sender, _amount);

The code of function would be


function stakeTokens(uint256 _amount, address _token) public {

        require(_amount > 0, "Amount must be more than 0");
        require(tokenIsAllowed(_token), "Token is currently no allowed");

        IERC20(_token).approve(msg.sender, _amount);        

        IERC20(_token).transferFrom(msg.sender, address(this), _amount);
        updateUniqueTokensStaked(msg.sender, _token);
        stakingBalance[_token][msg.sender] = stakingBalance[_token][msg.sender] + _amount;
        if (uniqueTokensStaked[msg.sender] == 1){
            stakers.push(msg.sender);
        }
    }

debugger is saying I am saying the problem was at line IERC20(_token).transferFrom(msg.sender, address(this), _amount);

But when i got to token contract and increase the allowance it is working , but not from tokenfarm , i might be missing something silly here , please do let me know

Thanks
PatrickAlphaC commented 2 years ago

You can't call the approve function from inside your contract. You have to call it outside your contract. The caller of approve has to be the owner of the token. When you call stakeTokens, the contract calls approve instead of your wallet who owns the tokens.

Make sense?

You -> call stakeTokens -> calls approve

vs.

you -> call approve

It has to be the 2nd, where you call approve. Not you call the contract which calls approve.

You'd have to call approve outside the contract.

PGCodehub commented 2 years ago

Yes , Thank you , makes sense , i thought we might be able to call this approval from contract itself, it seems we have to interact with both token and token farm contract

I want to thank you for creating the amazing course on solidity, it was easy to understand and intuitive