"jsonrpc":"2.0","error":"execution reverted" in getPrice function

1.2k views Asked by At

make 1NFT free -> after nft per .0022 sale function

so I made this get price function,

function getPrice(address _sender,uint256 _quantity) public view returns (uint256){
    uint256 _userFreeAmount = maxFree.sub(_numberMinted(_sender)); //can free 
    if (_userFreeAmount<=0){ 
        return price.mul(_quantity);//error
    }else if(_quantity.sub(_userFreeAmount)<=0){
         return 0;
    }else{
        return price.mul(_quantity.sub(_userFreeAmount));
    }
}

and it make rpc error in this case -> "if (_userFreeAmount<=0)"

and my mint function on front is this

const mint = async () => {
    let myProvider = web3.currentProvider;
    let networkCheck = myProvider.networkVersion == null ? myProvider.chainId : myProvider.networkVersion;
    if (networkCheck == CHAINID) {
        if (contract && account) {
            const quantity = parseInt($('.supply').text());
            try {
                const price = await contract.methods.getPrice(account,quantity).call();
                await contract.methods.publicMint(quantity).send({ from: account, value: price});
                $.statusSection.init("minting success.");
            } catch (error) {
                alert(error.name);
                alert(error.message)
            }
        }
    } else {
        await switchNetwork();
        location.reload();
    }
}

how can i fix it?

1

There are 1 answers

0
Allen Wong On

At

uint256 _userFreeAmount = maxFree.sub(_numberMinted(_sender));

It is possible that result would be negative number. uint256 is not used for negative number, thats why rpc reverts when underflow happen. You can use int256 instead.

Arithmetic operations revert on underflow and overflow. You can use unchecked { ... } to use the previous wrapping behaviour.

See Solidity v0.8.0 Breaking Changes