utils.ts
Overview
The [utils.ts](/projects/291/69086) file provides utility functions and configured HTTP clients for interacting with a blockchain indexer API. Its primary purpose is to fetch enriched transaction data for a given transaction ID (`txid`) from an external indexer service, handling retries and error conditions gracefully.
This file abstracts the complexity of making HTTP requests to the indexer, including retry logic and exponential backoff, and returns transactions in a structured format compatible with the system’s `Tx` model.
Detailed Explanations
Environment Variables
INDEXER_URL: The base URL of the blockchain transaction indexer API.RPC_API_KEY: API key used for authenticating requests to the indexer.
Both environment variables are mandatory, and the file throws an error on initialization if either is missing.
Constants / Instances
axiosNoRetry
Type:
AxiosInstanceDescription: An Axios HTTP client instance configured with a 5-second timeout and the necessary API key as a query parameter.
Usage: Used for making requests where retry logic is not needed.
axiosWithRetry
Type:
AxiosInstance(wrapped with retry capabilities)Description: An Axios HTTP client configured to retry failed requests up to 6 times with exponential backoff delays. Timeout is set to 10 seconds.
Retry Strategy: Uses
createAxiosRetryfrom the@shapeshiftoss/common-apipackage with a delay factor of 1000ms.Usage: Used for requests where eventual consistency requires retrying, such as fetching transactions that may not be immediately finalized.
Functions
getTransaction
async function getTransaction(
txid: string,
shouldRetry?: boolean,
retryCount = 0
): Promise<Tx>
Parameters:
txid(string): The transaction ID to fetch.shouldRetry(boolean, optional): Whether to enable retry logic; defaults tofalse.retryCount(number, optional): Internal counter to track the number of retry attempts; defaults to 0.
Returns:
Promise<Tx>— A promise that resolves to a transaction object conforming to theTxinterface.Description:
Makes a POST request to
${INDEXER_URL}/v0/transactions/with the specifiedtxid.Uses either
axiosNoRetryoraxiosWithRetrybased on theshouldRetryflag.If the transaction is not found (
data[0]is undefined), it retries up to 5 times with an exponential delay between attempts.On success, maps the response from the
EnrichedTransaction(fromhelius-sdk) to the localTxmodel, extracting relevant event properties (compressed,nft,swap) and returning the enriched transaction.On failure after all retries or on other errors, throws a handled error.
Example Usage:
import { getTransaction } from './utils'
async function example() {
try {
const tx = await getTransaction('some-transaction-id', true)
console.log('Transaction:', tx)
} catch (error) {
console.error('Failed to fetch transaction:', error)
}
}
Important Implementation Details
Retry Logic: The retry mechanism is designed to handle blockchain transaction finality delays:
The indexer’s
/transactionsendpoint only returns transactions with "finalized" commitment level.However, the system listens for "confirmed" logs, which may precede finalization.
To bridge this gap, the function retries fetching the transaction up to 5 times with exponential delays (using
exponentialDelay), allowing enough time (~1 minute) for the transaction to reach finality.
Error Handling: All errors are passed through a centralized
handleErrorfunction from@shapeshiftoss/common-apito normalize and enrich error information.Type Mapping: The function converts
EnrichedTransactiontypes from the external SDK into the localTxtype, ensuring compatibility with other parts of the system.
Interaction with Other Parts of the System
Models: Depends on the
Txinterface/type defined in the local./modelsmodule.External SDK: Uses
EnrichedTransactiontype from thehelius-sdkto type-check API responses.Common API Utilities: Utilizes shared helper functions (
createAxiosRetry,exponentialDelay,handleError) from the@shapeshiftoss/common-apipackage.Environment Configuration: Relies on environment variables to configure API URLs and keys, implying integration with deployment or runtime configuration management.
Consumer Modules: Likely consumed by higher-level services or business logic layers that need to retrieve blockchain transaction details reliably.
Visual Diagram
flowchart TD
A[getTransaction(txid, shouldRetry, retryCount)]
A -->|shouldRetry = true| B[axiosWithRetry POST /transactions]
A -->|shouldRetry = false| C[axiosNoRetry POST /transactions]
B --> D{Response Data}
C --> D
D -->|tx found| E[Map EnrichedTransaction -> Tx]
D -->|tx not found| F{retryCount < 5?}
F -->|Yes| G[exponentialDelay]
G --> A
F -->|No| H[Throw 'Transaction not found' error]
A -->|Catch error| I[handleError]
The flowchart illustrates the decision-making process within
getTransaction: choosing the Axios instance, handling response data, retrying with delay if transaction not found, and error handling.
Summary
The [utils.ts](/projects/291/69086) file is a specialized utility module focused on retrieving enriched blockchain transaction data with robust retry and error handling mechanisms. It abstracts HTTP client configuration and retry logic, providing a clean interface (`getTransaction`) for other parts of the application to reliably fetch transaction details from an external indexer service. This file is a critical integration point ensuring the system can handle eventual consistency and delays inherent in blockchain data finalization.