UNPKG

@noves/noves-sdk

Version:
1,393 lines (1,384 loc) 180 kB
/** * Error types for the Noves SDK */ /** * Enum for different error types that can occur in the SDK */ declare enum ErrorType { UNAUTHORIZED = "UNAUTHORIZED", INVALID_API_KEY = "INVALID_API_KEY", RATE_LIMIT_EXCEEDED = "RATE_LIMIT_EXCEEDED", JOB_NOT_FOUND = "JOB_NOT_FOUND", JOB_PROCESSING = "JOB_PROCESSING", JOB_NOT_READY = "JOB_NOT_READY", INVALID_REQUEST = "INVALID_REQUEST", INVALID_RESPONSE_FORMAT = "INVALID_RESPONSE_FORMAT", NETWORK_ERROR = "NETWORK_ERROR", UNKNOWN_ERROR = "UNKNOWN_ERROR", VALIDATION_ERROR = "VALIDATION_ERROR" } /** * Error code to message mapping for consistent error messages */ declare const ERROR_MESSAGES: Record<ErrorType, string>; /** * Error code to HTTP status code mapping */ declare const ERROR_STATUS_CODES: Record<ErrorType, number>; /** * Common types shared across all ecosystems */ interface ApiResponse { succeeded: boolean; response: any; httpStatusCode?: number; errorType?: string; } /** * Comprehensive configuration interface for the retry mechanism. * Provides fine-grained control over retry behavior across all SDK modules. */ interface RetryConfig { /** Enable or disable the retry mechanism. Default: false (for backward compatibility) */ enabled: boolean; /** Maximum number of attempts including the initial request. Default: 3 */ maxAttempts: number; /** Base delay in milliseconds before the first retry. Default: 1000ms */ baseDelay: number; /** Maximum delay in milliseconds between retries. Default: 30000ms (30 seconds) */ maxDelay: number; /** Exponential backoff multiplier. Default: 2 */ exponentialBase: number; /** Whether to add jitter to delay calculations. Default: true */ jitter: boolean; /** Jitter factor as a percentage of the calculated delay. Default: 0.1 (10%) */ jitterFactor: number; /** Array of error types that should trigger a retry */ retryableErrors: ErrorType[]; /** Array of HTTP status codes that should trigger a retry */ retryableStatusCodes: number[]; /** Whether to respect Retry-After headers from the server. Default: true */ respectRetryAfter: boolean; /** Number of consecutive failures before opening the circuit breaker. Default: 5 */ circuitBreakerThreshold: number; /** Time in milliseconds before attempting to close the circuit breaker. Default: 60000ms (1 minute) */ circuitBreakerResetTime: number; /** Callback function called before each retry attempt */ onRetry?: (attempt: number, error: any, delay: number) => void; /** Callback function called when a request succeeds after retries */ onSuccess?: (attempt: number) => void; /** Callback function called when all retry attempts are exhausted */ onFailure?: (attempts: number, finalError: any) => void; } /** * Context information for tracking retry attempts and circuit breaker state. * Used internally by the retry engine to maintain state across operations. */ interface RetryContext { /** Unique identifier for this operation type (e.g., "translate-evm", "pricing-svm") */ operationId: string; /** Timestamp when the operation started */ startTime: number; /** Number of consecutive failures for this operation type */ failures: number; /** Timestamp of the last failure for this operation type */ lastFailureTime: number; /** Whether the circuit breaker is currently open for this operation */ circuitOpen: boolean; } /** * Interface for the core retry engine that handles retry logic. */ interface RetryEngine { /** * Execute a request function with retry logic applied. * @param requestFn Function that makes the actual request * @param config Retry configuration to use * @param context Retry context for tracking state * @returns Promise that resolves with the request result */ executeWithRetry<T>(requestFn: () => Promise<T>, config: RetryConfig, context: RetryContext): Promise<T>; /** * Calculate the delay before the next retry attempt. * @param attempt Current attempt number (1-based) * @param config Retry configuration * @param retryAfter Optional Retry-After header value in seconds * @returns Delay in milliseconds */ calculateDelay(attempt: number, config: RetryConfig, retryAfter?: number): number; /** * Determine if an error should trigger a retry. * @param error The error that occurred * @param attempt Current attempt number (1-based) * @param config Retry configuration * @returns True if the error should be retried */ shouldRetry(error: any, attempt: number, config: RetryConfig): boolean; /** * Check if the circuit breaker is open for the given context. * @param context Retry context * @returns True if the circuit breaker is open */ isCircuitOpen(context: RetryContext): boolean; /** * Record a failure for circuit breaker tracking. * @param context Retry context to update */ recordFailure(context: RetryContext): void; /** * Record a success for circuit breaker tracking. * @param context Retry context to update */ recordSuccess(context: RetryContext): void; } /** * Navigation metadata embedded within enhanced cursors for stateless pagination. * This allows cursors to be self-contained with full navigation context. */ interface CursorNavigationMeta { /** * Current page index in the navigation sequence (0-based) */ currentPageIndex: number; /** * Complete navigation history - array of PageOptions for each page visited * Index 0 = first page, Index 1 = second page, etc. */ navigationHistory: PageOptions[]; /** * Whether backward navigation is possible from this cursor */ canGoBack: boolean; /** * Whether forward navigation is possible from this cursor */ canGoForward: boolean; /** * PageOptions for the previous page (null if on first page) */ previousPageOptions: PageOptions | null; /** * PageOptions for the next page (null if no next page) */ nextPageOptions: PageOptions | null; /** * Original page index before navigation history truncation. * Used for proper navigation when history is limited. */ originalPageIndex?: number; /** * Start index of the navigation history slice. * Used to reconstruct full context when needed. */ historyStartIndex?: number; } /** * Enhanced cursor data that includes navigation metadata. * This extends PageOptions with navigation context for stateless pagination. */ interface EnhancedCursorData extends PageOptions { /** * Navigation metadata for cursor-based pagination. * When present, enables full backward/forward navigation from cursors. */ _cursorMeta?: CursorNavigationMeta; } /** * Represents the available options for a page of transactions. * * All ecosystems use nextPageUrl-based pagination that is handled automatically by the SDK. * When you call getTransactions() or similar methods, the SDK will return a TransactionsPage * object that you can use to iterate through pages using the next() method. * * These options are for filtering and configuring the initial request only. * Pagination between pages is handled internally via nextPageUrl parsing. * * @interface PageOptions */ interface PageOptions { /** * The starting block number to filter by. (Optional) */ startBlock?: number; /** * The ending block number to filter by. (Optional) */ endBlock?: number; /** * The starting timestamp for the transaction page in milliseconds. (Optional) */ startTimestamp?: number; /** * The ending timestamp for the transaction page in milliseconds. (Optional) */ endTimestamp?: number; /** * The sort order for the transaction page. Valid options are 'desc' (descending) or 'asc' (ascending). (Optional) */ sort?: 'desc' | 'asc'; /** * The account address to view transactions from. (Optional) */ viewAsAccountAddress?: string; /** * The number of transactions to retrieve per page. Defaults to 10. (Optional) * Maximum page sizes vary by ecosystem: EVM (50), SVM/UTXO (100). */ pageSize?: number; /** * Whether to retrieve live data or paginate through historical data. Defaults to false. (Optional) * Only applicable for EVM chains. */ liveData?: boolean; /** * Whether to view transactions as the sender. (Optional) * Only applicable for EVM chains. */ viewAsTransactionSender?: boolean; /** * Whether to use v5 format for transaction responses. (Optional) * Applicable for EVM and UTXO chains. Defaults to false (v2 format). * For UTXO chains, this determines the format path parameter (v5 or v2). */ v5Format?: boolean; /** * The number of epochs to retrieve staking transactions for. (Optional) * Only applicable for SVM staking transactions. */ numberOfEpochs?: number; /** * Whether to include token prices in the response. (Optional) */ includePrices?: boolean; /** * Whether to exclude tokens with zero prices. (Optional) */ excludeZeroPrices?: boolean; /** * Transaction cursor token for pagination. (Internal use - set by API responses) * This parameter is used by the API to exclude already-seen transactions. */ ignoreTransactions?: string; /** * Page key for TVM pagination cursor. (Internal use - set by API responses) * This parameter is used by TVM chains for pagination. */ pageKey?: string; /** * Page number for offset-based pagination. (Internal use - set by API responses) * This parameter is used for job-based pagination in UTXO. */ pageNumber?: number; /** * Sort order for job-based pagination. (Internal use - set by API responses) * This parameter is used for job-based pagination in UTXO. */ ascending?: boolean; /** * Maximum number of pages to keep in navigation history for cursor-based pagination. * This limits backward navigation but prevents cursor growth and 413 errors. * Defaults to 10 if not specified. Set to a higher value if you need deeper backward navigation. * @default 10 */ maxNavigationHistory?: number; /** * Marker token for XRPL pagination. (Internal use - set by API responses) * This parameter is used by XRPL chains for pagination. */ marker?: string; } /** * Risk detection information for URL screening */ interface UrlRisk { /** * The type of risk detected (e.g., "blacklisted") */ type: string; } /** * Response from the URL screening endpoint */ interface ForesightUrlScreenResponse { /** * The domain that was screened */ domain: string; /** * Array of risks detected for this URL */ risksDetected: UrlRisk[]; } /** * Configuration for customizing the underlying fetch client behavior. * Allows users to set request timeouts, pass AbortController signals, * and customize headers for all SDK requests. * * @example * ```typescript * // Set a 30-second timeout for all requests * const translate = Translate.evm({ * apiKey: 'YOUR_API_KEY', * fetchConfig: { timeout: 30000 } * }); * * // Use an AbortController for global cancellation * const controller = new AbortController(); * const translate = Translate.evm({ * apiKey: 'YOUR_API_KEY', * fetchConfig: { signal: controller.signal } * }); * // Later: controller.abort(); * ``` */ interface FetchConfig { /** * Default request timeout in milliseconds for all API calls. * When set, each request will be automatically aborted if it exceeds this duration. * The timeout creates an internal AbortController per request attempt. * If both `timeout` and `signal` are provided, the request will abort when either triggers first. * Timeout applies per-attempt when retries are enabled (each retry gets a fresh timeout). * @example 30000 // 30 seconds */ timeout?: number; /** * Default AbortSignal to apply to all fetch calls. * Useful for global cancellation (e.g., when shutting down your application or unmounting a component). * If both `timeout` and `signal` are provided, the request will abort when either triggers first. * When this signal is aborted, the request is cancelled immediately and retries are skipped. * @example * ```typescript * const controller = new AbortController(); * const translate = Translate.evm({ * apiKey: 'YOUR_API_KEY', * fetchConfig: { signal: controller.signal } * }); * // Cancel all in-flight requests: * controller.abort(); * ``` */ signal?: AbortSignal; /** * Additional headers to include in every request. * These are merged with the SDK's default headers (apiKey, Content-Type). * SDK default headers (apiKey, Content-Type) take precedence over custom headers. * @example { 'X-Custom-Header': 'my-value' } */ headers?: Record<string, string>; } /** * Enhanced factory options for SDK initialization */ interface SDKOptions { apiKey: string; retryConfig?: RetryConfig | string; environment?: 'production' | 'development' | 'testing'; /** * Configuration for customizing the underlying fetch client behavior. * Allows setting request timeouts, abort signals, and custom headers. * @see FetchConfig */ fetchConfig?: FetchConfig; } /** * SVM (Solana Virtual Machine) ecosystem-specific types * These types match the actual API responses from the Noves API */ /** * Represents an SVM chain as returned by the Translate API */ interface SVMTranslateChain { name: string; ecosystem: string; nativeCoin: { name: string; symbol: string; address: string; decimals: number; }; tier: number; } /** * Response from the SVM chains endpoint */ type SVMTranslateChainsResponse = SVMTranslateChain[]; /** * Interface representing a token in a transfer */ interface SVMTranslateToken { decimals: number; address: string; name: string | null; symbol: string | null; icon: string | null; } /** * Interface representing an account in a transfer */ interface SVMTranslateAccount { name: string | null; address: string | null; owner: { name: string | null; address: string | null; }; } /** * Interface representing a transfer in a transaction */ interface SVMTranslateTransfer { action: string; amount: string; token: SVMTranslateToken; from: SVMTranslateAccount; to: SVMTranslateAccount; } /** * Interface representing the raw transaction data */ interface SVMTranslateRawTransactionData { signature: string; blockNumber: number; signer: string; interactedAccounts: string[]; } /** * Interface representing the source of the transaction for V5 format */ interface SVMTranslateSourceV5 { type: string | null; name: string | null; } /** * Interface representing the source of the transaction for V4 format */ interface SVMTranslateSourceV4 { type: string; name: string; } /** * SVM transaction type union based on actual API response from /svm/txTypes endpoint */ type SVMTransactionType = 'addLiquidity' | 'bridge' | 'cancelNftListing' | 'claimRewards' | 'closeTipAccount' | 'createNftListing' | 'depositForStake' | 'depositToVault' | 'distributeRewards' | 'error' | 'failed' | 'mergeStake' | 'mintNFT' | 'mintToken' | 'removeLiquidity' | 'stake' | 'swap' | 'unclassified' | 'unstake' | 'withdrawStake'; /** * Interface representing classification data for SVM V5 transactions */ interface SVMTranslateClassificationDataV5 { type: SVMTransactionType; description: string | null; } /** * Interface representing classification data for SVM V4 transactions */ interface SVMTranslateClassificationDataV4 { type: SVMTransactionType; } /** * Interface representing a V4 SVM transaction response */ interface SVMTranslateTransactionV4 { txTypeVersion: 4; source: SVMTranslateSourceV4; timestamp: number; classificationData: SVMTranslateClassificationDataV4; transfers: SVMTranslateTransfer[]; rawTransactionData: SVMTranslateRawTransactionData; } /** * Interface representing a V5 SVM transaction response */ interface SVMTranslateTransactionV5 { txTypeVersion: 5; source: SVMTranslateSourceV5; timestamp: number; classificationData: SVMTranslateClassificationDataV5; transfers: SVMTranslateTransfer[]; values: any[]; rawTransactionData: SVMTranslateRawTransactionData; } /** * Union type for SVM transactions */ type SVMTranslateTransaction = SVMTranslateTransactionV4 | SVMTranslateTransactionV5; /** * Interface representing paginated SVM transactions response */ interface SVMTranslateTransactionsResponse { items: SVMTranslateTransaction[]; page: number; pageSize: number; nextPageUrl: string | null; } /** * Interface representing a transaction description */ interface SVMTranslateDescribeTransaction { signature: string; type: SVMTransactionType; description: string; timestamp: number; transfers: SVMTranslateTransfer[]; } /** * Interface representing SPL accounts response */ interface SVMTranslateSPLAccounts { accountPubkey: string; tokenAccounts: Array<{ pubKey: string; }>; } /** * Interface representing SVM token balance */ interface SVMTranslateTokenBalance { balance: string; usdValue: string; token: { symbol: string; name: string; decimals: number; address: string; price: string; }; } /** * Response from the SVM token balances endpoint */ type SVMTranslateTokenBalancesResponse = SVMTranslateTokenBalance[]; /** * Interface representing a single transaction type */ interface SVMTranslateTransactionType { type: string; description: string; } /** * Interface representing the full transaction types response from /svm/txTypes endpoint */ interface SVMTranslateTransactionTypesResponse { version: number; transactionTypes: SVMTranslateTransactionType[]; } /** * Interface representing transaction job for SVM */ interface SVMTranslateTransactionJob { jobId: string; nextPageUrl: string; startTimestamp: number; } /** * Interface representing transaction job response for SVM */ interface SVMTranslateTransactionJobResponse { items: SVMTranslateTransaction[]; pageSize: number; hasNextPage: boolean; nextPageUrl: string | null; } /** * Interface representing delete transaction job response for SVM */ interface SVMTranslateDeleteTransactionJobResponse { message: string; } /** * Interface representing transaction count job start response for SVM */ interface SVMTranslateTransactionCountJobStartResponse { jobId: string; resultsUrl: string; } /** * Interface representing transaction count response for SVM */ interface SVMTranslateTransactionCountResponse { chain: string; timestamp: number; account: { address: string; transactionCount: number; }; } /** * Interface representing SVM staking transaction */ interface SVMTranslateStakingTransaction { txTypeVersion: number; source: SVMTranslateSourceV5; timestamp: number; classificationData: { description: string; type: SVMTransactionType; }; transfers: SVMTranslateTransfer[]; values: Array<{ key: string; value: string; }>; rawTransactionData: { signature: string; blockNumber: number; signer: string; interactedAccounts: string[] | null; }; } /** * Interface representing SVM staking transactions response */ interface SVMTranslateStakingTransactionsResponse { items: SVMTranslateStakingTransaction[]; numberOfEpochs: number; failedEpochs: any[]; nextPageUrl: string | null; } /** * Interface representing SVM staking epoch response */ interface SVMTranslateStakingEpochResponse { txTypeVersion: 5; source: SVMTranslateSourceV5; timestamp: number; classificationData: { description: string; type: string; }; transfers: SVMTranslateTransfer[]; values: Array<{ key: string; value: string; }>; rawTransactionData: { signature: string; blockNumber: number; signer: string; interactedAccounts: string[] | null; }; } /** * Interface representing an SVM chain as returned by the Pricing API */ interface SVMPricingChain { name: string; ecosystem: string; nativeCoin: { name: string; symbol: string; address: string; decimals: number; }; } /** * Response from the SVM pricing chains endpoint */ type SVMPricingChainsResponse = SVMPricingChain[]; /** * Interface representing a token in SVM pricing response */ interface SVMPricingToken { address: string; symbol: string; name: string; } /** * Interface representing price information in SVM pricing response */ interface SVMPricingPriceInfo { amount: string; currency: string; status: string; } /** * Interface representing the complete SVM pricing response * Matches the actual API response from GET /svm/{chain}/price/{tokenAddress} */ interface SVMPricingPrice { chain: string; token: SVMPricingToken; price: SVMPricingPriceInfo; priceType: string; priceStatus: string; } /** * Base class for all translate implementations. * Provides common functionality and structure for all blockchain translation modules. */ declare abstract class BaseTranslate { protected readonly ecosystem: string; private readonly client; /** * Create a BaseTranslate instance. * @param {string} ecosystem - The blockchain ecosystem identifier. * @param {string} apiKey - The API key to authenticate requests. * @param {Partial<RetryConfig>} [retryConfig] - Optional retry configuration for enhanced resilience. * @param {FetchConfig} [fetchConfig] - Optional fetch configuration for timeouts, abort signals, and custom headers. * @throws Will throw an error if the API key is not provided. */ constructor(ecosystem: string, apiKey: string, retryConfig?: Partial<RetryConfig>, fetchConfig?: FetchConfig); /** * Make a request to the API. * @param {string} endpoint - The API endpoint to request. * @param {string} [method='GET'] - The HTTP method to use. * @param {RequestInit} [options={}] - Additional request options. * @returns {Promise<any>} The response from the API. * @throws Will throw an error if the request fails or returns an error response. */ protected makeRequest(endpoint: string, method?: string, options?: RequestInit): Promise<any>; /** * Validate the response structure. * @param {any} response - The response to validate. * @param {string[]} requiredFields - The required fields in the response. * @returns {boolean} True if the response is valid, false otherwise. */ protected validateResponse(response: any, requiredFields: string[]): boolean; } type SPLAccounts = SVMTranslateSPLAccounts; type SVMTransactionV4 = SVMTranslateTransactionV4; type SVMTransactionV5 = SVMTranslateTransactionV5; type SVMTransaction = SVMTranslateTransaction; /** * Class representing the SVM translation module. */ declare class TranslateSVM extends BaseTranslate { private request; /** * Create a TranslateSVM instance. * @param {string} apiKey - The API key to authenticate requests. * @param {Partial<RetryConfig>} [retryConfig] - Optional retry configuration for enhanced resilience. * @param {FetchConfig} [fetchConfig] - Optional fetch configuration for timeouts, abort signals, and custom headers. * @throws Will throw an error if the API key is not provided. */ constructor(apiKey: string, retryConfig?: Partial<RetryConfig>, fetchConfig?: FetchConfig); /** * Returns a list with the names of the SVM blockchains currently supported by this API. * Use the provided chain name when calling other methods. * @returns {Promise<SVMTranslateChainsResponse>} A promise that resolves to an array of chains. */ getChains(): Promise<SVMTranslateChainsResponse>; /** * Returns all of the available transaction information for the signature requested. * @param {string} chain - The chain name. Defaults to solana. * @param {string} signature - The transaction signature. * @param {number} [txTypeVersion=5] - Optional. The transaction type version to use (4 or 5). Defaults to 5. * @returns {Promise<SVMTransactionV4 | SVMTransactionV5>} A promise that resolves to the transaction details. * @throws {TransactionError} If there are validation errors in the request. */ getTransaction(chain: string | undefined, signature: string, txTypeVersion?: number): Promise<SVMTransactionV4 | SVMTransactionV5>; /** * Get a pagination object to iterate over transactions pages. * @param {string} chain - The chain name. * @param {string} accountAddress - The account address. * @param {PageOptions} pageOptions - The page options object. * @returns {Promise<TransactionsPage<SVMTransaction>>} A promise that resolves to a TransactionsPage instance. */ getTransactions(chain: string, accountAddress: string, pageOptions?: PageOptions): Promise<TransactionsPage<SVMTransaction>>; /** * @deprecated Use getTransactions instead. This method will be removed in a future version. * Get a pagination object to iterate over transactions pages. * @param {string} chain - The chain name. * @param {string} accountAddress - The account address. * @param {PageOptions} pageOptions - The page options object. * @returns {Promise<TransactionsPage<SVMTransaction>>} A promise that resolves to a TransactionsPage instance. */ Transactions(chain: string, accountAddress: string, pageOptions?: PageOptions): Promise<TransactionsPage<SVMTransaction>>; /** * Returns a list of the available SPL token account addresses for the chain and wallet requested. * @param {string} accountAddress - The account address. * @param {string} chain - The chain name. Defaults to solana. * @returns {Promise<SPLAccounts>} A promise that resolves to the SPL accounts data. * @throws {TransactionError} If there are validation errors in the request. */ getSplTokens(accountAddress: string, chain?: string): Promise<SPLAccounts>; /** * Returns a list of all available transaction types that can be returned by the API. * This is useful for understanding what types of transactions can be classified. * @returns {Promise<SVMTranslateTransactionTypesResponse>} A promise that resolves to an object containing transaction types and version. */ getTxTypes(): Promise<SVMTranslateTransactionTypesResponse>; /** * For a list of transactions, returns their descriptions and types. * Useful in cases where you need to describe multiple transactions at once. * @param {string} chain - The chain name. * @param {string[]} signatures - Array of transaction signatures. * @param {string} viewAsAccountAddress - OPTIONAL - Results are returned with the view/perspective of this wallet address. * @returns {Promise<SVMTranslateDescribeTransaction[]>} A promise that resolves to an array of transaction descriptions. * @throws {TransactionError} If there are validation errors in the request. */ describeTransactions(chain: string, signatures: string[], viewAsAccountAddress?: string): Promise<SVMTranslateDescribeTransaction[]>; /** * Start a transaction job for the given chain and account address. * @param {string} chain - The chain name. * @param {string} accountAddress - The account address. * @param {number} startTimestamp - The start timestamp. * @param {boolean} validateStartTimestamp - Whether to validate the start timestamp. * @returns {Promise<SVMTranslateTransactionJob>} A promise that resolves to the transaction job. */ startTransactionJob(chain: string, accountAddress: string, startTimestamp?: number, validateStartTimestamp?: boolean): Promise<SVMTranslateTransactionJob>; /** * Get the results of a transaction job. * @param {string} chain - The chain name. * @param {string} jobId - The job ID from the transaction job. * @param {PageOptions} pageOptions - The page options object. * @returns {Promise<SVMTranslateTransactionJobResponse>} A promise that resolves to the transaction job results. * @throws {TransactionError} If there are validation errors in the request. */ getTransactionJobResults(chain: string, jobId: string, pageOptions?: PageOptions): Promise<SVMTranslateTransactionJobResponse>; /** * Delete a transaction job. * @param {string} chain - The chain name. * @param {string} jobId - The job ID to delete. * @returns {Promise<SVMTranslateDeleteTransactionJobResponse>} A promise that resolves to the deletion confirmation message. * @throws {TransactionError} If there are validation errors in the request. */ deleteTransactionJob(chain: string, jobId: string): Promise<SVMTranslateDeleteTransactionJobResponse>; /** * Get token balances for an account address. * @param {string} chain - The chain name. * @param {string} accountAddress - The account address. * @param {boolean} [includePrices=true] - Optional. Whether to include token prices in the response. * @param {boolean} [excludeZeroPrices=false] - Optional. Whether to exclude tokens with zero price. * @returns {Promise<SVMTranslateTokenBalance[]>} A promise that resolves to the balances data. * @throws {TransactionError} If there are validation errors in the request. */ getTokenBalances(chain: string, accountAddress: string, includePrices?: boolean, excludeZeroPrices?: boolean): Promise<SVMTranslateTokenBalance[]>; /** * Get the transaction count for an account address. * @param {string} chain - The chain name. Defaults to solana. * @param {string} accountAddress - The account address to get transaction count for. * @param {string} [webhookUrl] - Optional webhook URL for job completion notification. * @returns {Promise<SVMTranslateTransactionCountResponse>} A promise that resolves to the transaction count data. * @throws {TransactionError} If there are validation errors in the request. */ getTransactionCount(chain: string | undefined, accountAddress: string, webhookUrl?: string): Promise<SVMTranslateTransactionCountResponse>; /** * Get staking transactions for a staking account. * @param {string} chain - The chain name. Defaults to solana. * @param {string} stakingAccount - The staking account address. * @param {PageOptions} pageOptions - Optional pagination options. * @returns {Promise<SVMTranslateStakingTransactionsResponse>} A promise that resolves to the staking transactions data. * @throws {TransactionError} If there are validation errors in the request. */ getStakingTransactions(chain: string | undefined, stakingAccount: string, pageOptions?: PageOptions): Promise<SVMTranslateStakingTransactionsResponse>; /** * Get staking information for a specific epoch. * @param {string} chain - The chain name. Defaults to solana. * @param {string} stakingAccount - The staking account address. * @param {number} epoch - The epoch number. * @returns {Promise<SVMTranslateStakingEpochResponse>} A promise that resolves to the staking epoch data. * @throws {TransactionError} If there are validation errors in the request. */ getStakingEpoch(chain: string | undefined, stakingAccount: string, epoch: number): Promise<SVMTranslateStakingEpochResponse>; } /** * UTXO-specific types for the Translate API * These types match the actual API responses from UTXO endpoints */ /** * UTXO chain information returned by the getChains endpoint */ interface UTXOTranslateChain { name: string; ecosystem: 'utxo'; nativeCoin: { name: string; symbol: string; address: string; decimals: number; }; tier: number; } /** * Response type for getChains endpoint */ type UTXOTranslateChainsResponse = UTXOTranslateChain[]; /** * UTXO token information */ interface UTXOTranslateToken { symbol: string; name: string; decimals: number; address: string; } /** * UTXO address information - v2 format (nullable addresses) */ interface UTXOTranslateAddressV2 { name: string | null; address: string | null; } /** * UTXO address information - v5 format (with owner field) */ interface UTXOTranslateAddressV5 { name: string; address: string; owner: Record<string, any>; } /** * UTXO transfer information - v2 format (in sent/received arrays) */ interface UTXOTranslateTransferV2 { action: string; from: UTXOTranslateAddressV2; to: UTXOTranslateAddressV2; amount: string; token: UTXOTranslateToken; } /** * UTXO transfer information - v5 format (in transfers array) */ interface UTXOTranslateTransferV5 { action: string; from: UTXOTranslateAddressV5; to: UTXOTranslateAddressV5; amount: string; token: UTXOTranslateToken; } /** * UTXO-specific transaction summary for inputs and outputs */ interface UTXOTransactionSummaryItem { senders?: string[]; receivers?: string[]; totalSent?: { amount: string; token: UTXOTranslateToken; }; totalReceived?: { amount: string; token: UTXOTranslateToken; }; } /** * UTXO-specific transaction summary */ interface UTXOTransactionSummary { inputs: UTXOTransactionSummaryItem[]; outputs: UTXOTransactionSummaryItem[]; } /** * UTXO transaction type union based on backend confirmation (only sendToken/receiveToken) */ type UTXOTransactionType = 'sendToken' | 'receiveToken'; /** * UTXO classification data - v2 format */ interface UTXOTranslateClassificationDataV2 { type: UTXOTransactionType; source: { type: string; }; description: string; protocol: Record<string, any>; sent: UTXOTranslateTransferV2[]; received: UTXOTranslateTransferV2[]; utxo: { summary: UTXOTransactionSummary; }; } /** * UTXO classification data - v5 format */ interface UTXOTranslateClassificationDataV5 { type: UTXOTransactionType; source: { type: string; }; description: string; protocol: Record<string, any>; } /** * UTXO raw transaction data - v2 format (timestamp in rawTransactionData) */ interface UTXOTranslateRawTransactionDataV2 { transactionHash: string; blockNumber: number; transactionFee: { amount: string; token: UTXOTranslateToken; }; timestamp: number; } /** * UTXO raw transaction data - v5 format (no timestamp in rawTransactionData) */ interface UTXOTranslateRawTransactionDataV5 { transactionHash: string; blockNumber: number; transactionFee: { amount: string; token: UTXOTranslateToken; }; } /** * UTXO value item - v5 format specific */ interface UTXOTranslateValueItem { name: string; value: { summary: UTXOTransactionSummary; }; } /** * UTXO transaction - v2 format */ interface UTXOTranslateTransactionV2 extends PaginatedItem { txTypeVersion: 2; chain: string; accountAddress: string; classificationData: UTXOTranslateClassificationDataV2; rawTransactionData: UTXOTranslateRawTransactionDataV2; } /** * UTXO transaction - v5 format */ interface UTXOTranslateTransactionV5 extends PaginatedItem { txTypeVersion: 5; chain: string; accountAddress: string; timestamp: number; classificationData: UTXOTranslateClassificationDataV5; transfers: UTXOTranslateTransferV5[]; values: UTXOTranslateValueItem[]; rawTransactionData: UTXOTranslateRawTransactionDataV5; } /** * Union type for UTXO transactions */ type UTXOTranslateTransaction = UTXOTranslateTransactionV2 | UTXOTranslateTransactionV5; /** * Response type for the Transactions endpoint */ interface UTXOTranslateTransactionsResponse { items: UTXOTranslateTransaction[]; pageNumber: number; pageSize: number; hasNextPage: boolean; nextPageUrl: string | null; } /** * UTXO token balance information */ interface UTXOTranslateBalanceData { balance: string; token: { symbol: string; name: string; decimals: number; address: string; }; } /** * Response type for token balances endpoint */ type UTXOTranslateBalancesResponse = UTXOTranslateBalanceData[]; /** * Bitcoin address type for getAddressesByMasterKey * Supports both numeric and string values */ type BitcoinAddressType = 0 | 1 | 2 | 3 | 'Legacy' | 'SegWit' | 'SegWitP2SH' | 'Taproot'; /** * Options for getAddressesByMasterKey endpoint */ interface GetAddressesByMasterKeyOptions { /** * Number of addresses to derive from the master key * Values between 1-10000. Default: 20 */ count?: number; /** * Bitcoin address type to generate * Supports both numeric (0-3) and string values * 0/'Legacy': Legacy P2PKH addresses starting with "1" - Most compatible, higher fees * 1/'SegWit': Native SegWit P2WPKH addresses starting with "bc1" - Lower fees, modern standard * 2/'SegWitP2SH': SegWit P2SH-P2WPKH addresses starting with "3" - Backward compatible SegWit * 3/'Taproot': Taproot P2TR addresses starting with "bc1p" - Enhanced privacy and flexibility * Default: 'Legacy' (0) */ addressType?: BitcoinAddressType; } /** * Response type for getAddressesByXpub endpoint (Bitcoin-specific) */ type UTXOTranslateAddressesResponse = string[]; /** * UTXO Transaction Job for batch processing * Based on actual API response from POST /utxo/{chain}/txs/job/start */ interface UTXOTranslateTransactionJob { jobId: string; nextPageUrl: string; } /** * UTXO Transaction Job Response for batch processing * Based on actual API response from GET /utxo/{chain}/txs/job/{jobId} */ interface UTXOTranslateTransactionJobResponse { items: UTXOTranslateTransaction[]; pageSize: number; hasNextPage: boolean; nextPageUrl: string | null; } /** * UTXO Job Progress Response (425 status) * Returned when job is still processing */ interface UTXOTranslateJobProgressResponse { detail: { message: string; txsProcessed: number; }; } /** * Delete transaction job response for UTXO * Based on actual API response from DELETE /utxo/{chain}/txs/job/{jobId} */ interface UTXOTranslateDeleteTransactionJobResponse { message: string; } /** * Interface representing a UTXO chain as returned by the Pricing API * Based on actual API response from GET /utxo/chains */ interface UTXOPricingChain { name: string; ecosystem: 'utxo'; nativeCoin: { name: string; symbol: string; address: string; decimals: number; }; } /** * Response from the UTXO pricing chains endpoint */ type UTXOPricingChainsResponse = UTXOPricingChain[]; /** * Interface representing a token in UTXO pricing response * Based on actual API response from GET /utxo/{chain}/price/{token} */ interface UTXOPricingToken { symbol: string; name: string; address: string; decimals: number; } /** * Interface representing price information in UTXO pricing response * Based on actual API response from GET /utxo/{chain}/price/{token} */ interface UTXOPricingPriceInfo { amount: string; currency: string; status: string; } /** * Interface representing the complete UTXO pricing response * Based on actual API response from GET /utxo/{chain}/price/{token} */ interface UTXOPricingPrice { chain: string; token: UTXOPricingToken; price: UTXOPricingPriceInfo; priceType: string; priceStatus: string; } /** * Class representing the UTXO translation module. */ declare class TranslateUTXO { private request; private apiKey; /** * Create a TranslateUTXO instance. * @param {string} apiKey - The API key to authenticate requests. * @param {Partial<RetryConfig>} [retryConfig] - Optional retry configuration for enhanced resilience. * @param {FetchConfig} [fetchConfig] - Optional fetch configuration for timeouts, abort signals, and custom headers. * @throws Will throw an error if the API key is not provided. */ constructor(apiKey: string, retryConfig?: Partial<RetryConfig>, fetchConfig?: FetchConfig); /** * Returns a list with the names of the UTXO blockchains currently supported by this API. * Use the provided chain name when calling other methods. * @returns {Promise<UTXOTranslateChain[]>} A promise that resolves to an array of chains. */ getChains(): Promise<UTXOTranslateChain[]>; /** * Get a pagination object to iterate over transactions pages. * @param {string} chain - The chain name. * @param {string} accountAddress - The account address. * @param {PageOptions} pageOptions - The page options object. Use v5Format: true to get v5 format responses. * @returns {Promise<TransactionsPage<UTXOTranslateTransaction>>} A promise that resolves to a TransactionsPage instance. */ getTransactions(chain: string, accountAddress: string, pageOptions?: PageOptions): Promise<TransactionsPage<UTXOTranslateTransaction>>; /** * @deprecated Use getTransactions instead. This method will be removed in v2.0.0. * Get a pagination object to iterate over transactions pages. * @param {string} chain - The chain name. * @param {string} accountAddress - The account address. * @param {PageOptions} pageOptions - The page options object. * @returns {Promise<TransactionsPage<UTXOTranslateTransaction>>} A promise that resolves to a TransactionsPage instance. */ Transactions(chain: string, accountAddress: string, pageOptions?: PageOptions): Promise<TransactionsPage<UTXOTranslateTransaction>>; /** * Utility endpoint for Bitcoin. Returns a list of derived addresses for the given master key. * @param {string} masterKey - The master key (xpub, ypub, or zpub) to derive BTC addresses from. * @param {GetAddressesByMasterKeyOptions} options - Optional parameters for address derivation. * @returns {Promise<UTXOTranslateAddressesResponse>} A promise that resolves to an array of derived addresses. * @throws {TransactionError} If there are validation errors in the request. */ getAddressesByMasterKey(masterKey: string, options?: GetAddressesByMasterKeyOptions): Promise<UTXOTranslateAddressesResponse>; /** * @deprecated Use getAddressesByMasterKey instead. This method will be removed in v2.0.0. * Utility endpoint for Bitcoin. Returns a list of derived addresses for the given xpub address. * @param {string} xpub - The xpub address to derive BTC addresses from. * @param {GetAddressesByMasterKeyOptions} options - Optional parameters for address derivation. * @returns {Promise<UTXOTranslateAddressesResponse>} A promise that resolves to an array of derived addresses. * @throws {TransactionError} If there are validation errors in the request. */ getAddressesByXpub(xpub: string, options?: GetAddressesByMasterKeyOptions): Promise<UTXOTranslateAddressesResponse>; /** * Returns all of the available transaction information for the chain and transaction hash requested. * @param {string} chain - The chain name. * @param {string} hash - The transaction hash. * @param {number} [txTypeVersion=5] - The transaction format version (2 or 5). Defaults to 5. * @param {string} [viewAsAccountAddress] - Optional account address to view the transaction from its perspective. * @returns {Promise<UTXOTranslateTransaction>} A promise that resolves to the transaction details. * @throws {TransactionError} If there are validation errors in the request. */ getTransaction(chain: string, hash: string, txTypeVersion?: number, viewAsAccountAddress?: string): Promise<UTXOTranslateTransaction>; /** * Get token balances for an account address. * @param {string} chain - The chain name. * @param {string} accountAddress - The account address. * @param {number} [blockNumber] - Optional block number to retrieve balances as of. * @param {number} [timestamp] - Optional timestamp to retrieve balances as of. * @param {boolean} [includePrices=true] - Optional. Whether to include token prices in the response. * @param {boolean} [excludeZeroPrices=false] - Optional. Whether to exclude tokens with zero price. * @returns {Promise<UTXOTranslateBalancesResponse>} A promise that resolves to the balances data. * @throws {TransactionError} If there are validation errors in the request. */ getTokenBalances(chain: string, accountAddress: string, blockNumber?: number, timestamp?: number, includePrices?: boolean, excludeZeroPrices?: boolean): Promise<UTXOTranslateBalancesResponse>; /** * Starts a transaction job for processing multiple transactions in a UTXO wallet. * The job will be processed in the background, and results will become available once all transactions have been fetched. * @param {string} chain - The chain name. * @param {string} accountAddress - The account address. * @param {number} [startBlock] - Optional starting block number. * @param {number} [endBlock] - Optional ending block number. * @param {number} [startTimestamp] - Optional starting timestamp. * @param {number} [endTimestamp] - Optional ending timestamp. * @returns {Promise<UTXOTranslateTransactionJob>} A promise that resolves to the transaction job. * @throws {TransactionError} If there are validation errors in the request. */ startTransactionJob(chain: string, accountAddress: string, startBlock?: number, endBlock?: number, startTimestamp?: number, endTimestamp?: number): Promise<UTXOTranslateTransactionJob>; /** * Gets the results of a transaction job. * If the job is not finished yet, this will return a 425 status with progress information. * @param {string} chain - The chain name. * @param {string} jobId - The job ID from the transaction job. * @param {PageOptions} pageOptions - The page options. * @returns {Promise<UTXOTranslateTransactionJobResponse>} A promise that resolves to the transaction job response. * @throws {TransactionError} If there are validation errors in the request or if the job is not finished (425 status). */ getTransactionJobResults(chain: string, jobId: string, pageOptions?: PageOptions): Promise<UTXOTranslateTransactionJobResponse>; /** * Deletes a transaction job. * @param {string} chain - The chain name. * @param {string} jobId - The job ID to delete. * @returns {Promise<UTXOTranslateDeleteTransactionJobResponse>} A promise that resolves to the deletion confirmation message. * @throws {TransactionError} If there are validation errors in the request. */ deleteTransactionJob(chain: string, jobId: string): Promise<UTXOTranslateDeleteTransactionJobResponse>; } /** * Cosmos ecosystem-specific types */ /** * Native coin information for Cosmos chains */ interface COSMOSPricingNativeCoin { name: string; symbol: string; address: string; decimals: number; } /** * Represents a Cosmos chain from the pricing /cosmos/chains endpoint */ interface COSMOSPricingChain { name: string; ecosystem: string; nativeCoin: COSMOSPricingNativeCoin; } /** * Response type for the pricing getChains method */ type COSMOSPricingChainsResponse = COSMOSPricingChain[]; /** * Token information for pricing - matches actual API response * All fields are required based on actual API response structure */ interface COSMOSPricingToken { address: string; symbol: string; name: string; decimals: number; } /** * Exchange information for pricing - matches actual API response * Only name can be null based on actual API response */ interface COSMOSPricingExchange { name: string | null; } /** * Price information - matches actual API response * Amount is always present based on actual API response */ interface COSMOSPricingPrice { amount: string; } /** * Pool pricing response for Cosmos chains - matches actual API response exactly * Updated to reflect actual API response structure with correct nullable fields */ interface COSMOSPricingPoolPricing { chain: string; exchange: COSMOSPricingExchange; poolAddress: string; baseToken: COSMOSPricingToken; quoteToken: COSMOSPricingToken; price: COSMOSPricingPrice; } /** * Represents a Cosmos chain from the /cosmos/chains endpoint */ interface COSMOSTranslateChain { name: string; ecosystem: string; nativeCoin: { name: string; symbol: string; address: string; decimals: number; }; tier: number; } /** * Response type for the getChains method */ type COSMOSTranslateChainsResponse = COSMOSTranslateChain[]; /** * Token balance for Cosmos */ interface COSMOSTranslateTokenBalance { balance: string; token: { symbol: string; name: string; decimals: number; address: s