0

I've been cloning many Defi apps on Github and reading their implementations of Web3 / Javascript with the contract.

Seems like most are just calling the contracts methods using the promise style, and less common is the event emitter style.

async function buyCredits() {
  try {
    const receipt = await contract.methods.buyCredits().send({
      from: account,
      gas: 233000,
      value: choice.value,
    });

    // Is it safe to assume this block was mined here
    // and the user has the new 
    const credits = await contract.methods.usersCredits().call({
      from: account,
    });


    alert('It was mined!');
    console.log(`This user has ${credits} credits`);
  } catch (e) {
    alert("It NOT mined!");
  }
}

Where buyCredits is just an external payable contract function that gives users credits for ether.

Is this the most reliable way? From the Web3 docs, it seems like the promise to contract methods just return the tx receipt and that does not guarantee the block is mined.

Are there any tutorials, pointers, etc.. on doing this in the most reliable and recommended way? Thanks!

1

2 Answers 2

2

As mentioned by @Ismael, the receipt will indicate that your transaction was mined, but you may consider waiting for a few more blocks mined after yours to protect against potential chain reorganization.

As you are asking for any tutorial or documentation, I followed the one below some time ago and it worked quite well for me:

Track blockchain transactions with web3.js

If you go to section ETH transactions confirmations counting, you just need to implement these couple of functions:

  • getConfirmations()
  • confirmEtherTransaction()

Up to you to decide the number of block confirmations to consider a transaction is fully confirmed (the more blocks you set, the more time you wait).

0

From web3 documentation

Resolves when the transaction receipt is available

The receipt availability implies the transaction was mined.

For most cases it should work (assumming the gas price is high enough to mine the transaction quickly).

But you always have the possibility of a chain reorganization, or having to wait a long time for confirmation.

Your Answer

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

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