0

I have a contract method:

 function setFile(string fName, string fileHash) public{
  File memory file = File({fileName:fName,fileHash:fileHash});
  files.push(file);
  return something;
 }

Web3.js code

ContractInstance.setFile(file.name,hashResult,function(error, result){
  if(!error)
  {
    console.log("Transaction submitted");
  }
  else{
    console.log("Error");
  }
});

When I call ContractInstance.setFile(browser side), metamask opens and asks for gas price. On submit, console.log("Transaction submitted"); is executed even when transaction is not completed.

Is there a way to implement a callback in web3.js such that when transaction is completed(contract method call), a callback method should be executed. Contract method might returns something that should be saved in database.

1

Two ways:

1) result should contain the transaction ID. Catch that and create a watch for it showing up in a block.

2) Log an event in your setFile function and listen for that.

Be aware that even if one of those results tells you your transaction has got into a block, it may subsequently disappear again if the block it was in is orphaned. If this matters to you, you may prefer to wait multiple blocks and make sure your file is still there before you notify the user that it's done.

  • Thanks. I think solidity events is a good idea. Is it similar to callbacks that our server-side web3.js code can listen to? Also, are transactions executed in the same order they are submitted ? Or they can be picked up(pending ones) in any order ? – Vivek Sadh Aug 6 '18 at 11:52
  • You can get events either as callbacks or by polling, and you can do it on the client side or the server side. Transactions from the same account are executed in the order they are submitted or not at all, controlled by the account nonce, but apart from that transactions can be mined in any order that the miners like. In practice they mostly mine things with higher transaction fees first, but this can vary due to the vagaries of network propagation and node reboots. – Edmund Edgar Aug 6 '18 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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