@tuwaio/pulsar-core 0.0.6 → 0.1.1

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
@@ -4,14 +4,14 @@ import { PersistOptions } from 'zustand/middleware';
4
4
 
5
5
  /**
6
6
  * @file This file defines the core data structures and TypeScript types for the Pulsar transaction tracking engine.
7
- * It includes types for transactions, their statuses, store interfaces, and utility types for Zustand slices.
8
- * These types are framework-agnostic and form the foundation of the entire tracking system.
7
+ * It specifies the framework-agnostic models for transactions, their lifecycle statuses, and the interfaces for
8
+ * the Zustand-based store and chain-specific adapters.
9
9
  */
10
10
 
11
11
  /**
12
12
  * A utility type for creating modular Zustand store slices, enabling composable state management.
13
- * @template T - The type of the state slice.
14
- * @template S - The type of the full store state, defaulting to T.
13
+ * @template T The state slice being defined.
14
+ * @template S The full store state that includes the slice `T`.
15
15
  */
16
16
  type StoreSlice<T extends object, S extends object = T> = (set: StoreApi<S extends T ? S : S & T>['setState'], get: StoreApi<S extends T ? S : S & T>['getState']) => T;
17
17
  /**
@@ -31,22 +31,27 @@ declare enum TransactionAdapter {
31
31
  declare enum TransactionStatus {
32
32
  /** The transaction failed to execute due to an on-chain error or rejection. */
33
33
  Failed = "Failed",
34
- /** The transaction was successfully mined and executed. */
34
+ /** The transaction was successfully mined and included in a block. */
35
35
  Success = "Success",
36
36
  /** The transaction was replaced by another with the same nonce (e.g., a speed-up or cancel). */
37
37
  Replaced = "Replaced"
38
38
  }
39
39
  /**
40
40
  * The fundamental structure for any transaction being tracked by Pulsar.
41
- * This forms the base upon which chain-specific transaction types are built.
42
- * @template T - The type of the tracker identifier (e.g., 'ethereum', 'gelato', 'safe').
41
+ * 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
43
  */
44
44
  type BaseTransaction<T> = {
45
- /** A unique key identifying a re-executable action from the `TxActions` registry. */
46
- actionKey?: string;
47
45
  /** The chain identifier (e.g., 1 for Ethereum Mainnet, 'SN_MAIN' for Starknet). */
48
46
  chainId: number | string;
49
- /** A user-facing description. Can be a single string or an array for [pending, success, error, replaced] states. */
47
+ /**
48
+ * User-facing description. Can be a single string for all states, or a tuple for specific states.
49
+ * @example
50
+ * // A single description for all states
51
+ * description: 'Swap 1 ETH for 1,500 USDC'
52
+ * // Specific descriptions for each state in order: [pending, success, error, replaced]
53
+ * description: ['Swapping...', 'Swapped Successfully', 'Swap Failed', 'Swap Replaced']
54
+ */
50
55
  description?: string | [string, string, string, string];
51
56
  /** The error message if the transaction failed. */
52
57
  errorMessage?: string;
@@ -66,7 +71,14 @@ type BaseTransaction<T> = {
66
71
  pending: boolean;
67
72
  /** The final on-chain status of the transaction. */
68
73
  status?: TransactionStatus;
69
- /** A user-facing title. Can be a single string or an array for [pending, success, error, replaced] states. */
74
+ /**
75
+ * User-facing title. Can be a single string for all states, or a tuple for specific states.
76
+ * @example
77
+ * // A single title for all states
78
+ * title: 'ETH/USDC Swap'
79
+ * // Specific titles for each state in order: [pending, success, error, replaced]
80
+ * title: ['Processing Swap', 'Swap Complete', 'Swap Error', 'Swap Replaced']
81
+ */
70
82
  title?: string | [string, string, string, string];
71
83
  /** The specific tracker responsible for monitoring this transaction's status. */
72
84
  tracker: T;
@@ -79,7 +91,7 @@ type BaseTransaction<T> = {
79
91
  };
80
92
  /**
81
93
  * Represents an EVM-specific transaction, extending the base properties with EVM fields.
82
- * @template T - The type of the tracker identifier.
94
+ * @template T The type of the tracker identifier.
83
95
  */
84
96
  type EvmTransaction<T> = BaseTransaction<T> & {
85
97
  adapter: TransactionAdapter.EVM;
@@ -102,7 +114,7 @@ type EvmTransaction<T> = BaseTransaction<T> & {
102
114
  };
103
115
  /**
104
116
  * Represents a Solana-specific transaction, extending the base properties.
105
- * @template T - The type of the tracker identifier.
117
+ * @template T The type of the tracker identifier.
106
118
  */
107
119
  type SolanaTransaction<T> = BaseTransaction<T> & {
108
120
  adapter: TransactionAdapter.SOLANA;
@@ -114,10 +126,14 @@ type SolanaTransaction<T> = BaseTransaction<T> & {
114
126
  recentBlockhash?: string;
115
127
  /** The slot in which the transaction was processed. */
116
128
  slot?: number;
129
+ /** The number of confirmations received. `null` if the transaction is pending or unconfirmed. */
130
+ confirmations?: number | null;
131
+ /** The RPC URL used to submit and track this transaction. */
132
+ rpcUrl?: string;
117
133
  };
118
134
  /**
119
135
  * Represents a Starknet-specific transaction, extending the base properties.
120
- * @template T - The type of the tracker identifier.
136
+ * @template T The type of the tracker identifier.
121
137
  */
122
138
  type StarknetTransaction<T> = BaseTransaction<T> & {
123
139
  adapter: TransactionAdapter.Starknet;
@@ -133,36 +149,33 @@ type StarknetTransaction<T> = BaseTransaction<T> & {
133
149
  };
134
150
  /** A union type representing any possible transaction structure that Pulsar can handle. */
135
151
  type Transaction<T> = EvmTransaction<T> | SolanaTransaction<T> | StarknetTransaction<T>;
136
- /**
137
- * A registry of functions that can be re-executed, keyed by `actionKey`.
138
- * Used for implementing "Retry" functionality.
139
- */
140
- type TxActions = Record<string, (...args: any[]) => Promise<unknown>>;
141
152
  /**
142
153
  * Represents the parameters required to initiate a new transaction tracking flow.
143
154
  */
144
- type InitialTransactionParams = {
155
+ type InitialTransactionParams<A> = {
145
156
  adapter: TransactionAdapter;
146
- /** A key to identify the re-executable action from the `TxActions` registry. */
147
- actionKey?: string;
148
- /** A user-facing description for the transaction. */
157
+ /** The function that executes the on-chain action (e.g., sending a transaction) and returns a preliminary identifier like a hash. */
158
+ actionFunction: (...args: any[]) => Promise<A | undefined>;
159
+ /** A user-facing description for the transaction. Supports state-specific descriptions. */
149
160
  description?: string | [string, string, string, string];
150
161
  /** The target chain ID for the transaction. */
151
162
  desiredChainID: number | string;
152
163
  /** Any custom data to associate with the transaction. */
153
164
  payload?: object;
154
- /** A user-facing title for the transaction. */
165
+ /** A user-facing title for the transaction. Supports state-specific titles. */
155
166
  title?: string | [string, string, string, string];
156
167
  /** The application-specific type of the transaction. */
157
168
  type: string;
158
169
  /** If true, the detailed tracking modal will open automatically upon initiation. */
159
170
  withTrackedModal?: boolean;
171
+ /** The RPC URL to use for the transaction. Required for Solana transactions. */
172
+ rpcUrl?: string;
160
173
  };
161
174
  /**
162
175
  * Represents a transaction in its temporary, pre-submission state.
163
176
  * This is used for UI feedback while the transaction is being signed and sent.
164
177
  */
165
- type InitialTransaction = InitialTransactionParams & {
178
+ type InitialTransaction<A> = InitialTransactionParams<A> & {
166
179
  /** An error message if the initialization fails (e.g., user rejects signature). */
167
180
  errorMessage?: string;
168
181
  /** A flag indicating if the transaction is being processed (e.g., waiting for signature). */
@@ -174,9 +187,9 @@ type InitialTransaction = InitialTransactionParams & {
174
187
  };
175
188
  /**
176
189
  * Defines the interface for a transaction adapter, which provides chain-specific logic and utilities.
177
- * @template TR - The type of the tracker identifier (e.g., a string enum).
178
- * @template T - The specific transaction type, extending `Transaction<TR>`.
179
- * @template A - The type of the key returned by the `actionFunction` (e.g., a transaction hash).
190
+ * @template TR The type of the tracker identifier (e.g., a string enum).
191
+ * @template T The specific transaction type, extending `Transaction<TR>`.
192
+ * @template A The type of the key returned by the `actionFunction` (e.g., a transaction hash).
180
193
  */
181
194
  type TxAdapter<TR, T extends Transaction<TR>, A> = {
182
195
  /** The unique key identifying this adapter. */
@@ -186,18 +199,18 @@ type TxAdapter<TR, T extends Transaction<TR>, A> = {
186
199
  walletAddress: string;
187
200
  walletType: string;
188
201
  };
189
- /** Ensures the connected wallet is on the correct network for the transaction. */
202
+ /** Ensures the connected wallet is on the correct network for the transaction. Throws an error if the chain is mismatched. */
190
203
  checkChainForTx: (chainId: string | number) => Promise<void>;
191
- /** Determines the appropriate tracker and final `txKey` based on the result of an action. */
204
+ /** Determines the appropriate tracker and final `txKey` from the result of an action. */
192
205
  checkTransactionsTracker: (actionTxKey: A, walletType: string) => {
193
206
  txKey: string;
194
207
  tracker: TR;
195
208
  };
196
- /** Initializes the correct background tracker for a given transaction. */
209
+ /** Selects and initializes the correct background tracker for a given transaction. */
197
210
  checkAndInitializeTrackerInStore: (params: {
198
211
  tx: T;
199
212
  } & Pick<ITxTrackingStore<TR, T, A>, 'transactionsPool' | 'updateTxParams' | 'onSucceedCallbacks' | 'removeTxFromPool'>) => Promise<void>;
200
- /** Returns the base URL for the blockchain explorer. */
213
+ /** Returns the base URL for the blockchain explorer for the current network. */
201
214
  getExplorerUrl: () => string | undefined;
202
215
  /** Optional: Fetches a name from a chain-specific name service (e.g., ENS). */
203
216
  getName?: (address: string) => Promise<string | null>;
@@ -210,30 +223,32 @@ type TxAdapter<TR, T extends Transaction<TR>, A> = {
210
223
  /** Optional: Logic to retry a failed transaction. */
211
224
  retryTxAction?: (params: {
212
225
  txKey: string;
213
- tx: InitialTransactionParams;
214
- actions?: TxActions;
226
+ tx: InitialTransactionParams<A>;
215
227
  onClose: (txKey?: string) => void;
216
228
  } & Partial<Pick<ITxTrackingStore<TR, T, A>, 'handleTransaction'>>) => Promise<void>;
217
- /** Optional: Constructs a full explorer URL for a specific transaction. */
229
+ /**
230
+ * Optional: Constructs a full explorer URL for a specific transaction.
231
+ * May require the full transaction pool to resolve details for replaced transactions.
232
+ */
218
233
  getExplorerTxUrl?: (transactionsPool: TransactionPool<TR, T>, txKey: string, replacedTxHash?: string) => string;
219
234
  };
220
235
  /**
221
236
  * The complete interface for the Pulsar transaction tracking store.
222
- * @template TR - The type of the tracker identifier.
223
- * @template T - The transaction type.
224
- * @template A - The return type of the `actionFunction`.
237
+ * @template TR The type of the tracker identifier.
238
+ * @template T The transaction type.
239
+ * @template A The return type of the `actionFunction`.
225
240
  */
226
- type ITxTrackingStore<TR, T extends Transaction<TR>, A> = IInitializeTxTrackingStore<TR, T> & {
241
+ type ITxTrackingStore<TR, T extends Transaction<TR>, A> = IInitializeTxTrackingStore<TR, T, A> & {
227
242
  /**
228
- * The core function that handles the entire lifecycle of a new transaction.
243
+ * The primary method for initiating and tracking a new transaction from start to finish.
229
244
  * It manages UI state, executes the on-chain action, and initiates background tracking.
230
- * @param params - The parameters for handling the transaction.
245
+ * @param params The parameters for handling the transaction.
231
246
  */
232
247
  handleTransaction: (params: {
233
248
  /** The async function to execute (e.g., a smart contract write call). Must return a unique key or undefined. */
234
249
  actionFunction: () => Promise<A | undefined>;
235
250
  /** The metadata for the transaction. */
236
- params: InitialTransactionParams;
251
+ params: Omit<InitialTransactionParams<A>, 'actionFunction'>;
237
252
  /** The default tracker to use if it cannot be determined automatically. */
238
253
  defaultTracker?: TR;
239
254
  }) => Promise<void>;
@@ -245,58 +260,64 @@ type ITxTrackingStore<TR, T extends Transaction<TR>, A> = IInitializeTxTrackingS
245
260
  };
246
261
 
247
262
  /**
248
- * @file This file provides the core slice for the Zustand store, responsible for managing the state of transactions.
249
- * It includes functions and types for initializing the store and performing basic CRUD operations on the transaction pool.
263
+ * @file This file defines the core Zustand slice for managing the state of transactions. It includes the state,
264
+ * actions, and types necessary for initializing the store and performing CRUD operations on the transaction pool.
250
265
  */
251
266
 
252
267
  /**
253
- * Defines the structure of the transaction pool, which is a record of transactions indexed by their unique keys.
254
- * @template TR - The type of the tracker identifier.
255
- * @template T - The transaction type.
268
+ * Defines the structure of the transaction pool, a key-value store of transactions indexed by their unique keys.
269
+ * @template TR The type of the tracker identifier.
270
+ * @template T The transaction type.
256
271
  */
257
272
  type TransactionPool<TR, T extends Transaction<TR>> = Record<string, T>;
258
273
  /**
259
- * A utility type that extracts a subset of fields from the `Transaction` type
260
- * that are updatable via the `updateTxParams` action.
261
- * @template TR - The type of the tracker identifier.
274
+ * A utility type that creates a union of all fields that can be safely updated
275
+ * on a transaction object via the `updateTxParams` action. This ensures type safety
276
+ * and prevents accidental modification of immutable properties.
277
+ * @template TR The type of the tracker identifier.
262
278
  */
263
- type UpdatableTransactionFields<TR> = Partial<Pick<EvmTransaction<TR>, 'to' | 'nonce' | 'txKey' | 'pending' | 'hash' | 'status' | 'replacedTxHash' | 'errorMessage' | 'finishedTimestamp' | 'isTrackedModalOpen' | 'isError' | 'maxPriorityFeePerGas' | 'maxFeePerGas' | 'input' | 'value'>>;
279
+ 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'>>;
264
280
  /**
265
- * Defines the interface for the base transaction tracking store slice.
266
- * It includes the state and actions for managing transactions.
267
- * @template TR - The type of the tracker identifier.
268
- * @template T - The transaction type.
281
+ * The interface for the base transaction tracking store slice.
282
+ * It includes the state and actions for managing the transaction lifecycle.
283
+ * @template TR The type of the tracker identifier.
284
+ * @template T The specific transaction type.
285
+ * @template A The return type of the initial action function.
269
286
  */
270
- interface IInitializeTxTrackingStore<TR, T extends Transaction<TR>> {
271
- /** An optional callback function to be executed when a transaction successfully completes. */
287
+ interface IInitializeTxTrackingStore<TR, T extends Transaction<TR>, A> {
288
+ /** A callback function executed when any transaction successfully completes. */
272
289
  onSucceedCallbacks?: (tx: T) => Promise<void> | void;
273
- /** A pool of all transactions currently being tracked, indexed by their `txKey`. */
290
+ /** A pool of all transactions currently being tracked, indexed by `txKey`. */
274
291
  transactionsPool: TransactionPool<TR, T>;
275
- /** The key of the most recently added transaction. */
292
+ /** The `txKey` of the most recently added transaction. */
276
293
  lastAddedTxKey?: string;
277
- /** The state of a transaction that is currently being initiated but not yet submitted. */
278
- initialTx?: InitialTransaction;
279
- /** Adds a new transaction to the tracking pool. */
280
- addTxToPool: (tx: T) => void;
281
- /** Updates one or more parameters of an existing transaction in the pool. */
294
+ /** The state for a transaction being initiated, used for UI feedback before it's submitted to the chain. */
295
+ initialTx?: InitialTransaction<A>;
296
+ /** Adds a new transaction to the tracking pool and marks it as pending. */
297
+ addTxToPool: (tx: Transaction<TR>) => void;
298
+ /** Updates one or more properties of an existing transaction in the pool. */
282
299
  updateTxParams: (txKey: string, fields: UpdatableTransactionFields<TR>) => void;
283
- /** Removes a transaction from the tracking pool using its key. */
300
+ /** Removes a transaction from the tracking pool by its key. */
284
301
  removeTxFromPool: (txKey: string) => void;
285
- /** Closes the tracking modal for a specific transaction. */
302
+ /** Closes the tracking modal for a transaction and clears any initial transaction state. */
286
303
  closeTxTrackedModal: (txKey?: string) => void;
287
- /** Returns the key of the last transaction that was added to the pool. */
304
+ /** A selector function to retrieve the key of the last transaction added to the pool. */
288
305
  getLastTxKey: () => string | undefined;
289
306
  }
290
307
  /**
291
- * Creates a Zustand store slice containing the core logic for transaction tracking.
292
- * This function is a slice creator and is meant to be used within `createStore` from Zustand.
293
- * @param {object} options - Configuration options for the store slice.
294
- * @param {function} [options.onSucceedCallbacks] - An optional async callback to run when a transaction succeeds.
295
- * @returns {StoreSlice<IInitializeTxTrackingStore<TR, T>>} A Zustand store slice.
308
+ * Creates a Zustand store slice with the core logic for transaction state management.
309
+ * This function is a slice creator intended for use with Zustand's `create` function.
310
+ *
311
+ * @template TR The type of the tracker identifier.
312
+ * @template T The specific transaction type.
313
+ * @template A The return type of the initial action function.
314
+ * @param options Configuration for the store slice.
315
+ * @param options.onSucceedCallbacks An optional async callback to run when a transaction succeeds.
316
+ * @returns A Zustand store slice implementing `IInitializeTxTrackingStore`.
296
317
  */
297
- declare function initializeTxTrackingStore<TR, T extends Transaction<TR>>({ onSucceedCallbacks, }: {
318
+ declare function initializeTxTrackingStore<TR, T extends Transaction<TR>, A>({ onSucceedCallbacks, }: {
298
319
  onSucceedCallbacks?: (tx: T) => Promise<void> | void;
299
- }): StoreSlice<IInitializeTxTrackingStore<TR, T>>;
320
+ }): StoreSlice<IInitializeTxTrackingStore<TR, T, A>>;
300
321
 
301
322
  /**
302
323
  * @file This file contains selector functions for deriving state from the transaction tracking store.
@@ -350,18 +371,18 @@ declare const selectPendingTransactionsByActiveWallet: <TR, T extends Transactio
350
371
  /**
351
372
  * Creates the main Pulsar store for transaction tracking.
352
373
  *
353
- * This function sets up a Zustand store with persistence, combining the core
354
- * transaction slice with adapter-specific logic to handle the entire lifecycle
355
- * of a transaction.
374
+ * This function configures a Zustand store enhanced with persistence. It combines the core transaction management
375
+ * slice with a powerful orchestration logic that leverages chain-specific adapters to handle the entire
376
+ * lifecycle of a transaction—from initiation and chain validation to execution and background status tracking.
356
377
  *
357
- * @template TR - The type of the tracker identifier (e.g., a string enum).
358
- * @template T - The specific transaction type, extending the base `Transaction`.
359
- * @template A - The type for the adapter-specific context or API.
378
+ * @template TR The type of the tracker identifier (e.g., a string enum).
379
+ * @template T The specific transaction type, extending the base `Transaction`.
380
+ * @template A The type of the key returned by the `actionFunction` (e.g., a transaction hash).
360
381
  *
361
- * @param {object} config - Configuration object for creating the store.
362
- * @param {function} [config.onSucceedCallbacks] - Optional async callback executed on transaction success.
363
- * @param {TxAdapter<TR, T, A>[]} config.adapters - An array of adapters for different transaction types or chains.
364
- * @param {PersistOptions<ITxTrackingStore<TR, T, A>>} [options] - Configuration for the Zustand persist middleware.
382
+ * @param config Configuration object for creating the store.
383
+ * @param config.onSucceedCallbacks Optional async callback executed on transaction success.
384
+ * @param config.adapters An array of adapters for different chains or transaction types.
385
+ * @param options Configuration for the Zustand `persist` middleware.
365
386
  * @returns A fully configured Zustand store instance.
366
387
  */
367
388
  declare function createPulsarStore<TR, T extends Transaction<TR>, A>({ onSucceedCallbacks, adapters, ...options }: {
@@ -514,4 +535,4 @@ declare const selectAdapterByKey: <TR, T extends Transaction<TR>, A>({ adapterKe
514
535
  adapters: TxAdapter<TR, T, A>[];
515
536
  }) => TxAdapter<TR, T, A> | undefined;
516
537
 
517
- 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 TxActions, type TxAdapter, createBoundedUseStore, createPulsarStore, initializePollingTracker, initializeTxTrackingStore, selectAdapterByKey, selectAllTransactions, selectAllTransactionsByActiveWallet, selectPendingTransactions, selectPendingTransactionsByActiveWallet, selectTxByKey };
538
+ 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 };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
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 S({onSucceedCallbacks:n}){return (e,o)=>({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,T=>{let c=T.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:()=>o().lastAddedTxKey})}var A=n=>Object.values(n).sort((e,o)=>Number(e.localTimestamp)-Number(o.localTimestamp)),D=n=>A(n).filter(e=>e.pending),U=(n,e)=>n[e],b=(n,e)=>A(n).filter(o=>o.from.toLowerCase()===e.toLowerCase()),$=(n,e)=>b(n,e).filter(o=>o.pending);var R=({adapterKey:n,adapters:e})=>{if(!e||e.length===0){console.error("Adapter selection failed: The provided adapters array is empty.");return}let o=e.find(t=>t.key===n);return o||(console.warn(`No adapter found for key: "${n}". Falling back to the first available adapter: "${e[0].key}".`),e[0])};function Z({onSucceedCallbacks:n,adapters:e,...o}){return vanilla.createStore()(middleware.persist((t,i)=>({...S({onSucceedCallbacks:n})(t,i),initializeTransactionsPool:async()=>{let r=Object.values(i().transactionsPool).filter(T=>T.pending);await Promise.all(r.map(T=>R({adapterKey:T.adapter,adapters:e})?.checkAndInitializeTrackerInStore({tx:T,...i()})));},handleTransaction:async({defaultTracker:r,actionFunction:T,params:c})=>{let{desiredChainID:x,...m}=c,g=w__default.default().unix();t({initialTx:{...c,localTimestamp:g,isInitializing:true}});let l=R({adapterKey:m.adapter,adapters:e});if(!l){let a=new Error("No adapter found for this transaction.");throw d(a),a}try{let{walletType:a,walletAddress:u}=l.getWalletInfo();await l.checkChainForTx(x);let s=await T();if(!s){t({initialTx:void 0});return}let p={...m,walletType:a,from:u,tracker:r,chainId:x,localTimestamp:g,txKey:"",pending:!1,isTrackedModalOpen:c.withTrackedModal},{tracker:k,txKey:P}=l.checkTransactionsTracker(s,p.walletType),h={...p,tracker:k,txKey:P,hash:k==="ethereum"?s:void 0};i().addTxToPool(h),t(K=>immer.produce(K,y=>{y.initialTx&&(y.initialTx.isInitializing=!1,y.initialTx.lastTxKey=P);}));let I=i().transactionsPool[P];await l.checkAndInitializeTrackerInStore({tx:I,...i()});}catch(a){throw d(a),a}function d(a){let u=a instanceof Error?a.message:String(a);t(s=>immer.produce(s,p=>{p.initialTx&&(p.initialTx.isInitializing=false,p.initialTx.errorMessage=u);}));}}}),{...o}))}var z=(t=>(t.EVM="evm",t.SOLANA="solana",t.Starknet="starknet",t))(z||{}),M=(t=>(t.Failed="Failed",t.Success="Success",t.Replaced="Replaced",t))(M||{});var ie=(n=>e=>zustand.useStore(n,e));var C=5e3,O=10;function ae(n){let{tx:e,fetcher:o,onInitialize:t,onSuccess:i,onFailure:r,onIntervalTick:T,onReplaced:c,removeTxFromPool:x,pollingInterval:m=C,maxRetries:g=O}=n;if(!e.pending)return;t?.();let l=g,d=true,a=s=>{d&&(d=false,x&&!s?.withoutRemoving&&x(e.txKey));};(async()=>{for(;d&&l>0;)try{if(await new Promise(s=>setTimeout(s,m)),!d)break;await o({tx:e,stopPolling:a,onSuccess:i,onFailure:r,onIntervalTick:T,onReplaced:c});}catch(s){console.error(`Polling fetcher for txKey ${e.txKey} threw an error:`,s),l--;}l<=0&&(console.warn(`Polling for txKey ${e.txKey} stopped after reaching the maximum number of retries.`),r(),a());})();}exports.TransactionAdapter=z;exports.TransactionStatus=M;exports.createBoundedUseStore=ie;exports.createPulsarStore=Z;exports.initializePollingTracker=ae;exports.initializeTxTrackingStore=S;exports.selectAdapterByKey=R;exports.selectAllTransactions=A;exports.selectAllTransactionsByActiveWallet=b;exports.selectPendingTransactions=D;exports.selectPendingTransactionsByActiveWallet=$;exports.selectTxByKey=U;//# sourceMappingURL=index.js.map
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,adapters:e})=>{if(!e||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])};function Q({onSucceedCallbacks:n,adapters: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,adapters: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,adapters: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
2
2
  //# sourceMappingURL=index.js.map