Getting Transaction Receipt

Retrieving a transaction receipt by User Operation Hash is an essential step to confirm the successful execution of a transaction on the blockchain. The sdk.getTrxReceiptByUserOpHash(userOpHash, chainId) function in the Magmar SDK allows you to retrieve this receipt, which contains vital information about the transaction’s status and details. This is particularly useful for ensuring that a transaction has been processed correctly before proceeding with subsequent actions.

📄 Function Overview

sdk.getTrxReceiptByUserOpHash(userOpHash, chainId)

  • Parameters:

    • userOpHash (string): The user operation hash for which you want to retrieve the transaction receipt. You typically obtain this hash as a response from the sendUserOp or sendUserOpBatch function.

    • chainId (number): The chain ID of the blockchain network where the transaction was executed.

  • Returns:

    • If the transaction with the provided userOpHash exists on the blockchain and has been successfully executed, the function returns the transaction receipt object.

    • If the transaction has not been executed or does not exist, the function returns an error or a suitable indication of the transaction's absence.


🛠️ Example: Retrieving a Transaction Receipt with Retry Logic

Here’s an example using JavaScript’s async/await to retrieve the transaction receipt, including a simple retry loop:

const userOpHash = 'your-user-operation-hash';
const chainId = 1; // Replace with the appropriate chain ID for your blockchain network.
const maxRetryAttempts = 5; // Define the maximum number of retry attempts.
const retryIntervalMs = 5000; // Define the retry interval in milliseconds (e.g., 5 seconds).

async function waitForTransactionReceipt(userOpHash, chainId, maxAttempts, retryInterval) {
  let attempts = 0;
  let transactionReceipt = null;

  while (attempts < maxAttempts) {
    try {
      transactionReceipt = await sdk.getTrxReceiptByUserOpHash(userOpHash, chainId);
      if (transactionReceipt) {
        // Transaction was executed successfully.
        // You can access details such as block number, gas used, status, etc.
        console.log('Transaction Receipt:', transactionReceipt);
        return transactionReceipt; // Return the receipt and exit the loop.
      } else {
        // Transaction not found or not yet executed. Retry after a delay.
        console.log('Transaction not found or not executed. Retrying in', retryInterval / 1000, 'seconds...');
        await new Promise(resolve => setTimeout(resolve, retryInterval));
        attempts++;
      }
    } catch (error) {
      // Handle any errors that may occur during the retrieval process.
      console.error('Error:', error.message);
      // Retry after a delay.
      console.log('Retrying in', retryInterval / 1000, 'seconds...');
      await new Promise(resolve => setTimeout(resolve, retryInterval));
      attempts++;
    }
  }

  // If the maximum retry attempts are reached without success, handle the error.
  console.error('Maximum retry attempts reached. Transaction not confirmed.');
  return null; // Return null to indicate failure.
}

// Call the function to wait for the transaction receipt.
waitForTransactionReceipt(userOpHash, chainId, maxRetryAttempts, retryIntervalMs)
  .then(result => {
    if (result) {
      // Transaction was confirmed.
      // You can proceed with further actions here.
    } else {
      // Handle the case where the transaction was not confirmed.
      // Consider notifying the user or taking appropriate action.
    }
  });

Explanation:

  • Retry Logic: The function includes a retry mechanism that attempts to retrieve the transaction receipt multiple times (maxRetryAttempts) with a defined delay (retryIntervalMs) between attempts.

  • Transaction Confirmation: If the transaction receipt is successfully retrieved, the transaction details are logged, and the function exits. If not, the function retries until the maximum attempts are reached.

  • Error Handling: If the transaction cannot be confirmed within the allotted attempts, an error is logged, and the function returns null.


🎉 Conclusion

Using the sdk.getTrxReceiptByUserOpHash function in conjunction with a retry loop allows you to reliably confirm the execution of transactions on the blockchain. This ensures that you can safely proceed with any subsequent operations based on the transaction’s outcome.

Last updated