@tuwaio/pulsar-core 0.1.3 → 0.1.5

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>, 'updateTxParams' | '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?: (tx: T) => 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,13 @@ 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;
276
+ /** Callback to execute when the transaction is successfully submitted. */
277
+ onSucceedCallback?: (tx: T) => Promise<void> | void;
252
278
  }) => Promise<void>;
253
279
  /**
254
280
  * Initializes trackers for all pending transactions in the pool.
@@ -264,37 +290,31 @@ type ITxTrackingStore<TR, T extends Transaction<TR>, A> = IInitializeTxTrackingS
264
290
 
265
291
  /**
266
292
  * 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.
293
+ * @template T The type of the transaction object being tracked.
269
294
  */
270
- type TransactionPool<TR, T extends Transaction<TR>> = Record<string, T>;
295
+ type TransactionPool<T extends Transaction> = Record<string, T>;
271
296
  /**
272
297
  * A utility type that creates a union of all fields that can be safely updated
273
298
  * on a transaction object via the `updateTxParams` action. This ensures type safety
274
299
  * and prevents accidental modification of immutable properties.
275
- * @template TR The type of the tracker identifier.
276
300
  */
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'>>;
301
+ 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
302
  /**
279
303
  * The interface for the base transaction tracking store slice.
280
304
  * It includes the state and actions for managing the transaction lifecycle.
281
- * @template TR The type of the tracker identifier.
282
305
  * @template T The specific transaction type.
283
- * @template A The return type of the initial action function.
284
306
  */
285
- interface IInitializeTxTrackingStore<TR, T extends Transaction<TR>, A> {
286
- /** A callback function executed when any transaction successfully completes. */
287
- onSucceedCallbacks?: (tx: T) => Promise<void> | void;
307
+ interface IInitializeTxTrackingStore<T extends Transaction> {
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,11 @@ 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
- * @param options.onSucceedCallbacks An optional async callback to run when a transaction succeeds.
314
331
  * @returns A Zustand store slice implementing `IInitializeTxTrackingStore`.
315
332
  */
316
- declare function initializeTxTrackingStore<TR, T extends Transaction<TR>, A>({ onSucceedCallbacks, }: {
317
- onSucceedCallbacks?: (tx: T) => Promise<void> | void;
318
- }): StoreSlice<IInitializeTxTrackingStore<TR, T, A>>;
333
+ declare function initializeTxTrackingStore<T extends Transaction>(): StoreSlice<IInitializeTxTrackingStore<T>>;
319
334
 
320
335
  /**
321
336
  * @file This file contains selector functions for deriving state from the transaction tracking store.
@@ -324,47 +339,42 @@ declare function initializeTxTrackingStore<TR, T extends Transaction<TR>, A>({ o
324
339
 
325
340
  /**
326
341
  * 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
342
  * @template T - The transaction type.
329
- * @param {TransactionPool<TR, T>} transactionsPool - The entire transaction pool from the store.
343
+ * @param {TransactionPool<T>} transactionsPool - The entire transaction pool from the store.
330
344
  * @returns {T[]} An array of all transactions, sorted chronologically.
331
345
  */
332
- declare const selectAllTransactions: <TR, T extends Transaction<TR>>(transactionsPool: TransactionPool<TR, T>) => T[];
346
+ declare const selectAllTransactions: <T extends Transaction>(transactionsPool: TransactionPool<T>) => T[];
333
347
  /**
334
348
  * Selects all transactions that are currently in a pending state, sorted chronologically.
335
- * @template TR - The type of the tracker identifier.
336
349
  * @template T - The transaction type.
337
- * @param {TransactionPool<TR, T>} transactionsPool - The entire transaction pool from the store.
350
+ * @param {TransactionPool<T>} transactionsPool - The entire transaction pool from the store.
338
351
  * @returns {T[]} An array of pending transactions.
339
352
  */
340
- declare const selectPendingTransactions: <TR, T extends Transaction<TR>>(transactionsPool: TransactionPool<TR, T>) => T[];
353
+ declare const selectPendingTransactions: <T extends Transaction>(transactionsPool: TransactionPool<T>) => T[];
341
354
  /**
342
355
  * Selects a single transaction from the pool by its unique key (`txKey`).
343
- * @template TR - The type of the tracker identifier.
344
356
  * @template T - The transaction type.
345
- * @param {TransactionPool<TR, T>} transactionsPool - The entire transaction pool from the store.
357
+ * @param {TransactionPool<T>} transactionsPool - The entire transaction pool from the store.
346
358
  * @param {string} key - The `txKey` of the transaction to retrieve.
347
359
  * @returns {T | undefined} The transaction object if found, otherwise undefined.
348
360
  */
349
- declare const selectTxByKey: <TR, T extends Transaction<TR>>(transactionsPool: TransactionPool<TR, T>, key: string) => T | undefined;
361
+ declare const selectTxByKey: <T extends Transaction>(transactionsPool: TransactionPool<T>, key: string) => T | undefined;
350
362
  /**
351
363
  * Selects all transactions initiated by a specific wallet address, sorted chronologically.
352
- * @template TR - The type of the tracker identifier.
353
364
  * @template T - The transaction type.
354
- * @param {TransactionPool<TR, T>} transactionsPool - The entire transaction pool from the store.
365
+ * @param {TransactionPool<T>} transactionsPool - The entire transaction pool from the store.
355
366
  * @param {string} from - The wallet address (`from` address) to filter transactions by.
356
367
  * @returns {T[]} An array of transactions associated with the given wallet.
357
368
  */
358
- declare const selectAllTransactionsByActiveWallet: <TR, T extends Transaction<TR>>(transactionsPool: TransactionPool<TR, T>, from: string) => T[];
369
+ declare const selectAllTransactionsByActiveWallet: <T extends Transaction>(transactionsPool: TransactionPool<T>, from: string) => T[];
359
370
  /**
360
371
  * Selects all pending transactions for a specific wallet address, sorted chronologically.
361
- * @template TR - The type of the tracker identifier.
362
372
  * @template T - The transaction type.
363
- * @param {TransactionPool<TR, T>} transactionsPool - The entire transaction pool from the store.
373
+ * @param {TransactionPool<T>} transactionsPool - The entire transaction pool from the store.
364
374
  * @param {string} from - The wallet address (`from` address) to filter transactions by.
365
375
  * @returns {T[]} An array of pending transactions for the given wallet.
366
376
  */
367
- declare const selectPendingTransactionsByActiveWallet: <TR, T extends Transaction<TR>>(transactionsPool: TransactionPool<TR, T>, from: string) => T[];
377
+ declare const selectPendingTransactionsByActiveWallet: <T extends Transaction>(transactionsPool: TransactionPool<T>, from: string) => T[];
368
378
 
369
379
  /**
370
380
  * Creates the main Pulsar store for transaction tracking.
@@ -373,30 +383,26 @@ declare const selectPendingTransactionsByActiveWallet: <TR, T extends Transactio
373
383
  * slice with a powerful orchestration logic that leverages chain-specific adapters to handle the entire
374
384
  * lifecycle of a transaction—from initiation and chain validation to execution and background status tracking.
375
385
  *
376
- * @template TR The type of the tracker identifier (e.g., a string enum).
377
386
  * @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
387
  *
380
388
  * @param config Configuration object for creating the store.
381
- * @param config.onSucceedCallbacks Optional async callback executed on transaction success.
382
389
  * @param config.adapter Adapter or an array of adapters for different chains or transaction types.
383
390
  * @param options Configuration for the Zustand `persist` middleware.
384
391
  * @returns A fully configured Zustand store instance.
385
392
  */
386
- declare function createPulsarStore<TR, T extends Transaction<TR>, A>({ onSucceedCallbacks, adapter, ...options }: {
387
- 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;
393
+ declare function createPulsarStore<T extends Transaction>({ adapter, ...options }: {
394
+ adapter: TxAdapter<T> | TxAdapter<T>[];
395
+ } & PersistOptions<ITxTrackingStore<T>>): Omit<zustand.StoreApi<ITxTrackingStore<T>>, "setState" | "persist"> & {
396
+ setState(partial: ITxTrackingStore<T> | Partial<ITxTrackingStore<T>> | ((state: ITxTrackingStore<T>) => ITxTrackingStore<T> | Partial<ITxTrackingStore<T>>), replace?: false | undefined): unknown;
397
+ setState(state: ITxTrackingStore<T> | ((state: ITxTrackingStore<T>) => ITxTrackingStore<T>), replace: true): unknown;
392
398
  persist: {
393
- setOptions: (options: Partial<PersistOptions<ITxTrackingStore<TR, T, A>, ITxTrackingStore<TR, T, A>, unknown>>) => void;
399
+ setOptions: (options: Partial<PersistOptions<ITxTrackingStore<T>, ITxTrackingStore<T>, unknown>>) => void;
394
400
  clearStorage: () => void;
395
401
  rehydrate: () => Promise<void> | void;
396
402
  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>>;
403
+ onHydrate: (fn: (state: ITxTrackingStore<T>) => void) => () => void;
404
+ onFinishHydration: (fn: (state: ITxTrackingStore<T>) => void) => () => void;
405
+ getOptions: () => Partial<PersistOptions<ITxTrackingStore<T>, ITxTrackingStore<T>, unknown>>;
400
406
  };
401
407
  };
402
408
 
@@ -445,8 +451,8 @@ declare const createBoundedUseStore: <S extends StoreApi<unknown>>(store: S) =>
445
451
  /**
446
452
  * Defines the parameters for the fetcher function used within the polling tracker.
447
453
  * 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.
454
+ * @template R The expected type of the successful API response.
455
+ * @template T The type of the transaction object being tracked.
450
456
  */
451
457
  type PollingFetcherParams<R, T> = {
452
458
  /** The transaction object being tracked. */
@@ -466,13 +472,12 @@ type PollingFetcherParams<R, T> = {
466
472
  };
467
473
  /**
468
474
  * 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.
475
+ * @template R The expected type of the successful API response.
476
+ * @template T The type of the transaction object.
472
477
  */
473
- type PollingTrackerConfig<R, T, TR> = {
478
+ type PollingTrackerConfig<R, T extends Transaction> = {
474
479
  /** The transaction object to be tracked. It must include `txKey` and `pending` status. */
475
- tx: T & Pick<Transaction<TR>, 'txKey' | 'pending'>;
480
+ tx: T & Pick<Transaction, 'txKey' | 'pending'>;
476
481
  /** The function that performs the data fetching (e.g., an API call) on each interval. */
477
482
  fetcher: (params: PollingFetcherParams<R, T>) => Promise<void>;
478
483
  /** Callback to be invoked when the transaction successfully completes. */
@@ -501,10 +506,9 @@ type PollingTrackerConfig<R, T, TR> = {
501
506
  *
502
507
  * @template R The expected type of the API response.
503
508
  * @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.
509
+ * @param {PollingTrackerConfig<R, T>} config - The configuration for the tracker.
506
510
  */
507
- declare function initializePollingTracker<R, T, TR>(config: PollingTrackerConfig<R, T, TR>): void;
511
+ declare function initializePollingTracker<R, T extends Transaction>(config: PollingTrackerConfig<R, T>): void;
508
512
 
509
513
  /**
510
514
  * @file This file contains a utility function for selecting a specific transaction adapter from a list.
@@ -518,19 +522,17 @@ declare function initializePollingTracker<R, T, TR>(config: PollingTrackerConfig
518
522
  * and returns the first adapter in the array as a fallback. This fallback mechanism
519
523
  * ensures that the system can still function, but it highlights a potential configuration issue.
520
524
  *
521
- * @template TR - The type of the tracker identifier.
522
525
  * @template T - The transaction type, extending the base `Transaction`.
523
- * @template A - The type for the adapter-specific context or API.
524
526
  *
525
527
  * @param {object} params - The parameters for the selection.
526
528
  * @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.
529
+ * @param {TxAdapter<T> | TxAdapter<T>[]} params.adapter - Adapter or an array of adapters for different chains or transaction types.
528
530
  *
529
- * @returns {TxAdapter<TR, T, A> | undefined} The found transaction adapter, the fallback adapter, or undefined if the adapters array is empty.
531
+ * @returns {TxAdapter<T> | undefined} The found transaction adapter, the fallback adapter, or undefined if the adapters array is empty.
530
532
  */
531
- declare const selectAdapterByKey: <TR, T extends Transaction<TR>, A>({ adapterKey, adapter, }: {
533
+ declare const selectAdapterByKey: <T extends Transaction>({ adapterKey, adapter, }: {
532
534
  adapterKey: TransactionAdapter;
533
- adapter: TxAdapter<TR, T, A> | TxAdapter<TR, T, A>[];
534
- }) => TxAdapter<TR, T, A> | undefined;
535
+ adapter: TxAdapter<T> | TxAdapter<T>[];
536
+ }) => TxAdapter<T> | undefined;
535
537
 
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 };
538
+ 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'),z=require('dayjs'),middleware=require('zustand/middleware'),vanilla=require('zustand/vanilla'),zustand=require('zustand');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var z__default=/*#__PURE__*/_interopDefault(z);function A(){return (r,t)=>({transactionsPool:{},lastAddedTxKey:void 0,initialTx:void 0,addTxToPool:e=>{r(n=>immer.produce(n,i=>{i.lastAddedTxKey=e.txKey,e.txKey&&(i.transactionsPool[e.txKey]={...e,pending:true});}));},updateTxParams:(e,n)=>{r(i=>immer.produce(i,a=>{let l=a.transactionsPool[e];l&&Object.assign(l,n);}));},removeTxFromPool:e=>{r(n=>immer.produce(n,i=>{delete i.transactionsPool[e];}));},closeTxTrackedModal:e=>{r(n=>immer.produce(n,i=>{e&&i.transactionsPool[e]&&(i.transactionsPool[e].isTrackedModalOpen=false),i.initialTx=void 0;}));},getLastTxKey:()=>t().lastAddedTxKey})}var v=r=>Object.values(r).sort((t,e)=>Number(t.localTimestamp)-Number(e.localTimestamp)),j=r=>v(r).filter(t=>t.pending),G=(r,t)=>r[t],F=(r,t)=>v(r).filter(e=>e.from.toLowerCase()===t.toLowerCase()),D=(r,t)=>F(r,t).filter(e=>e.pending);var R=(n=>(n.EVM="evm",n.SOLANA="solana",n.Starknet="starknet",n))(R||{}),E=(i=>(i.Ethereum="ethereum",i.Safe="safe",i.Gelato="gelato",i.Solana="solana",i))(E||{}),I=(n=>(n.Failed="Failed",n.Success="Success",n.Replaced="Replaced",n))(I||{});var k=({adapterKey:r,adapter:t})=>{if(Array.isArray(t)){if(t.length===0){console.error("Adapter selection failed: The provided adapters array is empty.");return}let e=t.find(n=>n.key===r);return e||(console.warn(`No adapter found for key: "${r}". Falling back to the first available adapter: "${t[0].key}".`),t[0])}return t};function ie({adapter:r,...t}){return vanilla.createStore()(middleware.persist((e,n)=>({...A()(e,n),initializeTransactionsPool:async()=>{let i=Object.values(n().transactionsPool).filter(a=>a.pending);await Promise.all(i.map(a=>k({adapterKey:a.adapter,adapter:r})?.checkAndInitializeTrackerInStore({tx:a,...n()})));},handleTransaction:async({defaultTracker:i,actionFunction:a,onSucceedCallback:l,params:p})=>{let{desiredChainID:x,...m}=p,g=z__default.default().unix();e({initialTx:{...p,actionFunction:a,localTimestamp:g,isInitializing:true}});let c=k({adapterKey:m.adapter,adapter:r}),T=o=>{let u=o instanceof Error?o.message:String(o);e(s=>immer.produce(s,d=>{d.initialTx&&(d.initialTx.isInitializing=false,d.initialTx.errorMessage=u);}));};if(!c){let o=new Error("No adapter found for this transaction.");throw T(o),o}try{let{walletType:o,walletAddress:u}=c.getWalletInfo();await c.checkChainForTx(x);let s=await a();if(!s){e({initialTx:void 0});return}let{tracker:d,txKey:y}=c.checkTransactionsTracker(s,o),b={...m,walletType:o,from:u,tracker:d||i,chainId:x,localTimestamp:g,txKey:y,hash:d==="ethereum"?s:void 0,pending:!1,isTrackedModalOpen:p.withTrackedModal};n().addTxToPool(b),e(w=>immer.produce(w,S=>{S.initialTx&&(S.initialTx.isInitializing=!1,S.initialTx.lastTxKey=y);}));let h=n().transactionsPool[y];await c.checkAndInitializeTrackerInStore({tx:h,...n()});let P=n().transactionsPool[h.txKey];P.status==="Success"&&l&&P&&l(P);}catch(o){throw T(o),o}}}),{...t}))}var ce=(r=>t=>zustand.useStore(r,t));var B=5e3,U=10;function Te(r){let{tx:t,fetcher:e,onInitialize:n,onSuccess:i,onFailure:a,onIntervalTick:l,onReplaced:p,removeTxFromPool:x,pollingInterval:m=B,maxRetries:g=U}=r;if(!t.pending)return;n?.();let c=g,T=true,o=s=>{T&&(T=false,x&&!s?.withoutRemoving&&x(t.txKey));};(async()=>{for(;T&&c>0;)try{if(await new Promise(s=>setTimeout(s,m)),!T)break;await e({tx:t,stopPolling:o,onSuccess:i,onFailure:a,onIntervalTick:l,onReplaced:p});}catch(s){console.error(`Polling fetcher for txKey ${t.txKey} threw an error:`,s),c--;}c<=0&&(console.warn(`Polling for txKey ${t.txKey} stopped after reaching the maximum number of retries.`),a(),o());})();}exports.TransactionAdapter=R;exports.TransactionStatus=I;exports.TransactionTracker=E;exports.createBoundedUseStore=ce;exports.createPulsarStore=ie;exports.initializePollingTracker=Te;exports.initializeTxTrackingStore=A;exports.selectAdapterByKey=k;exports.selectAllTransactions=v;exports.selectAllTransactionsByActiveWallet=F;exports.selectPendingTransactions=j;exports.selectPendingTransactionsByActiveWallet=D;exports.selectTxByKey=G;//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map