import { Buffer } from 'buffer'; import { type BigNumberish, type BytesLike, type Numeric } from 'ethers'; import type { Chain } from './chain.ts'; import { type NetworkInfo, type WithLogger, ChainFamily } from './types.ts'; /** * Returns *some* block number with timestamp prior to `timestamp` * * @param getBlockTimestamp - function to get block timestamp * @param recentBlockNumber - a block guaranteed to be after `timestamp` (e.g. latest) * @param timestamp - target timestamp * @param precision - returned blockNumber should be within this many blocks before timestamp * @returns blockNumber of a block at provider which is close but before target timestamp * @throws {@link CCIPBlockBeforeTimestampNotFoundError} if no block exists before the given timestamp */ export declare function getSomeBlockNumberBefore(getBlockTimestamp: (blockNumber: number) => Promise, recentBlockNumber: number, timestamp: number, { precision, logger }?: { precision?: number; } & WithLogger): Promise; /** * Converts a chain selector, chain ID, or chain name to complete network information * * @param selectorOrIdOrName - Can be: * - Chain selector as bigint or numeric string * - Chain ID as number, bigint or string (EVM: "1", Aptos: "aptos:1", Solana: genesisHash) * - Chain name as string ("ethereum-mainnet") * @returns Complete NetworkInfo object * @throws {@link CCIPChainNotFoundError} if chain is not found * * @example * ```typescript * import { networkInfo } from '@chainlink/ccip-sdk' * * // By chain name * const sepolia = networkInfo('ethereum-testnet-sepolia') * console.log('Selector:', sepolia.chainSelector) * * // By chain selector * const fuji = networkInfo(14767482510784806043n) * console.log('Name:', fuji.name) // 'avalanche-testnet-fuji' * * // By chain ID * const mainnet = networkInfo(1) * console.log('Family:', mainnet.family) // 'EVM' * ``` */ export declare const networkInfo: import("micro-memoize").Memoized<(selectorOrIdOrName: bigint | number | string) => NetworkInfo, {}>; /** * Generates block ranges for paginated log queries. * * @param params - Range parameters: * - `singleBlock` - yields a single `{ fromBlock, toBlock }` for that block. * - `startBlock` + `endBlock` - moves forward from `startBlock` up to `endBlock`. * - `page` - step size per range (default 10 000). * @returns Generator of `{ fromBlock, toBlock }` pairs, optionally with a `progress` percentage * string when iterating forward. */ export declare function blockRangeGenerator(params: { page?: number; } & ({ endBlock: number; startBlock: number; } | { singleBlock: number; })): Generator<{ fromBlock: number; toBlock: number; progress?: undefined; } | { fromBlock: number; toBlock: number; progress: string; }, void, unknown>; /** * JSON replacer function that converts BigInt values to strings. * @param _key - Property key (unused). * @param value - Value to transform. * @returns String representation if BigInt, otherwise unchanged value. * @example * ```typescript * import { bigIntReplacer } from '@chainlink/ccip-sdk' * * const data = { amount: 1000000000000000000n } * const json = JSON.stringify(data, bigIntReplacer) * console.log(json) // '{"amount":"1000000000000000000"}' * ``` * @see {@link bigIntReviver} - Revive BigInt values when parsing */ export declare function bigIntReplacer(_key: string, value: unknown): unknown; /** * JSON reviver function that converts numeric strings back to BigInt. * @param _key - Property key (unused). * @param value - Value to transform. * @returns BigInt if numeric string, otherwise unchanged value. * @example * ```typescript * import { bigIntReviver } from '@chainlink/ccip-sdk' * * const json = '{"amount":"1000000000000000000"}' * const data = JSON.parse(json, bigIntReviver) * console.log(typeof data.amount) // 'bigint' * ``` * @see {@link bigIntReplacer} - Stringify BigInt values */ export declare function bigIntReviver(_key: string, value: unknown): unknown; /** * Parses JSON text with BigInt support for large integers. * Uses yaml parser which handles integers as BigInt when they exceed safe integer range. * @param text - JSON string to parse * @returns Parsed object with large integers as BigInt */ export declare function parseJson(text: string): T; /** * Decode address from a 32-byte hex string. * * @param address - Address bytes to decode (hex string or Uint8Array) * @param family - Chain family for address format (defaults to EVM) * @returns Decoded address string * @throws {@link CCIPChainFamilyUnsupportedError} if chain family is not supported * * @example * ```typescript * import { decodeAddress, ChainFamily } from '@chainlink/ccip-sdk' * * // Decode EVM address from 32-byte hex * const evmAddr = decodeAddress('0x000000000000000000000000abc123...', ChainFamily.EVM) * console.log(evmAddr) // '0xABC123...' * * // Decode Solana address * const solAddr = decodeAddress(bytes, ChainFamily.Solana) * console.log(solAddr) // Base58 encoded address * ``` */ export declare function decodeAddress(address: BytesLike, family?: ChainFamily): string; /** * Validate a value is a txHash string in some supported chain family * @param txHash - Value to check * @param family - Optional chain family to validate against * @returns true if value is a valid transaction hash * @throws {@link CCIPChainFamilyUnsupportedError} if specified chain family is not supported */ export declare function isSupportedTxHash(txHash: unknown, family?: ChainFamily): txHash is string; /** * Version of decodeAddress which is aware of custom cross-chain OnRamp formats **/ export declare function decodeOnRampAddress(address: BytesLike, family?: ChainFamily): string; /** * Converts little-endian bytes to BigInt. * @param data - Little-endian byte data. * @returns BigInt value. */ export declare function leToBigInt(data: BytesLike | readonly number[]): bigint; /** * Converts a BigNumber to little-endian byte array. * @param value - Numeric value to convert. * @param width - Optional byte width for padding. * @returns Little-endian Uint8Array. */ export declare function toLeArray(value: BigNumberish, width?: Numeric): Uint8Array; /** * Checks if the given data is a valid Base64 encoded string. * @param data - Data to check. * @returns True if valid Base64 string. */ export declare function isBase64(data: unknown): data is string; /** * Converts various data formats to Uint8Array. * @param data - Bytes, number array, or Base64 string. * @returns Uint8Array representation. * @throws {@link CCIPDataFormatUnsupportedError} if data format is not recognized * * @example * ```typescript * import { getDataBytes } from '@chainlink/ccip-sdk' * * // From hex string * const bytes1 = getDataBytes('0x1234abcd') * * // From number array * const bytes2 = getDataBytes([0x12, 0x34, 0xab, 0xcd]) * * // From Base64 * const bytes3 = getDataBytes('EjSrzQ==') * ``` */ export declare function getDataBytes(data: BytesLike | readonly number[]): Uint8Array; /** * Converts bytes to a Node.js Buffer. * @param bytes - Bytes to convert (hex string, Uint8Array, Base64, etc). * @returns Node.js Buffer. */ export declare function bytesToBuffer(bytes: BytesLike | readonly number[]): Buffer; /** * Extracts address bytes, handling both hex and Base58 formats. * @param address - Address in hex or Base58 format. * @returns Address bytes as Uint8Array. */ export declare function getAddressBytes(address: BytesLike | readonly number[]): Uint8Array; /** * Encodes remote/alien addresses for Any SRC * * Addresses less than 32 bytes (EVM 20B, Aptos/Solana/Sui 32B) are zero-padded to 32 bytes * Addresses greater than 32 bytes (e.g., TON 4+32=36B) are used as raw bytes without padding */ export declare function encodeAddressToAny(address: BytesLike): Buffer; /** * Converts snake_case strings to camelCase */ export declare function snakeToCamel(str: string): string; /** * Recursively converts all snake_case keys in an object to camelCase * Only converts keys that actually have snake_case format */ export declare function convertKeysToCamelCase(obj: unknown, mapValues?: (value: unknown, key?: string) => unknown, key?: string): unknown; /** * Promise-based sleep utility. * @param ms - Duration in milliseconds. * @returns Promise that resolves after the specified duration. */ export declare const sleep: (ms: number) => Promise; /** * Configuration for the withRetry utility. */ export type WithRetryConfig = { /** Maximum number of retry attempts */ maxRetries: number; /** Initial delay in milliseconds before the first retry */ initialDelayMs: number; /** Multiplier applied to delay after each retry */ backoffMultiplier: number; /** Maximum delay in milliseconds between retries */ maxDelayMs: number; /** Whether to respect the error's retryAfterMs hint */ respectRetryAfterHint: boolean; /** Optional logger for retry attempts */ logger?: { debug: (...args: unknown[]) => void; warn: (...args: unknown[]) => void; }; }; /** * Executes an async operation with retry logic and exponential backoff. * Only retries on transient errors (as determined by shouldRetry from errors/utils). * * @param operation - Async function to execute * @param config - Retry configuration * @returns Promise resolving to the operation result * @throws The last error encountered after all retries are exhausted * * @example * ```typescript * const result = await withRetry( * () => apiClient.getMessageById(id), * { * maxRetries: 3, * initialDelayMs: 1000, * backoffMultiplier: 2, * maxDelayMs: 30000, * respectRetryAfterHint: true, * } * ) * ``` */ export declare function withRetry(operation: () => Promise, config: WithRetryConfig): Promise; /** * Parses a typeAndVersion string into its components. * @param typeAndVersion - String in format "TypeName vX.Y.Z". * @returns Tuple of `[normalizedType, normalizedVersion, original, suffix?]` where * `normalizedType` has kebab-to-PascalCase, `CCIP` uppercasing, and ramp casing applied * (e.g., `"ccip-offramp"` becomes `"CCIPOffRamp"`), and `normalizedVersion` has the patch * component forced to `.0` for core contracts (OnRamp, OffRamp, Router). * @throws {@link CCIPTypeVersionInvalidError} if string format is invalid */ export declare function parseTypeAndVersion(typeAndVersion: string): Awaited>; type RateLimitOpts = { maxRequests: number; windowMs: number; maxRetries: number; }; /** * Creates a rate-limited fetch function with retry logic. * Configurable via maxRequests, windowMs, and maxRetries options. * @returns Rate-limited fetch function. */ export declare function createRateLimitedFetch(opts?: Partial, { logger, abort }?: { abort?: AbortSignal; } & WithLogger): typeof fetch; /** * Performs a fetch request with timeout and abort signal support. * * @param url - URL to fetch * @param operation - Operation name for error context * @param opts - Optional configuration: * - `timeoutMs` — request timeout in milliseconds (default: 30000). * - `signal` — an external `AbortSignal` to cancel the request. * - `fetch` — custom fetch function (defaults to `globalThis.fetch`). * - `init` — additional `RequestInit` fields merged into the fetch call. * @returns Promise resolving to Response * @throws CCIPTimeoutError if request times out * @throws CCIPAbortError if request is aborted via signal */ export declare function fetchWithTimeout(url: string, operation: string, opts?: { timeoutMs?: number; signal?: AbortSignal; fetch?: typeof globalThis.fetch; init?: RequestInit; }): Promise; declare const util: { inspect: ((v: unknown) => string) & { custom: symbol; defaultOptions: Record; }; } | { inspect: ((v: unknown) => string) & { custom: symbol; defaultOptions: { depth: number; }; }; }; export { util }; /** * Converts an AbortSignal into a Promise that rejects when the signal is aborted. * * The listener closure captures `reject` strongly and is held alive by the * signal, so the promise cannot be GC'd while the signal is alive. The * `once` option ensures the listener (and its reference to `reject`) is * released as soon as the signal fires. * * @param signal - AbortSignal to convert * @returns Promise that rejects with the signal's reason when aborted */ export declare function signalToPromise(signal: AbortSignal): Promise; //# sourceMappingURL=utils.d.ts.map