简体   繁体   中英

Solidity Transaction Issue

i'm facing some weird issues, or well, things i'm not understanding. I'm still pretty new with solidity tho, anyway, i'm trying to create a staking contract, based on an ERC20 token i created. I call the stake function with ethers.js and pass the amount with it. The staking contract saves some info and forwards receiver address and amount to the ERC20 transfer function.

async function stake () {
  await stakeContract.stake(1);
}


function stake (uint256 _amount) public {
     require(_amount > 0, "You must stake more than 0");
     require(_amount < ercToken.balanceOf(msg.sender), "The amount exceeds your balance");
     addressToStaked[msg.sender].push(Stakes(block.timestamp, _amount));
     totalStakes[msg.sender] += 1;
     ercToken.transfer(address(ercToken), _amount);
}

The transfer function then forwards the data to the internal _transfer function shown below. The problem is that, even if i do have enough tokens in my wallet, the _transfer function still fails with error: Amount exceeds balance.

I've double checked the mapping saving the balance and it works.

function _transfer(
    address from,
    address to,
    uint256 amount
) internal virtual {
    require(from != address(0), "ERC20: transfer from the zero address");
    require(to != address(0), "ERC20: transfer to the zero address");

    _beforeTokenTransfer(from, to, amount);

    uint256 fromBalance = _balances[from];
    require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
    unchecked {
        _balances[from] = fromBalance - amount;
        _balances[to] += amount;
    }

    emit Transfer(from, to, amount);

    _afterTokenTransfer(from, to, amount);
}

It seems you made a mistake on this line of the staking contract.

function stake (uint256 _amount) public {
     ...
     ercToken.transfer(address(ercToken), _amount);
}

The above line means, transfer "_amount" token to "ercToken" address from staking contract. So there should be some amounts ( >_amount ) of tokens on staking contract. But as you mentioned, you only have enough tokens on your wallet, not on staking contract.

Plz use "transferFrom" function or "safeTransferFrom" function of "SafeERC20" library to solve the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM