Search code examples
blockchainethereumsoliditysmartcontractsethers.js

Which is more effective way to subscribe state change in Ethereum


I click a button that run method approve(tokenID, myContract) in ERC721 so that my contract can transfer this token. After that, I need to wait until state in Ethereum to be updated before do anything else. So I need to know when state in Ethereum updated

I find out 2 ways of doing this

  1. Listen to event Approval in ERC721
  2. After call approve I receive response which contains txHash. I can then use this txHash to run library.getTransactionReceipt(txHash).then(receipt => {}) (library = Web3Provider)

My questions is

  1. When tx.receipt != null does it also means that Ethereum state updated?
  2. If it is, then which ways is more effective?

Solution

  • When tx.receipt != null does it also means that Ethereum state updated?

    The receipt can have non-null value when the transaction is reverted - which means the state was not updated. You can find this information in the receipt field status

    • true is successful
    • false is reverted

    Note: The recently implemented EIP-2718 effectively allows for transaction receipts without the status field, so it's possible that there are going to be some transaction types without the status in the future. Also, transactions before the Byzantinum hard fork (October 2017) don't have the status field as well.


    As to your original question, both ways are valid.

    If you're building a small application that doesn't have much logic or is okay to fail sometimes, the second option seems to be less robust (in terms of working with asynchronicity). You just wait for the txHash (that you only receive after the tx has been mined into a block), and then you get the tx receipt (containing the event log) based on the hash.

    But what if your app crashes between getting the tx hash and processing the event log from the receipt? If this is your concern, you might want to implement a way to store the tx hash to a DB, listen to the event logs (your point 1), and compare each event log (containing the hash of its transaction) with the stored tx hashes.