0
votes

I have Dapp, where user makes payable call of smart contract using web3.

contract.methods.bet(number).send({
  from: accounts[0],
  gas: 3000000,
  value: web3.utils.toWei(bet.toString(), 'ether')
}, (err, result) => {})

I listen events from smart contract in the Dapp, so I know when transaction mined:

contract.events.blockNumberEvent((error, event) => {
  console.log("transaction mined!");
});

But after this transaction mined I need to make transfers and some changes inside contract.

Can I make delayed call of smart contract (1 block delay) without user interactions? For sure with some amount of gas from my side.

2
Why do you want that one-block delay? Just initiate the transaction when the event triggers. Or you can use await when you send the transaction.nikos fotiadis
@nikosfotiadis Because I need hash of current block. But it's not available in current transaction, only when it mined.ambasador
Could you be more specific here: “I need to make transfers and some changes inside contract.”foba

2 Answers

0
votes

When the transaction is mined you get the receipt id, this indicates that the transaction is executed. So you can execute the next function after you get the receipt id. Incase if you want to execute it in next block one way could be that in the dapp you create a delay average time of the block is 14-15 seconds ( Reference) and after 14-15 seconds of delay execute the other function

0
votes

Let's start from the beginning when you send a transaction into the blockchain, you will receive a transactionHash right away. That txHash you can use it to check when your tx was accepted (included into a block) or rejected,

There are multiple alternatives you could use to as you see from the web3 official doc

One of them could be:

contract.methods.bet(number).send({
  from: accounts[0],
  gas: 3000000,
  value: web3.utils.toWei(bet.toString(), 'ether')
}, (error, transactionHash) => {
 if(error) // Handle the error
 else {
   txReceipt = null;
   while(true) {
      let txReceipt = web3.eth.getTransactionReceipt(txReceiptId);
      if (txReceipt != null && typeof txReceipt !== 'undefined') {
        break;
      }
    }
   if (txReceipt.status == "0x1") // Actions to take when tx success
   else // Actions to take when tx fails
 }
})

Another shorter alternative could be:

contract.methods.bet(number).send({
  from: accounts[0],
  gas: 3000000,
  value: web3.utils.toWei(bet.toString(), 'ether')
}).on('receipt', (txReceipt) => {
   if (txReceipt.status == "0x1") // Actions to take when tx success
   else // Actions to take when tx fails
})

Therefore there is no need to randomize your wait using 14-15s :)