[Ethereum] Metamask shows “ALERT: Transaction Error. Exception thrown in contract code” but transaction succeeds without error

defisolidity

I'm working on a dapp . and metamask show me error Metamask shows “ALERT: Transaction Error. Exception thrown in contract code” . I have successfully deployed the contract and the error come when i try to stake the token that are allowed and stored in the allow token array

address[] allowedTokens;

modifier tokenAllowed(address _token) {
        require(tokenIsAllowed(_token));
        _;
    }

    function tokenIsAllowed(address token) public view returns (bool) {
        for(uint256 i=0; i < allowedTokens.length; i++){
            if(allowedTokens[i] == token){
                return true;
            }
        }

        return false;
    }

function stakeTokens(uint256 _amount, address token, StakingTime _time) public tokenAllowed(token){
        // Require amount greater than 0
        require(_amount > 0, "amount cannot be 0");
        IERC20(token).transferFrom(msg.sender, address(this), _amount);
        setTime(msg.sender, token, _time);
        uint256 fees = _amount / 100;
        _amount = _amount - fees;
        stakingBalance[token][msg.sender] = stakingBalance[token][msg.sender] + _amount;
        userStakes[token][msg.sender] = StakingSubmission(msg.sender, token, _amount, _time);
        emit Staking(msg.sender, token, _amount, _time);
    }

Best Answer

Metamask shows “ALERT: Transaction Error. Exception thrown in contract code” but transaction succeeds without error

It's likely that Metamask's pre-flight check is failing for some reason, rather than the actual transaction.

Before submitting your transaction, Metamask runs a "dummy" transaction to check the probable outcome. From experience, this can sometimes be misleading. (Though in your case I can't see why it would be complaining - someone else might know better.)


More importantly, your stakeTokens() function code looks like it could contain a reentrancy vulnerability. See Known Attacks: Reentrancy.

Related Topic