@tuwaio/pulsar-core 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -25,6 +25,20 @@ declare enum TransactionAdapter {
25
25
  /** For the Starknet L2 network. */
26
26
  Starknet = "starknet"
27
27
  }
28
+ /**
29
+ * Enum representing the different tracking strategies available for EVM transactions.
30
+ * Each tracker corresponds to a specific method of monitoring a transaction's lifecycle.
31
+ */
32
+ declare enum TransactionTracker {
33
+ /** For standard on-chain EVM transactions tracked by their hash. */
34
+ Ethereum = "ethereum",
35
+ /** For multi-signature transactions managed and executed via a Safe contract. */
36
+ Safe = "safe",
37
+ /** For meta-transactions relayed and executed by the Gelato Network. */
38
+ Gelato = "gelato",
39
+ /** The tracker for monitoring standard Solana transaction signatures. */
40
+ Solana = "solana"
41
+ }
28
42
  /**
29
43
  * Represents the terminal status of a transaction after it has been processed.
30
44
  */
@@ -36,12 +50,29 @@ declare enum TransactionStatus {
36
50
  /** The transaction was replaced by another with the same nonce (e.g., a speed-up or cancel). */
37
51
  Replaced = "Replaced"
38
52
  }
53
+ /**
54
+ * Defines the shape of the identifier for a Gelato transaction task.
55
+ */
56
+ type GelatoTxKey = {
57
+ taskId: string;
58
+ };
59
+ /**
60
+ * A union type representing the unique identifier returned by an `actionFunction`
61
+ * after a transaction is submitted to the network or a relay service.
62
+ *
63
+ * This key is crucial for the EVM adapter to determine which tracker should
64
+ * monitor the transaction.
65
+ *
66
+ * It can be one of the following:
67
+ * - A standard `0x...` transaction hash (`Hex`).
68
+ * - A structured object from a relay service like Gelato (`GelatoTxKey`).
69
+ */
70
+ type ActionTxKey = `0x${string}` | GelatoTxKey | string;
39
71
  /**
40
72
  * The fundamental structure for any transaction being tracked by Pulsar.
41
73
  * This serves as the base upon which chain-specific transaction types are built.
42
- * @template T The type of the tracker identifier (e.g., 'ethereum', 'gelato').
43
74
  */
