0

If I have any 'require' statement in function, how can I display the error as an alert in frontend before the transaction is submitted ? For eg, ERC20 token contract, my HTML form is :

<div class="form-group col-md-2">
    <input  type="text" id="transfer_param1" placeholder="Transfer To">
    </div>

    <div class="form-group col-md-2">
    <input  type="text" id="transfer_param2" placeholder="Amount">
    </div>
    
      
    <div class="form-group col-md-2">
    <button id="button" onclick="transfer()">Transfer</button><br>
    </div>
    

and script tag has :

async function transfer(){
        var p1 = document.getElementById('transfer_param1').value;
        var p2 = document.getElementById('transfer_param2').value;
        
        const result = await MyToken.methods.transfer(p1, p2).send({from:web3.eth.defaultAccount, gas:1000000})
        .then(function (result) {
         $("#viewtransfer").html('Transfer successful <br>From : ' + (result.events.Transfer.returnValues.from) + '<br> To :    ' + (result.events.Transfer.returnValues.to) + '<br> of MyToken Amount: '+ (result.events.Transfer.returnValues.value));
        console.log(result);
        });
        }

Basically, I don't want the transaction to be submitted and fail and waste gas.

1 Answer 1

1

This is how I'm doing my transactions, using ethers instead of web3js. Basically in the first then, ethers attempts building the transaction tx by also estimating the gas with RPC call. This raises a error before the proper submission if the tx would revert.

    async function transfer(){
        var p1 = document.getElementById('transfer_param1').value;
        var p2 = document.getElementById('transfer_param2').value;

        MyToken.transfer(p1, p2).then((tx) => {
            tx.wait().then((result) => {
                console.log("Transaction successful, result: ", result);
            }).catch(err => {
                console.log("Transaction reverted, error: ", err)
            })
        }).catch(err => {
            console.log("Transaction will fail, error: ", err);
            // this works for sure if using metamask provider
            if (err.code === -32603) {
                console.log("Transaction will revert with reason: ", err.data.message);
            }
        })
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.