import { TuwaErrorState, OrbitAdapter, BaseAdapter, OrbitGenericAdapter } from '@tuwaio/orbit-core'; import * as zustand from 'zustand'; import { StoreApi } from 'zustand'; import { PersistOptions } from 'zustand/middleware'; /** * A utility type for creating modular Zustand store slices, enabling composable state management. * @template T The state slice being defined. * @template S The full store state that includes the slice `T`. */ type StoreSlice = (set: StoreApi['setState'], get: StoreApi['getState']) => T; /** * Enum representing the different tracking strategies available for transactions. * Each tracker corresponds to a specific method of monitoring a transaction's lifecycle. */ declare enum TransactionTracker { /** For standard on-chain EVM transactions tracked by their hash. */ Ethereum = "ethereum", /** For multi-signature transactions managed and executed via a Safe contract. */ Safe = "safe", /** * For meta-transactions relayed and executed by the Gelato Network. * @deprecated Gelato gasless relay is deprecated. Use TransactionTracker.ERC4337 instead. */ Gelato = "gelato", /** The tracker for monitoring standard Solana transaction signatures. */ Solana = "solana", /** For native ERC-4337 UserOperation transactions tracked via bundler RPC. */ ERC4337 = "erc4337" } /** * Represents the terminal status of a transaction after it has been processed. */ declare enum TransactionStatus { /** The transaction failed to execute due to an on-chain error or rejection. */ Failed = "Failed", /** The transaction was successfully mined and included in a block. */ Success = "Success", /** The transaction was replaced by another with the same nonce (e.g., a speed-up or cancel). */ Replaced = "Replaced" } /** * A union type representing the unique identifier returned by an `actionFunction` * after a transaction is submitted to the network or a relay service. * * This key is crucial for the adapter to determine which tracker should * monitor the transaction. * * It can be one of the following: * - A standard `0x...` transaction hash (`Hex`). * - A Solana transaction signature (string). */ type ActionTxKey = `0x${string}` | string; /** * The fundamental structure for any transaction being tracked by Pulsar. * This serves as the base upon which chain-specific transaction types are built. */ type BaseTransaction = { /** The chain identifier (e.g., 1 for Ethereum Mainnet, 'SN_MAIN' for Starknet). */ chainId: number | string; /** * User-facing description. Can be a single string for all states, or a tuple for specific states. * Each string is validated before execution and persistence. It must be 300 characters or less and must not contain * executable-like patterns such as `eval(` or `javascript:`. * @example * // A single description for all states * description: 'Swap 1 ETH for 1,500 USDC' * // Specific descriptions for each state in order: [pending, success, error, replaced] * description: ['Swapping...', 'Swapped Successfully', 'Swap Failed', 'Swap Replaced'] */ description?: string | [string, string, string, string]; /** The error state if the transaction failed, containing message and raw error details. */ error?: TuwaErrorState; /** The on-chain timestamp (in seconds) when the transaction was finalized. */ finishedTimestamp?: number; /** The sender's wallet address. */ from: string; /** A flag indicating if the transaction is in a failed state. */ isError?: boolean; /** A UI flag to control the visibility of a detailed tracking modal for this transaction. */ isTrackedModalOpen?: boolean; /** The local timestamp (in seconds) when the transaction was initiated by the user. */ localTimestamp: number; /** * Custom JSON-serializable data (strings or numbers) to associate with the transaction. * The serialized UTF-8 payload must be 10KB or less and string values must not contain executable-like patterns. */ payload?: Record; /** A flag indicating if the transaction is still awaiting on-chain confirmation. */ pending: boolean; /** The final on-chain status of the transaction. */ status?: TransactionStatus; /** * User-facing title. Can be a single string for all states, or a tuple for specific states. * Each string is validated before execution and persistence. It must be 100 characters or less and must not contain * executable-like patterns such as `eval(` or `javascript:`. * @example * // A single title for all states * title: 'ETH/USDC Swap' * // Specific titles for each state in order: [pending, success, error, replaced] * title: ['Processing Swap', 'Swap Complete', 'Swap Error', 'Swap Replaced'] */ title?: string | [string, string, string, string]; /** The specific tracker responsible for monitoring this transaction's status. */ tracker: TransactionTracker; /** The unique identifier for the transaction (e.g., EVM hash, Solana signature, or Gelato task ID). */ txKey: string; /** The application-specific type or category of the transaction (e.g., 'SWAP', 'APPROVE'). */ type: string; /** The type of connector used to sign the transaction (e.g., 'injected', 'walletConnect'). */ connectorType: string; /** The number of confirmations required for the transaction to be considered confirmed. */ requiredConfirmations?: number; /** The number of confirmations received. A string value indicates a confirmed transaction, while `null` means it's pending. */ confirmations?: number | string | null; /** The RPC URL to use for the transaction. Required for Solana transactions. */ rpcUrl?: string; /** Indicates the synchronization status of the transaction with the remote backend (Quasar). */ syncStatus?: 'synced' | 'pending-sync'; }; /** * Represents an EVM-specific transaction, extending the base properties with EVM fields. */ type EvmTransaction = BaseTransaction & { /** The adapter type for EVM transactions. */ adapter: OrbitAdapter.EVM; /** The on-chain transaction hash, available after submission. */ hash?: `0x${string}`; /** The data payload for the transaction, typically for smart contract interactions. */ input?: `0x${string}`; /** The maximum fee per gas for an EIP-1559 transaction (in wei). */ maxFeePerGas?: string; /** The maximum priority fee per gas for an EIP-1559 transaction (in wei). */ maxPriorityFeePerGas?: string; /** The transaction nonce, a sequential number for the sender's account. */ nonce?: number; /** The hash of a transaction that this one replaced. */ replacedTxHash?: `0x${string}`; /** The recipient's address or contract address. */ to?: `0x${string}`; /** The amount of native currency (in wei) being sent. */ value?: string; /** Optional custom bundler RPC URL for ERC-4337 UserOperation tracking. */ bundlerUrl?: string; /** Optional Pimlico API key for ERC-4337 UserOperation tracking. */ pimlicoApiKey?: string; }; /** * Represents a Solana-specific transaction, extending the base properties. */ type SolanaTransaction = BaseTransaction & { /** The adapter type for Solana transactions. */ adapter: OrbitAdapter.SOLANA; /** The transaction fee in lamports. */ fee?: number; /** The instructions included in the transaction. */ instructions?: unknown[]; /** The recent blockhash used for the transaction. */ recentBlockhash?: string; /** The slot in which the transaction was processed. */ slot?: number; }; /** * Represents a Starknet-specific transaction, extending the base properties. */ type StarknetTransaction = BaseTransaction & { /** The adapter type for Starknet transactions. */ adapter: OrbitAdapter.Starknet; /** The actual fee paid for the transaction. */ actualFee?: { amount: string; unit: string; }; /** The address of the contract being interacted with. */ contractAddress?: string; }; /** A union type representing any possible transaction structure that Pulsar can handle. */ type Transaction = EvmTransaction | SolanaTransaction | StarknetTransaction; /** * Represents the parameters required to initiate a new transaction tracking flow. */ type InitialTransactionParams = Pick & Pick & { /** The specific blockchain adapter for this transaction. */ adapter: OrbitAdapter; /** The function that executes the on-chain action (e.g., sending a transaction) and returns a preliminary identifier like a hash. */ actionFunction: (...args: any[]) => Promise; /** The target chain ID for the transaction. */ desiredChainID: number | string; /** If true, the detailed tracking modal will open automatically upon initiation. */ withTrackedModal?: boolean; /** The specific tracker responsible for monitoring this transaction's status. Required for Gelato / ERC-4337 tracker. */ tracker?: TransactionTracker; /** @deprecated Gelato relay is deprecated. */ gelatoApiKey?: string; }; /** * Represents a transaction in its temporary, pre-submission state. * This is used for UI feedback while the transaction is being signed and sent. */ type InitialTransaction = InitialTransactionParams & { /** Normalized error if the initialization fails (e.g., user rejects signature). */ error?: TuwaErrorState; /** A flag indicating if the transaction is being processed (e.g., waiting for signature). */ isInitializing: boolean; /** The `txKey` of the on-chain transaction that this action produced, used for linking the states. */ lastTxKey?: string; /** The local timestamp when the user initiated the action. */ localTimestamp: number; }; /** * Defines the standard callback structure for transaction events. * @template T The specific transaction type, extending `Transaction`. */ interface TrackerCallbacks { onSuccess?: (tx: T) => Promise | void; onError?: (error: unknown, tx?: T) => Promise | void; onReplaced?: (newTx: T, oldTx: T) => Promise | void; } /** * Callbacks for synchronizing local transaction state with a remote backend. * These are injected into the store at creation time. */ interface SyncCallbacks { /** * Called immediately after a transaction is created locally (added to pool). * Use this to POST the active pending transaction to the backend. */ onRemoteCreate?: (tx: T) => Promise; } /** * Callback executed before Pulsar initializes or submits a transaction. * * Throw an error from this function to block the transaction before `initialTx`, wallet interaction, * persistence, or remote synchronization starts. */ type BeforeTxProcess = () => Promise | void; /** * The configuration object containing one or more transaction adapters. * @template T The specific transaction type. */ type PulsarAdapter = OrbitGenericAdapter> & { /** Optional global preflight callback executed before every transaction unless locally overridden. */ beforeTxProcess?: BeforeTxProcess; maxTransactions?: number; gelatoApiKey?: string; /** Optional setting to abort the transaction if the beforeTxProcess hook or remote creation fails. Defaults to true. */ abortOnTxError?: boolean; } & SyncCallbacks; /** * Represents a tracker for a specific transaction tied to an action and a connector. * * @typedef {Object} CheckTxTracker * @property {ActionTxKey} actionTxKey - The key identifying the specific action related to the transaction. * @property {string} connectorType - The type of connector used for the transaction (e.g., wallet provider, blockchain interface). * @property {TransactionTracker} [tracker] - An optional tracker object that monitors the status and progress of the transaction. * @property {string} [gelatoApiKey] - @deprecated Gelato API key for Gelato relayer integration. * @property {string} [bundlerUrl] - Optional custom bundler RPC URL for ERC-4337 UserOperation tracking. * @property {string} [pimlicoApiKey] - Optional Pimlico API key for ERC-4337 UserOperation tracking. */ type CheckTxTracker = { actionTxKey: ActionTxKey; connectorType: string; tracker?: TransactionTracker; /** @deprecated Gelato relay is deprecated. Use bundlerUrl / pimlicoApiKey with ERC-4337 instead. */ gelatoApiKey?: string; /** Optional custom bundler RPC URL for ERC-4337 UserOperation tracking. */ bundlerUrl?: string; /** Optional Pimlico API key for ERC-4337 UserOperation tracking. */ pimlicoApiKey?: string; }; /** * Defines the interface for a transaction adapter, which provides chain-specific logic and utilities. * @template T The specific transaction type, extending `Transaction`. */ type TxAdapter = Pick & { /** The unique key identifying this adapter. */ key: OrbitAdapter; /** Returns information about the currently connected connector. */ getConnectorInfo: () => { /** The currently connected wallet address. */ walletAddress: string; /** The type of the connector (e.g., 'metamask', 'phantom'). */ connectorType: string; }; /** * Ensures the connected wallet is on the correct network for the transaction. * * This method should throw an error if the chain is mismatched. * @param chainId The desired chain ID for the transaction. * @param walletChainId The connected wallet chain ID. */ checkChainForTx: (chainId: string | number) => Promise; /** * Determines the appropriate tracker and final `txKey` from the result of an action. * @returns An object containing the final `txKey` and the `TransactionTracker` to be used. */ checkTransactionsTracker: ({ actionTxKey, connectorType, tracker }: CheckTxTracker) => { txKey: string; tracker: TransactionTracker; }; /** * Selects and initializes the correct background tracker for a given transaction. * @param params The parameters for initializing the tracker, including the transaction and store callbacks. */ checkAndInitializeTrackerInStore: (params: { tx: T; gelatoApiKey?: string; } & TrackerCallbacks & Pick, 'updateTxParams' | 'removeTxFromPool' | 'transactionsPool'>) => Promise | void; /** * Optional: Logic to cancel a pending EVM transaction. * @param tx The transaction to cancel. * @returns The new transaction hash for the cancellation. */ cancelTxAction?: (tx: T) => Promise; /** * Optional: Logic to speed up a pending EVM transaction. * @param tx The transaction to speed up. * @returns The new transaction hash for the sped-up transaction. */ speedUpTxAction?: (tx: T) => Promise; /** * Optional: Logic to retry a failed transaction. * @param params The parameters for retrying the transaction. * @param params.txKey The unique key of the transaction to retry. * @param params.tx The initial parameters of the transaction. * @param params.onClose Callback function to close the tracking modal. */ retryTxAction?: (params: { txKey: string; tx: InitialTransactionParams; onClose: (txKey?: string) => void; } & Partial, 'executeTxAction'>>) => Promise; /** * Optional: Constructs a full explorer URL for a specific transaction. * May require the full transaction pool to resolve details for replaced transactions. * @param tx The transaction object. * @returns The full URL to the transaction on the explorer. */ getExplorerTxUrl?: (tx: T) => string; }; /** * Defines the structure of the transaction pool, a key-value store of transactions indexed by their unique keys. * @template T The type of the transaction object being tracked. */ type TransactionPool = Record; /** * A utility type that creates a union of all fields that can be safely updated * on a transaction object via the `updateTxParams` action. This ensures type safety * and prevents accidental modification of immutable properties. */ type UpdatableTransactionFields = Partial> & Partial>; /** * The interface for the base transaction tracking store slice. * It includes the state and actions for managing the transaction lifecycle. * @template T The specific transaction type. */ interface IInitializeTxTrackingStore { /** A pool of all transactions currently being tracked, indexed by `txKey`. */ transactionsPool: TransactionPool; /** The `txKey` of the most recently added transaction. */ lastAddedTxKey?: string; /** The state for a transaction being initiated, used for verify feedback before it's submitted to the chain. */ initialTx?: InitialTransaction; /** * Adds a new transaction to the tracking pool and marks it as pending. * @param tx The transaction object to add. */ addTxToPool: (tx: T) => Promise; /** * Updates one or more properties of an existing transaction in the pool. * @param txKey The key of the transaction to update. * @param fields The partial object containing the fields to update. */ updateTxParams: (txKey: string, fields: UpdatableTransactionFields) => void; /** * Removes a transaction from the tracking pool by its key. * @param txKey The key of the transaction to remove. */ removeTxFromPool: (txKey: string) => void; /** * Closes the tracking modal for a transaction and clears any initial transaction state. * @param txKey The optional key of the transaction modal to close. */ closeTxTrackedModal: (txKey?: string) => void; /** * A selector function to retrieve the key of the last transaction added to the pool. * @returns The key of the last added transaction, or undefined if none exists. */ getLastTxKey: () => string | undefined; /** * A record of transaction keys that failed to sync with the remote backend (Quasar) * when `onRemoteCreate` was called. They will be retried automatically. */ unsyncedTxKeys?: Record; /** * Attempts to synchronize any transactions in `unsyncedTxKeys` that have reached a terminal * status but failed their initial `onRemoteCreate` call. */ reconcileUnsyncedTransactions: () => Promise; } /** * The complete interface for the Pulsar transaction tracking store. * @template T The transaction type. */ type ITxTrackingStore = IInitializeTxTrackingStore & { /** A getter function that returns the configured transaction adapter(s). */ getAdapter: () => TxAdapter | TxAdapter[]; /** * The primary method for initiating and tracking a new transaction from start to finish. * It manages UI state, executes the on-chain action, and initiates background tracking. * * @param params The parameters for handling the transaction. * @param params.actionFunction The async function to execute (e.g., a smart contract write call). Must return a unique key or undefined. * @param params.params The metadata for the transaction. Title, description, and payload are validated before execution. * @param params.defaultTracker The default tracker to use if it cannot be determined automatically. * @param params.beforeTxProcess Optional local preflight callback. When provided, it overrides the global callback from `createPulsarStore`. * @param params.onSuccess Callback to execute when the transaction is successfully submitted. * @param params.onError Callback to execute when the transaction fails. * @param params.onReplaced Callback to execute when the transaction is replaced. */ executeTxAction: (params: { actionFunction: () => Promise; params: Omit; defaultTracker?: TransactionTracker; beforeTxProcess?: BeforeTxProcess; abortOnTxError?: boolean; } & TrackerCallbacks) => Promise; /** * Initializes trackers for all pending transactions in the pool. * This is essential for resuming tracking after a page reload or application restart. */ initializeTransactionsPool: () => Promise; /** * Cross-device synchronization bridge. * Injects remote pending transactions into the local pool and starts their lifecycle trackers. * Also self-heals local pending transactions if the remote DB knows they are terminal. */ injectExternalPendingTxs: (remoteTxs: T[]) => Promise; }; /** * Represents the structure and behavior of an in-memory pagination system * for managing transaction history. */ type TxInMemoryPagination = { /** Indicates whether the store is currently loading transaction history. */ isLoading: boolean; /** Indicates whether the last loading request ended with an error. */ isError: boolean; /** Indicates whether more history pages are available. */ hasMore: boolean; /** The current page number in the paginated history. */ currentPage: number; /** Loads the next page of transaction history and appends it to the pool. */ fetchNextPage: (walletAddress: string) => Promise; }; /** * The complete interface for the Pulsar transaction in-memory store. * It keeps a paginated remote history in sync with a local transaction pool. * * @template T The transaction type. */ type ITxInMemoryStore = { /** A pool of all transactions currently being tracked and loaded from history, indexed by `txKey`. */ transactionsPool: TransactionPool; /** Loads the first page of transaction history. */ fetchInitial: (walletAddress: string) => Promise; /** Merges a local transaction pool into the in-memory store. */ syncWithLocalPool: (localPool: TransactionPool) => void; } & TxInMemoryPagination; /** * Parameters used to configure and manage an in-memory transaction store. * * @template T The transaction type. */ type ITxInMemoryStoreParameters = { /** A localTransactionsPool. */ localTransactionsPool: TransactionPool; /** * Attempts to synchronize any transactions in `unsyncedTxKeys` that have reached a terminal * status but failed their initial `onRemoteCreate` call. */ reconcileUnsyncedTransactions?: () => Promise; /** * Callback fired when remote history is successfully fetched. * Used to inject remote pending transactions into the persistent tracking store. */ onHistoryFetched?: (remoteTxs: T[]) => void; getHistory?: ({ page, walletAddress, }: { /** * Page number for pagination. * * @defaultValue `1` */ page?: number; walletAddress: string; }) => Promise<{ /** Array of transactions for the current page. */ docs: T[]; /** Total number of transactions matching the query. */ totalDocs: number; /** Total number of available pages. */ totalPages: number; /** Current page number. */ page: number; /** Indicates whether a next page exists. */ hasNextPage: boolean; /** Indicates whether a previous page exists. */ hasPrevPage: boolean; } | null>; }; /** * @file This file defines the core Zustand slice for managing the state of transactions. It includes the state, * actions, and types necessary for initializing the store and performing CRUD operations on the transaction pool. */ /** * Creates a Zustand store slice with the core logic for transaction state management. * This function is a slice creator intended for use with Zustand's `create` function. * * @template T The specific transaction type. * @param options Configuration for the store slice. * @returns A Zustand store slice implementing `IInitializeTxTrackingStore`. */ declare function initializeTxTrackingStore({ maxTransactions, onRemoteCreate, }: Pick, 'onRemoteCreate'> & { maxTransactions: number; }): StoreSlice>; /** * @file This file contains selector functions for deriving state from the transaction tracking store. * Selectors help abstract the state's shape and provide efficient, memoized access to computed data. */ /** * Selects all transactions from the pool and sorts them by their creation timestamp in ascending order. * @template T - The transaction type. * @param {TransactionPool} transactionsPool - The entire transaction pool from the store. * @returns {T[]} An array of all transactions, sorted chronologically. */ declare const selectAllTransactions: (transactionsPool: TransactionPool) => T[]; /** * Selects all transactions that are currently in a pending state, sorted chronologically. * @template T - The transaction type. * @param {TransactionPool} transactionsPool - The entire transaction pool from the store. * @returns {T[]} An array of pending transactions. */ declare const selectPendingTransactions: (transactionsPool: TransactionPool) => T[]; /** * Selects a single transaction from the pool by its unique key (`txKey`). * @template T - The transaction type. * @param {TransactionPool} transactionsPool - The entire transaction pool from the store. * @param {string} key - The `txKey` of the transaction to retrieve. * @returns {T | undefined} The transaction object if found, otherwise undefined. */ declare const selectTxByKey: (transactionsPool: TransactionPool, key: string) => T | undefined; /** * Selects all transactions initiated by a specific wallet address, sorted chronologically. * @template T - The transaction type. * @param {TransactionPool} transactionsPool - The entire transaction pool from the store. * @param {string} from - The wallet address (`from` address) to filter transactions by. * @returns {T[]} An array of transactions associated with the given wallet. */ declare const selectAllTransactionsByActiveWallet: (transactionsPool: TransactionPool, from: string) => T[]; /** * Selects all pending transactions for a specific wallet address, sorted chronologically. * @template T - The transaction type. * @param {TransactionPool} transactionsPool - The entire transaction pool from the store. * @param {string} from - The wallet address (`from` address) to filter transactions by. * @returns {T[]} An array of pending transactions for the given wallet. */ declare const selectPendingTransactionsByActiveWallet: (transactionsPool: TransactionPool, from: string) => T[]; /** * Creates an in-memory transaction store with synchronized local and remote sources. * * The store is designed to: * - keep a local transaction pool in sync with remote history * - preserve terminal transaction states * - support paginated history loading * - avoid duplicated merge logic across store actions * * @template T The transaction type. * @param params Store configuration parameters. * @param params.getHistory Optional remote history fetcher. * @returns A Zustand vanilla store instance for in-memory transaction management. */ declare function createTxInMemoryStore({ localTransactionsPool, reconcileUnsyncedTransactions, getHistory, onHistoryFetched, }: ITxInMemoryStoreParameters): zustand.StoreApi>; /** * Creates the main Pulsar store for transaction tracking. * * This function configures a Zustand store enhanced with persistence. It combines the core transaction management * slice with a powerful orchestration logic that leverages chain-specific adapters to handle the entire * lifecycle of a transaction—from initiation and chain validation to execution and background status tracking. * * @template T The specific transaction type, extending the base `Transaction`. * * @param config Configuration object for creating the store. * @param config.adapter Adapter or an array of adapters for different chains or transaction types. * @param options Configuration for the Zustand `persist` middleware. * @returns A fully configured Zustand store instance. */ declare function createPulsarStore({ adapter, maxTransactions, onRemoteCreate, gelatoApiKey, beforeTxProcess, abortOnTxError, ...options }: PulsarAdapter & PersistOptions>): Omit>, "setState" | "persist"> & { setState(partial: ITxTrackingStore | Partial> | ((state: ITxTrackingStore) => ITxTrackingStore | Partial>), replace?: false | undefined): unknown; setState(state: ITxTrackingStore | ((state: ITxTrackingStore) => ITxTrackingStore), replace: true): unknown; persist: { setOptions: (options: Partial, ITxTrackingStore, unknown>>) => void; clearStorage: () => void; rehydrate: () => Promise | void; hasHydrated: () => boolean; onHydrate: (fn: (state: ITxTrackingStore) => void) => () => void; onFinishHydration: (fn: (state: ITxTrackingStore) => void) => () => void; getOptions: () => Partial, ITxTrackingStore, unknown>>; }; }; /** * @file This file provides a utility for creating a type-safe, bounded Zustand hook from a vanilla store. * This pattern is recommended by the official Zustand documentation to ensure full type * safety when integrating vanilla stores with React. * * @see https://docs.pmnd.rs/zustand/guides/typescript#bounded-usestore-hook-for-vanilla-stores */ /** * A utility type that infers the state shape from a Zustand `StoreApi`. * It extracts the return type of the `getState` method. * @template S - The type of the Zustand store (`StoreApi`). */ type ExtractState = S extends { getState: () => infer T; } ? T : never; /** * Creates a bounded `useStore` hook from a vanilla Zustand store. * * This function takes a vanilla Zustand store instance and returns a React hook * that is pre-bound to that store. This approach provides a cleaner API and * enhances type inference, eliminating the need to pass the store instance * on every use. * * The returned hook supports two signatures: * 1. `useBoundedStore()`: Selects the entire state. * 2. `useBoundedStore(selector)`: Selects a slice of the state, returning only what the selector function specifies. * * @template S - The type of the Zustand store (`StoreApi`). * @param {S} store - The vanilla Zustand store instance to bind the hook to. * @returns {function} A fully typed React hook for accessing the store's state. */ declare const createBoundedUseStore: >(store: S) => { (): ExtractState; (selector: (state: ExtractState) => T): T; }; /** * @file This file provides a generic utility for creating a polling mechanism to track * asynchronous tasks, such as API-based transaction status checks (e.g., for Gelato or Safe). */ /** * Defines the parameters for the fetcher function used within the polling tracker. * The fetcher is the core logic that performs the actual API call. * @template R The expected type of the successful API response. * @template T The type of the transaction object being tracked. */ type PollingFetcherParams = { /** The transaction object being tracked. */ tx: T; /** A callback to stop the polling mechanism, typically called on success or terminal failure. */ stopPolling: (options?: { withoutRemoving?: boolean; }) => void; /** Callback to be invoked when the fetcher determines the transaction has succeeded. */ onSuccess: (response: R) => void; /** Callback to be invoked when the fetcher determines the transaction has failed. */ onFailure: (response?: R) => void; /** Optional callback for each successful poll, useful for updating UI with intermediate states. */ onIntervalTick?: (response: R) => void; /** Optional callback for when a transaction is replaced (e.g., speed-up). */ onReplaced?: (response: R) => void; }; /** * Defines the configuration object for the `initializePollingTracker` function. * @template R The expected type of the successful API response. * @template T The type of the transaction object. */ type PollingTrackerConfig = { /** The transaction object to be tracked. It must include `txKey` and `pending` status. */ tx: T & Pick; /** The function that performs the data fetching (e.g., an API call) on each interval. */ fetcher: (params: PollingFetcherParams) => Promise; /** Callback to be invoked when the transaction successfully completes. */ onSuccess: (response: R) => void; /** Callback to be invoked when the transaction fails. */ onFailure: (response?: R) => void; /** Optional callback executed once when the tracker is initialized. */ onInitialize?: () => void; /** Optional callback for each successful poll. */ onIntervalTick?: (response: R) => void; /** Optional callback for when a transaction is replaced. */ onReplaced?: (response: R) => void; /** Optional function to remove the transaction from the main pool, typically after polling stops. */ removeTxFromPool?: (txKey: string) => void; /** The interval (in milliseconds) between polling attempts. Defaults to 5000ms. */ pollingInterval?: number; /** The number of consecutive failed fetches before stopping the tracker. Defaults to 10. */ maxRetries?: number; }; /** * Initializes a generic polling tracker that repeatedly calls a fetcher function * to monitor the status of an asynchronous task. * * This function handles the lifecycle of polling, including starting, stopping, * and automatic termination after a certain number of failed attempts. * * @template R The expected type of the API response. * @template T The type of the transaction object. * @param {PollingTrackerConfig} config - The configuration for the tracker. */ declare function initializePollingTracker(config: PollingTrackerConfig): void; /** Maximum allowed length for each transaction title string. */ declare const MAX_TRANSACTION_TITLE_LENGTH = 100; /** Maximum allowed length for each transaction description string. */ declare const MAX_TRANSACTION_DESCRIPTION_LENGTH = 300; /** Maximum allowed serialized UTF-8 payload size in bytes. */ declare const MAX_TRANSACTION_PAYLOAD_BYTES: number; /** * Error thrown when transaction metadata fails Pulsar's safety limits. */ declare class PulsarTransactionValidationError extends Error { /** The transaction field that failed validation. */ readonly field: string; constructor(field: string, message: string); } /** * Validates metadata used before a transaction action is executed. * Throws when title, description, or payload violates Pulsar safety limits. */ declare function validateInitialTransactionParams(params: Omit): void; /** * Validates a complete transaction before it is persisted or synchronized. * Throws when title, description, or payload violates Pulsar safety limits. */ declare function validateTransaction(tx: T): void; export { type ActionTxKey, type BaseTransaction, type BeforeTxProcess, type CheckTxTracker, type EvmTransaction, type IInitializeTxTrackingStore, type ITxInMemoryStore, type ITxInMemoryStoreParameters, type ITxTrackingStore, type InitialTransaction, type InitialTransactionParams, MAX_TRANSACTION_DESCRIPTION_LENGTH, MAX_TRANSACTION_PAYLOAD_BYTES, MAX_TRANSACTION_TITLE_LENGTH, type PollingFetcherParams, type PollingTrackerConfig, type PulsarAdapter, PulsarTransactionValidationError, type SolanaTransaction, type StarknetTransaction, type StoreSlice, type SyncCallbacks, type TrackerCallbacks, type Transaction, type TransactionPool, TransactionStatus, TransactionTracker, type TxAdapter, type TxInMemoryPagination, type UpdatableTransactionFields, createBoundedUseStore, createPulsarStore, createTxInMemoryStore, initializePollingTracker, initializeTxTrackingStore, selectAllTransactions, selectAllTransactionsByActiveWallet, selectPendingTransactions, selectPendingTransactionsByActiveWallet, selectTxByKey, validateInitialTransactionParams, validateTransaction };