44
- type BaseTransaction<T> = {
75
+ type BaseTransaction = {
45
76
  /** The chain identifier (e.g., 1 for Ethereum Mainnet, 'SN_MAIN' for Starknet). */
46
77
  chainId: number | string;
47
78
  /**
@@ -81,7 +112,7 @@ type BaseTransaction<T> = {
81
112
  */
82
113
  title?: string | [string, string, string, string];
83
114
  /** The specific tracker responsible for monitoring this transaction's status. */
84
- tracker: T;
115
+ tracker: TransactionTracker;
85
116
  /** The unique identifier for the transaction (e.g., EVM hash, Gelato task ID). */
86
117
  txKey: string;
87
118
  /** The application-specific type or category of the transaction (e.g., 'SWAP', 'APPROVE'). */
@@ -91,9 +122,8 @@ type BaseTransaction<T> = {
91
122
  };
92
123
  /**
93
124
  * Represents an EVM-specific transaction, extending the base properties with EVM fields.
94
- * @template T The type of the tracker identifier.
95
125
  */
96
- type EvmTransaction<T> = BaseTransaction<T> & {
126
+ type EvmTransaction = BaseTransaction & {
97
127
  adapter: TransactionAdapter.EVM;
98
128
  /** The on-chain transaction hash, available after submission. */
99
129
  hash?: `0x${string}`;
@@ -114,9 +144,8 @@ type EvmTransaction<T> = BaseTransaction<T> & {
114
144
  };
115
145
  /**
116
146
  * Represents a Solana-specific transaction, extending the base properties.
117
- * @template T The type of the tracker identifier.
118
147
  */
119
- type SolanaTransaction<T> = BaseTransaction<T> & {
148
+ type SolanaTransaction = BaseTransaction & {
120
149
  adapter: TransactionAdapter.SOLANA;
121
150
  /** The transaction fee in lamports. */
122
151
  fee?: number;
@@ -133,9 +162,8 @@ type SolanaTransaction<T> = BaseTransaction<T> & {
133
162
  };
134
163
  /**
135
164
  * Represents a Starknet-specific transaction, extending the base properties.
136
- * @template T The type of the tracker identifier.
137
165
  */
138
- type StarknetTransaction<T> = BaseTransaction<T> & {
166
+ type StarknetTransaction = BaseTransaction & {
139
167
  adapter: TransactionAdapter.Starknet;
140
168
  /** The actual fee paid for the transaction. */
141
169
  actualFee?: {
@@ -146,14 +174,14 @@ type StarknetTransaction<T> = BaseTransaction<T> & {
146
174
  contractAddress?: string;
147
175
  };
148
176
  /** A union type representing any possible transaction structure that Pulsar can handle. */
149
- type Transaction<T> = EvmTransaction<T> | SolanaTransaction<T> | StarknetTransaction<T>;
177
+ type Transaction = EvmTransaction | SolanaTransaction | StarknetTransaction;
150
178
  /**
151
179
  * Represents the parameters required to initiate a new transaction tracking flow.
152
180
  */
153
- type InitialTransactionParams<A> = {
181
+ type InitialTransactionParams = {
154
182
  adapter: TransactionAdapter;
155
183
  /** The function that executes the on-chain action (e.g., sending a transaction) and returns a preliminary identifier like a hash. */
156
- actionFunction: (...args: any[]) => Promise<A | undefined>;
184
+ actionFunction: (...args: any[]) => Promise<ActionTxKey | undefined>;
157
185
  /** A user-facing description for the transaction. Supports state-specific descriptions. */
158
186
  description?: string | [string, string, string, string];
159
187
  /** The target chain ID for the transaction. */
@@ -173,7 +201,7 @@ type InitialTransactionParams<A> = {
173
201
  * Represents a transaction in its temporary, pre-submission state.
174
202
  * This is used for UI feedback while the transaction is being signed and sent.
175
203
  */
176
- type InitialTransaction<A> = InitialTransactionParams<A> & {
204
+ type InitialTransaction = InitialTransactionParams & {
177
205
  /** An error message if the initialization fails (e.g., user rejects signature). */
178
206
  errorMessage?: string;
179
207
  /** A flag indicating if the transaction is being processed (e.g., waiting for signature). */
@@ -185,11 +213,9 @@ type InitialTransaction<A> = InitialTransactionParams<A> & {
185
213
  };
186
214
  /**
187
215
  * Defines the interface for a transaction adapter, which provides chain-specific logic and utilities.
188
- * @template TR The type of the tracker identifier (e.g., a string enum).
189
- * @template T The specific transaction type, extending `Transaction<TR>`.
190
- * @template A The type of the key returned by the `actionFunction` (e.g., a transaction hash).
216
+ * @template T The specific transaction type, extending `Transaction`.
191
217
  */
192
- type TxAdapter<TR, T extends Transaction<TR>, A> = {
218
+ type TxAdapter<T extends Transaction> = {
193
219
  /** The unique key identifying this adapter. */
194
220
  key: TransactionAdapter;
195
221
  /** Returns information about the currently connected wallet. */
@@ -200,14 +226,14 @@ type TxAdapter<TR, T extends Transaction<TR>, A> = {
200
226
  /** Ensures the connected wallet is on the correct network for the transaction. Throws an error if the chain is mismatched. */
201
227
  checkChainForTx: (chainId: string | number) => Promise<void>;
202
228
  /** Determines the appropriate tracker and final `txKey` from the result of an action. */
203
- checkTransactionsTracker: (actionTxKey: A, walletType: string) => {
229
+ checkTransactionsTracker: (actionTxKey: ActionTxKey, walletType: string) => {
204
230
  txKey: string;
205
- tracker: TR;
231
+ tracker: TransactionTracker;
206
232
  };
207
233
  /** Selects and initializes the correct background tracker for a given transaction. */
208
234
  checkAndInitializeTrackerInStore: (params: {
209
235
  tx: T;
210
- } & Pick<ITxTrackingStore<TR, T, A>, 'transactionsPool' | 'updateTxParams' | 'onSucceedCallbacks' | 'removeTxFromPool'>) => Promise<void>;
236
+ } & Pick<ITxTrackingStore<T>, 'transactionsPool' | 'updateTxParams' | 'onSucceedCallbacks' | 'removeTxFromPool'>) => Promise<void>;
211
237
  /** Returns the base URL for the blockchain explorer for the current network. */
212
238
  getExplorerUrl: () => string | undefined;
213
239
  /** Optional: Fetches a name from a chain-specific name service (e.g., ENS). */
@@ -221,22 +247,20 @@ type TxAdapter<TR, T extends Transaction<TR>, A> = {
221
247
  /** Optional: Logic to retry a failed transaction. */
222
248
  retryTxAction?: (params: {
223
249
  txKey: string;
224
- tx: InitialTransactionParams<A>;
250
+ tx: InitialTransactionParams;
225
251
  onClose: (txKey?: string) => void;
226
- } & Partial<Pick<ITxTrackingStore<TR, T, A>, 'handleTransaction'>>) => Promise<void>;
252
+ } & Partial<Pick<ITxTrackingStore<T>, 'handleTransaction'>>) => Promise<void>;
227
253
  /**
228
254
  * Optional: Constructs a full explorer URL for a specific transaction.
229
255
  * May require the full transaction pool to resolve details for replaced transactions.
230
256
  */
231
- getExplorerTxUrl?: (transactionsPool: TransactionPool<TR, T>, txKey: string, replacedTxHash?: string) => string;
257
+ getExplorerTxUrl?: (transactionsPool: TransactionPool<T>, txKey: string, replacedTxHash?: string) => string;
232
258
  };
233
259
  /**
234
260
  * The complete interface for the Pulsar transaction tracking store.
235
- * @template TR The type of the tracker identifier.
236
261
  * @template T The transaction type.
237
- * @template A The return type of the `actionFunction`.
238
262
  */
239
- type ITxTrackingStore<TR, T extends Transaction<TR>, A> = IInitializeTxTrackingStore<TR, T, A> & {
263
+ type ITxTrackingStore<T extends Transaction> = IInitializeTxTrackingStore<T> & {
240
264
  /**
241
265
  * The primary method for initiating and tracking a new transaction from start to finish.
242
266
  * It manages UI state, executes the on-chain action, and initiates background tracking.
@@ -244,11 +268,11 @@ type ITxTrackingStore<TR, T extends Transaction<TR>, A> = IInitializeTxTrackingS
244
268
  */
245
269
  handleTransaction: (params: {
246
270
  /** The async function to execute (e.g., a smart contract write call). Must return a unique key or undefined. */
247
- actionFunction: () => Promise<A | undefined>;
271
+ actionFunction: () => Promise<ActionTxKey | undefined>;
248
272
  /** The metadata for the transaction. */
249
- params: Omit<InitialTransactionParams<A>, 'actionFunction'>;
273
+ params: Omit<InitialTransactionParams, 'actionFunction'>;
250
274
  /** The default tracker to use if it cannot be determined automatically. */
251
- defaultTracker?: TR;
275
+ defaultTracker?: TransactionTracker;
252
276
  }) => Promise<void>;
253
277
  /**
254
278
  * Initializes trackers for all pending transactions in the pool.
@@ -264,37 +288,33 @@ type ITxTrackingStore<TR, T extends Transaction<TR>, A> = IInitializeTxTrackingS
264
288
 
265
289
  /**
266
290
  * Defines the structure of the transaction pool, a key-value store of transactions indexed by their unique keys.
267
- * @template TR The type of the tracker identifier.
268
- * @template T The transaction type.
291
+ * @template T The type of the transaction object being tracked.
269
292
  */
270
- type TransactionPool<TR, T extends Transaction<TR>> = Record<string, T>;
293
+ type TransactionPool<T extends Transaction> = Record<string, T>;
271
294
  /**
272
295
  * A utility type that creates a union of all fields that can be safely updated
273
296
  * on a transaction object via the `updateTxParams` action. This ensures type safety
274
297
  * and prevents accidental modification of immutable properties.
275
- * @template TR The type of the tracker identifier.
276
298
  */
277
- type UpdatableTransactionFields<TR> = Partial<Pick<EvmTransaction<TR>, 'to' | 'nonce' | 'txKey' | 'pending' | 'hash' | 'status' | 'replacedTxHash' | 'errorMessage' | 'finishedTimestamp' | 'isTrackedModalOpen' | 'isError' | 'maxPriorityFeePerGas' | 'maxFeePerGas' | 'input' | 'value'>> & Partial<Pick<SolanaTransaction<TR>, 'slot' | 'confirmations' | 'fee' | 'instructions' | 'recentBlockhash' | 'rpcUrl'>>;
299
+ type UpdatableTransactionFields = Partial<Pick<EvmTransaction, 'to' | 'nonce' | 'txKey' | 'pending' | 'hash' | 'status' | 'replacedTxHash' | 'errorMessage' | 'finishedTimestamp' | 'isTrackedModalOpen' | 'isError' | 'maxPriorityFeePerGas' | 'maxFeePerGas' | 'input' | 'value'>> & Partial<Pick<SolanaTransaction, 'slot' | 'confirmations' | 'fee' | 'instructions' | 'recentBlockhash' | 'rpcUrl'>>;
278
300
  /**
279
301
  * The interface for the base transaction tracking store slice.
280
302
  * It includes the state and actions for managing the transaction lifecycle.
281
- * @template TR The type of the tracker identifier.
282
303
  * @template T The specific transaction type.
283
- * @template A The return type of the initial action function.
284
304
  */
285
- interface IInitializeTxTrackingStore<TR, T extends Transaction<TR>, A> {
305
+ interface IInitializeTxTrackingStore<T extends Transaction> {
286
306
  /** A callback function executed when any transaction successfully completes. */
287
307
  onSucceedCallbacks?: (tx: T) => Promise<void> | void;
288
308
  /** A pool of all transactions currently being tracked, indexed by `txKey`. */
289
- transactionsPool: TransactionPool<TR, T>;
309
+ transactionsPool: TransactionPool<T>;
290
310
  /** The `txKey` of the most recently added transaction. */
291
311
  lastAddedTxKey?: string;
292
312
  /** The state for a transaction being initiated, used for UI feedback before it's submitted to the chain. */
293
- initialTx?: InitialTransaction<A>;
313
+ initialTx?: InitialTransaction;
294
314
  /** Adds a new transaction to the tracking pool and marks it as pending. */
295
- addTxToPool: (tx: Transaction<TR>) => void;
315
+ addTxToPool: (tx: T) => void;
296
316
  /** Updates one or more properties of an existing transaction in the pool. */
297
- updateTxParams: (txKey: string, fields: UpdatableTransactionFields<TR>) => void;
317
+ updateTxParams: (txKey: string, fields: UpdatableTransactionFields) => void;
298
318
  /** Removes a transaction from the tracking pool by its key. */
299
319
  removeTxFromPool: (txKey: string) => void;
300
320
  /** Closes the tracking modal for a transaction and clears any initial transaction state. */
@@ -306,16 +326,14 @@ interface IInitializeTxTrackingStore<TR, T extends Transaction<TR>, A> {
306
326
  * Creates a Zustand store slice with the core logic for transaction state management.
307
327
  * This function is a slice creator intended for use with Zustand's `create` function.
308
328
  *
309
- * @template TR The type of the tracker identifier.
310
329
  * @template T The specific transaction type.
311
- * @template A The return type of the initial action function.
312
330
  * @param options Configuration for the store slice.
313
331
  * @param options.onSucceedCallbacks An optional async callback to run when a transaction succeeds.
314
332
  * @returns A Zustand store slice implementing `IInitializeTxTrackingStore`.
315
333
  */
316
- declare function initializeTxTrackingStore<TR, T extends Transaction<TR>, A>({ onSucceedCallbacks, }: {
334
+ declare function initializeTxTrackingStore<T extends Transaction>({ onSucceedCallbacks, }: {
317
335
  onSucceedCallbacks?: (tx: T) => Promise<void> | void;
318
- }): StoreSlice<IInitializeTxTrackingStore<TR, T, A>>;
336
+ }): StoreSlice<IInitializeTxTrackingStore<T>>;
319
337
 
320
338
  /**
321
339
  * @file This file contains selector functions for deriving state from the transaction tracking store.
@@ -324,47 +342,42 @@ declare function initializeTxTrackingStore<TR, T extends Transaction<TR>, A>({ o
324
342
 
325
343
  /**
326
344
  * Selects all transactions from the pool and sorts them by their creation timestamp in ascending order.
327
- * @template TR - The type of the tracker identifier.
328
345
  * @template T - The transaction type.
329
- * @param {TransactionPool<TR, T>} transactionsPool - The entire transaction pool from the store.
346
+ * @param {TransactionPool<T>} transactionsPool - The entire transaction pool from the store.
330
347
  * @returns {T[]} An array of all transactions, sorted chronologically.
331
348
  */
332
- declare const selectAllTransactions: <TR, T extends Transaction<TR>>(transactionsPool: TransactionPool<TR, T>) => T[];
349
+ declare const selectAllTransactions: <T extends Transaction>(transactionsPool: TransactionPool<T>) => T[];
333
350
  /**
334
351
  * Selects all transactions that are currently in a pending state, sorted chronologically.
335
- * @template TR - The type of the tracker identifier.
336
352
  * @template T - The transaction type.
337
- * @param {TransactionPool<TR, T>} transactionsPool - The entire transaction pool from the store.
353
+ * @param {TransactionPool<T>} transactionsPool - The entire transaction pool from the store.
338
354
  * @returns {T[]} An array of pending transactions.
339
355
  */
340
- declare const selectPendingTransactions: <TR, T extends Transaction<TR>>(transactionsPool: TransactionPool<TR, T>) => T[];
356
+ declare const selectPendingTransactions: <T extends Transaction>(transactionsPool: TransactionPool<T>) => T[];
341
357
  /**
342
358
  * Selects a single transaction from the pool by its unique key (`txKey`).
343
- * @template TR - The type of the tracker identifier.
344
359
  * @template T - The transaction type.
345
- * @param {TransactionPool<TR, T>} transactionsPool - The entire transaction pool from the store.
360
+ * @param {TransactionPool<T>} transactionsPool - The entire transaction pool from the store.
346
361
  * @param {string} key - The `txKey` of the transaction to retrieve.
347
362
  * @returns {T | undefined} The transaction object if found, otherwise undefined.
348
363
  */
349
- declare const selectTxByKey: <TR, T extends Transaction<TR>>(transactionsPool: TransactionPool<TR, T>, key: string) => T | undefined;
364
+ declare const selectTxByKey: <T extends Transaction>(transactionsPool: TransactionPool<T>, key: string) => T | undefined;
350
365
  /**
351
366
  * Selects all transactions initiated by a specific wallet address, sorted chronologically.
352
- * @template TR - The type of the tracker identifier.
353
367
  * @template T - The transaction type.
354
- * @param {TransactionPool<TR, T>} transactionsPool - The entire transaction pool from the store.
368
+ * @param {TransactionPool<T>} transactionsPool - The entire transaction pool from the store.
355
369
  * @param {string} from - The wallet address (`from` address) to filter transactions by.
356
370
  * @returns {T[]} An array of transactions associated with the given wallet.
357
371
  */
358
- declare const selectAllTransactionsByActiveWallet: <TR, T extends Transaction<TR>>(transactionsPool: TransactionPool<TR, T>, from: string) => T[];
372
+ declare const selectAllTransactionsByActiveWallet: <T extends Transaction>(transactionsPool: TransactionPool<T>, from: string) => T[];
359
373
  /**
360
374
  * Selects all pending transactions for a specific wallet address, sorted chronologically.
361
- * @template TR - The type of the tracker identifier.
362
375
  * @template T - The transaction type.
363
- * @param {TransactionPool<TR, T>} transactionsPool - The entire transaction pool from the store.
376
+ * @param {TransactionPool<T>} transactionsPool - The entire transaction pool from the store.
364
377
  * @param {string} from - The wallet address (`from` address) to filter transactions by.
365
378
  * @returns {T[]} An array of pending transactions for the given wallet.
366
379
  */
367
- declare const selectPendingTransactionsByActiveWallet: <TR, T extends Transaction<TR>>(transactionsPool: TransactionPool<TR, T>, from: string) => T[];
380
+ declare const selectPendingTransactionsByActiveWallet: <T extends Transaction>(transactionsPool: TransactionPool<T>, from: string) => T[];
368
381
 
369
382
  /**
370
383
  * Creates the main Pulsar store for transaction tracking.
@@ -373,9 +386,7 @@ declare const selectPendingTransactionsByActiveWallet: <TR, T extends Transactio
373
386
  * slice with a powerful orchestration logic that leverages chain-specific adapters to handle the entire
374
387
  * lifecycle of a transaction—from initiation and chain validation to execution and background status tracking.
375
388
  *
376
- * @template TR The type of the tracker identifier (e.g., a string enum).
377
389
  * @template T The specific transaction type, extending the base `Transaction`.
378
- * @template A The type of the key returned by the `actionFunction` (e.g., a transaction hash).
379
390
  *
380
391
  * @param config Configuration object for creating the store.
381
392
  * @param config.onSucceedCallbacks Optional async callback executed on transaction success.
@@ -383,20 +394,20 @@ declare const selectPendingTransactionsByActiveWallet: <TR, T extends Transactio
383
394
  * @param options Configuration for the Zustand `persist` middleware.
384
395
  * @returns A fully configured Zustand store instance.
385
396
  */
386
- declare function createPulsarStore<TR, T extends Transaction<TR>, A>({ onSucceedCallbacks, adapter, ...options }: {
397
+ declare function createPulsarStore<T extends Transaction>({ onSucceedCallbacks, adapter, ...options }: {
387
398
  onSucceedCallbacks?: (tx: T) => Promise<void> | void;
388
- adapter: TxAdapter<TR, T, A> | TxAdapter<TR, T, A>[];
389
- } & PersistOptions<ITxTrackingStore<TR, T, A>>): Omit<zustand.StoreApi<ITxTrackingStore<TR, T, A>>, "setState" | "persist"> & {
390
- setState(partial: ITxTrackingStore<TR, T, A> | Partial<ITxTrackingStore<TR, T, A>> | ((state: ITxTrackingStore<TR, T, A>) => ITxTrackingStore<TR, T, A> | Partial<ITxTrackingStore<TR, T, A>>), replace?: false | undefined): unknown;
391
- setState(state: ITxTrackingStore<TR, T, A> | ((state: ITxTrackingStore<TR, T, A>) => ITxTrackingStore<TR, T, A>), replace: true): unknown;
399
+ adapter: TxAdapter<T> | TxAdapter<T>[];
400
+ } & PersistOptions<ITxTrackingStore<T>>): Omit<zustand.StoreApi<ITxTrackingStore<T>>, "setState" | "persist"> & {
401
+ setState(partial: ITxTrackingStore<T> | Partial<ITxTrackingStore<T>> | ((state: ITxTrackingStore<T>) => ITxTrackingStore<T> | Partial<ITxTrackingStore<T>>), replace?: false | undefined): unknown;
402
+ setState(state: ITxTrackingStore<T> | ((state: ITxTrackingStore<T>) => ITxTrackingStore<T>), replace: true): unknown;
392
403
  persist: {
393
- setOptions: (options: Partial<PersistOptions<ITxTrackingStore<TR, T, A>, ITxTrackingStore<TR, T, A>, unknown>>) => void;
404
+ setOptions: (options: Partial<PersistOptions<ITxTrackingStore<T>, ITxTrackingStore<T>, unknown>>) => void;
394
405
  clearStorage: () => void;
395
406
  rehydrate: () => Promise<void> | void;
396
407
  hasHydrated: () => boolean;
397
- onHydrate: (fn: (state: ITxTrackingStore<TR, T, A>) => void) => () => void;
398
- onFinishHydration: (fn: (state: ITxTrackingStore<TR, T, A>) => void) => () => void;
399
- getOptions: () => Partial<PersistOptions<ITxTrackingStore<TR, T, A>, ITxTrackingStore<TR, T, A>, unknown>>;
408
+ onHydrate: (fn: (state: ITxTrackingStore<T>) => void) => () => void;
409
+ onFinishHydration: (fn: (state: ITxTrackingStore<T>) => void) => () => void;
410
+ getOptions: () => Partial<PersistOptions<ITxTrackingStore<T>, ITxTrackingStore<T>, unknown>>;
400
411
  };
401
412
  };
402
413
 
@@ -445,8 +456,8 @@ declare const createBoundedUseStore: <S extends StoreApi<unknown>>(store: S) =>
445
456
  /**
446
457
  * Defines the parameters for the fetcher function used within the polling tracker.
447
458
  * The fetcher is the core logic that performs the actual API call.
448
- * @template R - The expected type of the successful API response.
449
- * @template T - The type of the transaction object being tracked.
459
+ * @template R The expected type of the successful API response.
460
+ * @template T The type of the transaction object being tracked.
450
461
  */
451
462
  type PollingFetcherParams<R, T> = {
452
463
  /** The transaction object being tracked. */
@@ -466,13 +477,12 @@ type PollingFetcherParams<R, T> = {
466
477
  };
467
478
  /**
468
479
  * Defines the configuration object for the `initializePollingTracker` function.
469
- * @template R - The expected type of the successful API response.
470
- * @template T - The type of the transaction object.
471
- * @template TR - The type of the tracker identifier.
480
+ * @template R The expected type of the successful API response.
481
+ * @template T The type of the transaction object.
472
482
  */
473
- type PollingTrackerConfig<R, T, TR> = {
483
+ type PollingTrackerConfig<R, T extends Transaction> = {
474
484
  /** The transaction object to be tracked. It must include `txKey` and `pending` status. */
475
- tx: T & Pick<Transaction<TR>, 'txKey' | 'pending'>;
485
+ tx: T & Pick<Transaction, 'txKey' | 'pending'>;
476
486
  /** The function that performs the data fetching (e.g., an API call) on each interval. */
477
487
  fetcher: (params: PollingFetcherParams<R, T>) => Promise<void>;
478
488
  /** Callback to be invoked when the transaction successfully completes. */
@@ -501,10 +511,9 @@ type PollingTrackerConfig<R, T, TR> = {
501
511
  *
502
512
  * @template R The expected type of the API response.
503
513
  * @template T The type of the transaction object.
504
- * @template TR The type of the tracker identifier.
505
- * @param {PollingTrackerConfig<R, T, TR>} config - The configuration for the tracker.
514
+ * @param {PollingTrackerConfig<R, T>} config - The configuration for the tracker.
506
515
  */
507
- declare function initializePollingTracker<R, T, TR>(config: PollingTrackerConfig<R, T, TR>): void;
516
+ declare function initializePollingTracker<R, T extends Transaction>(config: PollingTrackerConfig<R, T>): void;
508
517
 
509
518
  /**
510
519
  * @file This file contains a utility function for selecting a specific transaction adapter from a list.
@@ -518,19 +527,17 @@ declare function initializePollingTracker<R, T, TR>(config: PollingTrackerConfig
518
527
  * and returns the first adapter in the array as a fallback. This fallback mechanism
519
528
  * ensures that the system can still function, but it highlights a potential configuration issue.
520
529
  *
521
- * @template TR - The type of the tracker identifier.
522
530
  * @template T - The transaction type, extending the base `Transaction`.
523
- * @template A - The type for the adapter-specific context or API.
524
531
  *
525
532
  * @param {object} params - The parameters for the selection.
526
533
  * @param {TransactionAdapter} params.adapterKey - The key of the desired adapter.
527
- * @param {TxAdapter<TR, T, A> | TxAdapter<TR, T, A>[]} params.adapter - Adapter or an array of adapters for different chains or transaction types.
534
+ * @param {TxAdapter<T> | TxAdapter<T>[]} params.adapter - Adapter or an array of adapters for different chains or transaction types.
528
535
  *
529
- * @returns {TxAdapter<TR, T, A> | undefined} The found transaction adapter, the fallback adapter, or undefined if the adapters array is empty.
536
+ * @returns {TxAdapter<T> | undefined} The found transaction adapter, the fallback adapter, or undefined if the adapters array is empty.
530
537
  */
531
- declare const selectAdapterByKey: <TR, T extends Transaction<TR>, A>({ adapterKey, adapter, }: {
538
+ declare const selectAdapterByKey: <T extends Transaction>({ adapterKey, adapter, }: {
532
539
  adapterKey: TransactionAdapter;
533
- adapter: TxAdapter<TR, T, A> | TxAdapter<TR, T, A>[];
534
- }) => TxAdapter<TR, T, A> | undefined;
540
+ adapter: TxAdapter<T> | TxAdapter<T>[];
541
+ }) => TxAdapter<T> | undefined;
535
542
 
536
- export { type BaseTransaction, type EvmTransaction, type IInitializeTxTrackingStore, type ITxTrackingStore, type InitialTransaction, type InitialTransactionParams, type PollingTrackerConfig, type SolanaTransaction, type StarknetTransaction, type StoreSlice, type Transaction, TransactionAdapter, type TransactionPool, TransactionStatus, type TxAdapter, createBoundedUseStore, createPulsarStore, initializePollingTracker, initializeTxTrackingStore, selectAdapterByKey, selectAllTransactions, selectAllTransactionsByActiveWallet, selectPendingTransactions, selectPendingTransactionsByActiveWallet, selectTxByKey };
543
+ export { type ActionTxKey, type BaseTransaction, type EvmTransaction, type GelatoTxKey, type IInitializeTxTrackingStore, type ITxTrackingStore, type InitialTransaction, type InitialTransactionParams, type PollingTrackerConfig, type SolanaTransaction, type StarknetTransaction, type StoreSlice, type Transaction, TransactionAdapter, type TransactionPool, TransactionStatus, TransactionTracker, type TxAdapter, createBoundedUseStore, createPulsarStore, initializePollingTracker, initializeTxTrackingStore, selectAdapterByKey, selectAllTransactions, selectAllTransactionsByActiveWallet, selectPendingTransactions, selectPendingTransactionsByActiveWallet, selectTxByKey };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var immer=require('immer'),K=require('dayjs'),middleware=require('zustand/middleware'),vanilla=require('zustand/vanilla'),zustand=require('zustand');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var K__default=/*#__PURE__*/_interopDefault(K);function A({onSucceedCallbacks:n}){return (e,a)=>({onSucceedCallbacks:n,transactionsPool:{},lastAddedTxKey:void 0,initialTx:void 0,addTxToPool:t=>{e(i=>immer.produce(i,r=>{r.lastAddedTxKey=t.txKey,t.txKey&&(r.transactionsPool[t.txKey]={...t,pending:true});}));},updateTxParams:(t,i)=>{e(r=>immer.produce(r,s=>{let c=s.transactionsPool[t];c&&Object.assign(c,i);}));},removeTxFromPool:t=>{e(i=>immer.produce(i,r=>{delete r.transactionsPool[t];}));},closeTxTrackedModal:t=>{e(i=>immer.produce(i,r=>{t&&r.transactionsPool[t]&&(r.transactionsPool[t].isTrackedModalOpen=false),r.initialTx=void 0;}));},getLastTxKey:()=>a().lastAddedTxKey})}var k=n=>Object.values(n).sort((e,a)=>Number(e.localTimestamp)-Number(a.localTimestamp)),N=n=>k(n).filter(e=>e.pending),$=(n,e)=>n[e],b=(n,e)=>k(n).filter(a=>a.from.toLowerCase()===e.toLowerCase()),j=(n,e)=>b(n,e).filter(a=>a.pending);var y=({adapterKey:n,adapter:e})=>{if(Array.isArray(e)){if(e.length===0){console.error("Adapter selection failed: The provided adapters array is empty.");return}let a=e.find(t=>t.key===n);return a||(console.warn(`No adapter found for key: "${n}". Falling back to the first available adapter: "${e[0].key}".`),e[0])}return e};function Q({onSucceedCallbacks:n,adapter:e,...a}){return vanilla.createStore()(middleware.persist((t,i)=>({...A({onSucceedCallbacks:n})(t,i),initializeTransactionsPool:async()=>{let r=Object.values(i().transactionsPool).filter(s=>s.pending);await Promise.all(r.map(s=>y({adapterKey:s.adapter,adapter:e})?.checkAndInitializeTrackerInStore({tx:s,...i()})));},handleTransaction:async({defaultTracker:r,actionFunction:s,params:c})=>{let{desiredChainID:x,...m}=c,g=K__default.default().unix();t({initialTx:{...c,actionFunction:s,localTimestamp:g,isInitializing:true}});let l=y({adapterKey:m.adapter,adapter:e}),d=o=>{let u=o instanceof Error?o.message:String(o);t(T=>immer.produce(T,p=>{p.initialTx&&(p.initialTx.isInitializing=false,p.initialTx.errorMessage=u);}));};if(!l){let o=new Error("No adapter found for this transaction.");throw d(o),o}try{let{walletType:o,walletAddress:u}=l.getWalletInfo();await l.checkChainForTx(x);let T=await s();if(!T){t({initialTx:void 0});return}let{tracker:p,txKey:P}=l.checkTransactionsTracker(T,o),v={...m,walletType:o,from:u,tracker:p||r,chainId:x,localTimestamp:g,txKey:P,hash:p==="ethereum"?T:void 0,pending:!1,isTrackedModalOpen:c.withTrackedModal};i().addTxToPool(v),t(I=>immer.produce(I,R=>{R.initialTx&&(R.initialTx.isInitializing=!1,R.initialTx.lastTxKey=P);}));let h=i().transactionsPool[P];await l.checkAndInitializeTrackerInStore({tx:h,...i()});}catch(o){throw d(o),o}}}),{...a}))}var E=(t=>(t.EVM="evm",t.SOLANA="solana",t.Starknet="starknet",t))(E||{}),z=(t=>(t.Failed="Failed",t.Success="Success",t.Replaced="Replaced",t))(z||{});var ne=(n=>e=>zustand.useStore(n,e));var L=5e3,C=10;function ie(n){let{tx:e,fetcher:a,onInitialize:t,onSuccess:i,onFailure:r,onIntervalTick:s,onReplaced:c,removeTxFromPool:x,pollingInterval:m=L,maxRetries:g=C}=n;if(!e.pending)return;t?.();let l=g,d=true,o=T=>{d&&(d=false,x&&!T?.withoutRemoving&&x(e.txKey));};(async()=>{for(;d&&l>0;)try{if(await new Promise(T=>setTimeout(T,m)),!d)break;await a({tx:e,stopPolling:o,onSuccess:i,onFailure:r,onIntervalTick:s,onReplaced:c});}catch(T){console.error(`Polling fetcher for txKey ${e.txKey} threw an error:`,T),l--;}l<=0&&(console.warn(`Polling for txKey ${e.txKey} stopped after reaching the maximum number of retries.`),r(),o());})();}exports.TransactionAdapter=E;exports.TransactionStatus=z;exports.createBoundedUseStore=ne;exports.createPulsarStore=Q;exports.initializePollingTracker=ie;exports.initializeTxTrackingStore=A;exports.selectAdapterByKey=y;exports.selectAllTransactions=k;exports.selectAllTransactionsByActiveWallet=b;exports.selectPendingTransactions=N;exports.selectPendingTransactionsByActiveWallet=j;exports.selectTxByKey=$;//# sourceMappingURL=index.js.map
1
+ 'use strict';var immer=require('immer'),w=require('dayjs'),middleware=require('zustand/middleware'),vanilla=require('zustand/vanilla'),zustand=require('zustand');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var w__default=/*#__PURE__*/_interopDefault(w);function k({onSucceedCallbacks:r}){return (e,a)=>({onSucceedCallbacks:r,transactionsPool:{},lastAddedTxKey:void 0,initialTx:void 0,addTxToPool:t=>{e(n=>immer.produce(n,i=>{i.lastAddedTxKey=t.txKey,t.txKey&&(i.transactionsPool[t.txKey]={...t,pending:true});}));},updateTxParams:(t,n)=>{e(i=>immer.produce(i,s=>{let l=s.transactionsPool[t];l&&Object.assign(l,n);}));},removeTxFromPool:t=>{e(n=>immer.produce(n,i=>{delete i.transactionsPool[t];}));},closeTxTrackedModal:t=>{e(n=>immer.produce(n,i=>{t&&i.transactionsPool[t]&&(i.transactionsPool[t].isTrackedModalOpen=false),i.initialTx=void 0;}));},getLastTxKey:()=>a().lastAddedTxKey})}var h=r=>Object.values(r).sort((e,a)=>Number(e.localTimestamp)-Number(a.localTimestamp)),N=r=>h(r).filter(e=>e.pending),j=(r,e)=>r[e],b=(r,e)=>h(r).filter(a=>a.from.toLowerCase()===e.toLowerCase()),G=(r,e)=>b(r,e).filter(a=>a.pending);var S=({adapterKey:r,adapter:e})=>{if(Array.isArray(e)){if(e.length===0){console.error("Adapter selection failed: The provided adapters array is empty.");return}let a=e.find(t=>t.key===r);return a||(console.warn(`No adapter found for key: "${r}". Falling back to the first available adapter: "${e[0].key}".`),e[0])}return e};function Y({onSucceedCallbacks:r,adapter:e,...a}){return vanilla.createStore()(middleware.persist((t,n)=>({...k({onSucceedCallbacks:r})(t,n),initializeTransactionsPool:async()=>{let i=Object.values(n().transactionsPool).filter(s=>s.pending);await Promise.all(i.map(s=>S({adapterKey:s.adapter,adapter:e})?.checkAndInitializeTrackerInStore({tx:s,...n()})));},handleTransaction:async({defaultTracker:i,actionFunction:s,params:l})=>{let{desiredChainID:x,...m}=l,g=w__default.default().unix();t({initialTx:{...l,actionFunction:s,localTimestamp:g,isInitializing:true}});let T=S({adapterKey:m.adapter,adapter:e}),d=o=>{let u=o instanceof Error?o.message:String(o);t(c=>immer.produce(c,p=>{p.initialTx&&(p.initialTx.isInitializing=false,p.initialTx.errorMessage=u);}));};if(!T){let o=new Error("No adapter found for this transaction.");throw d(o),o}try{let{walletType:o,walletAddress:u}=T.getWalletInfo();await T.checkChainForTx(x);let c=await s();if(!c){t({initialTx:void 0});return}let{tracker:p,txKey:y}=T.checkTransactionsTracker(c,o),A={...m,walletType:o,from:u,tracker:p||i,chainId:x,localTimestamp:g,txKey:y,hash:p==="ethereum"?c:void 0,pending:!1,isTrackedModalOpen:l.withTrackedModal};n().addTxToPool(A),t(K=>immer.produce(K,P=>{P.initialTx&&(P.initialTx.isInitializing=!1,P.initialTx.lastTxKey=y);}));let I=n().transactionsPool[y];await T.checkAndInitializeTrackerInStore({tx:I,...n()});}catch(o){throw d(o),o}}}),{...a}))}var E=(t=>(t.EVM="evm",t.SOLANA="solana",t.Starknet="starknet",t))(E||{}),z=(n=>(n.Ethereum="ethereum",n.Safe="safe",n.Gelato="gelato",n.Solana="solana",n))(z||{}),M=(t=>(t.Failed="Failed",t.Success="Success",t.Replaced="Replaced",t))(M||{});var re=(r=>e=>zustand.useStore(r,e));var C=5e3,O=10;function oe(r){let{tx:e,fetcher:a,onInitialize:t,onSuccess:n,onFailure:i,onIntervalTick:s,onReplaced:l,removeTxFromPool:x,pollingInterval:m=C,maxRetries:g=O}=r;if(!e.pending)return;t?.();let T=g,d=true,o=c=>{d&&(d=false,x&&!c?.withoutRemoving&&x(e.txKey));};(async()=>{for(;d&&T>0;)try{if(await new Promise(c=>setTimeout(c,m)),!d)break;await a({tx:e,stopPolling:o,onSuccess:n,onFailure:i,onIntervalTick:s,onReplaced:l});}catch(c){console.error(`Polling fetcher for txKey ${e.txKey} threw an error:`,c),T--;}T<=0&&(console.warn(`Polling for txKey ${e.txKey} stopped after reaching the maximum number of retries.`),i(),o());})();}exports.TransactionAdapter=E;exports.TransactionStatus=M;exports.TransactionTracker=z;exports.createBoundedUseStore=re;exports.createPulsarStore=Y;exports.initializePollingTracker=oe;exports.initializeTxTrackingStore=k;exports.selectAdapterByKey=S;exports.selectAllTransactions=h;exports.selectAllTransactionsByActiveWallet=b;exports.selectPendingTransactions=N;exports.selectPendingTransactionsByActiveWallet=G;exports.selectTxByKey=j;//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map