Decentralized Applications
Querying a Transaction

Querying a Transaction

Reading transactions in GenLayer allows you to inspect the details of any transaction that has been submitted to the network. This is useful for monitoring transaction status, debugging, and verifying transaction details.

Basic Transaction Reading

Here's the simplest way to read a transaction:

import { simulator } from 'genlayer-js/chains';
import { createClient } from 'genlayer-js';
 
const client = createClient({
  chain: simulator,
});
 
const transactionHash = "0x...";
 
const transaction = await client.getTransaction({ 
  hash: transactionHash 
});

Error Handling

async function getTransactionWithRetry(
  client: GenLayerClient,
  hash: string,
  maxAttempts = 3
): Promise<Transaction> {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      const tx = await client.getTransaction({ hash });
      if (!tx) throw new Error('Transaction not found');
      return tx;
    } catch (error) {
      if (attempt === maxAttempts) throw error;
      if (error.message.includes('not found')) {
        // Wait longer between retries for not found errors
        await new Promise(resolve => setTimeout(resolve, 2000 * attempt));
        continue;
      }
      throw error; // Rethrow other errors immediately
    }
  }
  throw new Error('Failed to fetch transaction after max retries');
}

Monitoring Transaction Status

async function monitorTransaction(
  client: GenLayerClient,
  hash: string,
  interval = 1000
): Promise<Transaction> {
  return new Promise((resolve, reject) => {
    const checkStatus = async () => {
      try {
        const tx = await client.getTransaction({ hash });
        
        if (!tx) {
          setTimeout(checkStatus, interval);
          return;
        }
 
        if (tx.status === 'pending') {
          setTimeout(checkStatus, interval);
          return;
        }
 
        resolve(tx);
      } catch (error) {
        reject(error);
      }
    };
 
    checkStatus();
  });
}
 
// Usage
const finalTx = await monitorTransaction(client, "0x...");