@tuwaio/pulsar-core 0.4.0 → 0.5.0

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/README.md CHANGED
@@ -33,14 +33,8 @@ This package exports one primary factory function: `createPulsarStore`.
33
33
  This package requires `zustand`, `immer` and `dayjs` as peer dependencies. You must install them alongside `@tuwaio/pulsar-core`.
34
34
 
35
35
  ```bash
36
- # Using pnpm
36
+ # Using pnpm (recommended), but you can use npm, yarn or bun as well
37
37
  pnpm add @tuwaio/pulsar-core @tuwaio/orbit-core zustand immer dayjs
38
-
39
- # Using npm
40
- npm install @tuwaio/pulsar-core @tuwaio/orbit-core zustand immer dayjs
41
-
42
- # Using yarn
43
- yarn add @tuwaio/pulsar-core @tuwaio/orbit-core zustand immer dayjs
44
38
  ```
45
39
 
46
40
  ---
@@ -55,7 +49,7 @@ This is the main factory function that creates your transaction store. It takes
55
49
 
56
50
  ```ts
57
51
  import { createBoundedUseStore, createPulsarStore, Transaction } from '@tuwaio/pulsar-core';
58
- import { evmAdapter } from '@tuwaio/pulsar-evm';
52
+ import { pulsarEvmAdapter } from '@tuwaio/pulsar-evm';
59
53
 
60
54
  import { appChains, config } from '@/configs/wagmiConfig';
61
55
 
@@ -77,11 +71,19 @@ export type TransactionUnion = ExampleTx;
77
71
  export const usePulsarStore = createBoundedUseStore(
78
72
  createPulsarStore<TransactionUnion>({
79
73
  name: storageName,
80
- adapter: evmAdapter(config, appChains),
74
+ adapter: pulsarEvmAdapter(config, appChains),
75
+ maxTransactions: 100, // Optional: defaults to 50
81
76
  }),
82
77
  );
83
78
  ```
84
79
 
80
+ ### Transaction Pool Management (FIFO)
81
+
82
+ To prevent the `localStorage` from growing indefinitely, Pulsar Core implements a **FIFO (First-In, First-Out) Eviction Policy**.
83
+
84
+ - **Maximum Transactions:** By default, the store keeps the last **50** transactions. You can customize this via the `maxTransactions` property in the `createPulsarStore` config.
85
+ - **Eviction Process:** When the pool exceeds the `maxTransactions` limit, the oldest transaction (based on `localTimestamp`) is automatically removed from the state and storage when a new one is added.
86
+
85
87
  ### The Returned Store API
86
88
 
87
89
  The `createPulsarStore` function returns a vanilla Zustand store with the following state and actions:
@@ -100,6 +102,38 @@ The `createPulsarStore` function returns a vanilla Zustand store with the follow
100
102
  - `updateTxParams(txKey, fields)`: Updates one or more properties of an existing transaction in the pool.
101
103
  - `removeTxFromPool(txKey)`: Removes a transaction from the pool by its key.
102
104
  - `closeTxTrackedModal(txKey?)`: A helper to manage UI state, which sets `isTrackedModalOpen` to `false` and clears the `initialTx` state.
105
+ - `getLastTxKey()`: Returns the `txKey` of the most recently added transaction.
106
+
107
+ #### **Selectors**
108
+
109
+ The package also provides a set of selector functions to help you efficiently query the transaction pool:
110
+
111
+ - `selectAllTransactions(pool)`: Returns all transactions sorted chronologically.
112
+ - `selectPendingTransactions(pool)`: Returns only transactions that are currently pending.
113
+ - `selectTxByKey(pool, txKey)`: Retrieves a specific transaction by its key.
114
+ - `selectAllTransactionsByActiveWallet(pool, address)`: Returns all transactions for a specific wallet.
115
+ - `selectPendingTransactionsByActiveWallet(pool, address)`: Returns pending transactions for a specific wallet.
116
+
117
+ ---
118
+
119
+ ## 🛠️ Advanced Usage: `initializePollingTracker`
120
+
121
+ For custom tracking requirements (like server-side tracking or non-standard APIs), you can use the low-level `initializePollingTracker` utility. This is the same engine used internally by Pulsar adapters for Gelato, Safe, and Solana.
122
+
123
+ ```ts
124
+ import { initializePollingTracker } from '@tuwaio/pulsar-core';
125
+
126
+ await initializePollingTracker({
127
+ tx: myTransaction,
128
+ fetcher: async ({ stopPolling, onSuccess, onFailure }) => {
129
+ const status = await checkMyCustomApi(myTransaction.txKey);
130
+ if (status === 'done') onSuccess(status);
131
+ if (status === 'error') onFailure(status);
132
+ },
133
+ onSuccess: (status) => console.log('Success!', status),
134
+ onFailure: (status) => console.error('Failed!', status),
135
+ });
136
+ ```
103
137
 
104
138
  ---
105
139
 
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { OrbitAdapter, BaseAdapter, OrbitGenericAdapter } from '@tuwaio/orbit-core';
1
+ import { TuwaErrorState, OrbitAdapter, BaseAdapter, OrbitGenericAdapter } from '@tuwaio/orbit-core';
2
2
  import * as zustand from 'zustand';
3
3
  import { StoreApi } from 'zustand';
4
4
  import { PersistOptions } from 'zustand/middleware';
@@ -70,8 +70,8 @@ type BaseTransaction = {
70
70
  * description: ['Swapping...', 'Swapped Successfully', 'Swap Failed', 'Swap Replaced']
71
71
  */
72
72
  description?: string | [string, string, string, string];
73
- /** The error message if the transaction failed. */
74
- errorMessage?: string;
73
+ /** The error state if the transaction failed, containing message and raw error details. */
74
+ error?: TuwaErrorState;
75
75
  /** The on-chain timestamp (in seconds) when the transaction was finalized. */
76
76
  finishedTimestamp?: number;
77
77
  /** The sender's wallet address. */
@@ -192,8 +192,8 @@ type InitialTransactionParams = {
192
192
  * This is used for UI feedback while the transaction is being signed and sent.
193
193
  */
194
194
  type InitialTransaction = InitialTransactionParams & {
195
- /** An error message if the initialization fails (e.g., user rejects signature). */
196
- errorMessage?: string;
195
+ /** Normalized error if the initialization fails (e.g., user rejects signature). */
196
+ error?: TuwaErrorState;
197
197
  /** A flag indicating if the transaction is being processed (e.g., waiting for signature). */
198
198
  isInitializing: boolean;
199
199
  /** The `txKey` of the on-chain transaction that this action produced, used for linking the states. */
@@ -307,7 +307,7 @@ type TransactionPool<T extends Transaction> = Record<string, T>;
307
307
  * on a transaction object via the `updateTxParams` action. This ensures type safety
308
308
  * and prevents accidental modification of immutable properties.
309
309
  */
310
- 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'>>;
310
+ type UpdatableTransactionFields = Partial<Pick<EvmTransaction, 'to' | 'nonce' | 'txKey' | 'pending' | 'hash' | 'status' | 'replacedTxHash' | 'error' | 'finishedTimestamp' | 'isTrackedModalOpen' | 'isError' | 'maxPriorityFeePerGas' | 'maxFeePerGas' | 'input' | 'value'>> & Partial<Pick<SolanaTransaction, 'slot' | 'confirmations' | 'fee' | 'instructions' | 'recentBlockhash' | 'rpcUrl'>>;
311
311
  /**
312
312
  * The interface for the base transaction tracking store slice.
313
313
  * It includes the state and actions for managing the transaction lifecycle.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { OrbitAdapter, BaseAdapter, OrbitGenericAdapter } from '@tuwaio/orbit-core';
1
+ import { TuwaErrorState, OrbitAdapter, BaseAdapter, OrbitGenericAdapter } from '@tuwaio/orbit-core';
2
2
  import * as zustand from 'zustand';
3
3
  import { StoreApi } from 'zustand';
4
4
  import { PersistOptions } from 'zustand/middleware';
@@ -70,8 +70,8 @@ type BaseTransaction = {
70
70
  * description: ['Swapping...', 'Swapped Successfully', 'Swap Failed', 'Swap Replaced']
71
71
  */
72
72
  description?: string | [string, string, string, string];
73
- /** The error message if the transaction failed. */
74
- errorMessage?: string;
73
+ /** The error state if the transaction failed, containing message and raw error details. */
74
+ error?: TuwaErrorState;
75
75
  /** The on-chain timestamp (in seconds) when the transaction was finalized. */
76
76
  finishedTimestamp?: number;
77
77
  /** The sender's wallet address. */
@@ -192,8 +192,8 @@ type InitialTransactionParams = {
192
192
  * This is used for UI feedback while the transaction is being signed and sent.
193
193
  */
194
194
  type InitialTransaction = InitialTransactionParams & {
195
- /** An error message if the initialization fails (e.g., user rejects signature). */
196
- errorMessage?: string;
195
+ /** Normalized error if the initialization fails (e.g., user rejects signature). */
196
+ error?: TuwaErrorState;
197
197
  /** A flag indicating if the transaction is being processed (e.g., waiting for signature). */
198
198
  isInitializing: boolean;
199
199
  /** The `txKey` of the on-chain transaction that this action produced, used for linking the states. */
@@ -307,7 +307,7 @@ type TransactionPool<T extends Transaction> = Record<string, T>;
307
307
  * on a transaction object via the `updateTxParams` action. This ensures type safety
308
308
  * and prevents accidental modification of immutable properties.
309
309
  */
310
- 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'>>;
310
+ type UpdatableTransactionFields = Partial<Pick<EvmTransaction, 'to' | 'nonce' | 'txKey' | 'pending' | 'hash' | 'status' | 'replacedTxHash' | 'error' | 'finishedTimestamp' | 'isTrackedModalOpen' | 'isError' | 'maxPriorityFeePerGas' | 'maxFeePerGas' | 'input' | 'value'>> & Partial<Pick<SolanaTransaction, 'slot' | 'confirmations' | 'fee' | 'instructions' | 'recentBlockhash' | 'rpcUrl'>>;
311
311
  /**
312
312
  * The interface for the base transaction tracking store slice.
313
313
  * It includes the state and actions for managing the transaction lifecycle.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var immer=require('immer'),orbitCore=require('@tuwaio/orbit-core'),C=require('dayjs'),middleware=require('zustand/middleware'),vanilla=require('zustand/vanilla'),zustand=require('zustand');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var C__default=/*#__PURE__*/_interopDefault(C);function h({maxTransactions:o}){return (t,s)=>({transactionsPool:{},lastAddedTxKey:void 0,initialTx:void 0,addTxToPool:e=>{t(n=>immer.produce(n,r=>{if(r.lastAddedTxKey=e.txKey,e.txKey){if(Object.keys(r.transactionsPool).length>=o){let d=Object.values(r.transactionsPool).sort((l,p)=>l.localTimestamp-p.localTimestamp);if(d.length>0){let l=d[0];delete r.transactionsPool[l.txKey];}}let c={...e,pending:true};r.transactionsPool[e.txKey]=c;}}));},updateTxParams:(e,n)=>{t(r=>immer.produce(r,i=>{let c=i.transactionsPool[e];c&&Object.assign(c,n);}));},removeTxFromPool:e=>{t(n=>immer.produce(n,r=>{delete r.transactionsPool[e];}));},closeTxTrackedModal:e=>{t(n=>immer.produce(n,r=>{if(e&&r.transactionsPool[e]){let i=r.transactionsPool[e];r.transactionsPool[e]={...i,isTrackedModalOpen:false};}r.initialTx=void 0;}));},getLastTxKey:()=>s().lastAddedTxKey})}var b=o=>Object.values(o).sort((t,s)=>Number(t.localTimestamp)-Number(s.localTimestamp)),D=o=>b(o).filter(t=>t.pending),_=(o,t)=>o[t],O=(o,t)=>b(o).filter(s=>s.from.toLowerCase()===t.toLowerCase()),H=(o,t)=>O(o,t).filter(s=>s.pending);function ee({adapter:o,maxTransactions:t=50,...s}){return vanilla.createStore()(middleware.persist((e,n)=>({...h({maxTransactions:t})(e,n),getAdapter:()=>o,initializeTransactionsPool:async()=>{let r=Object.values(n().transactionsPool).filter(i=>i.pending);await Promise.all(r.map(i=>orbitCore.selectAdapterByKey({adapterKey:i.adapter,adapter:o})?.checkAndInitializeTrackerInStore({tx:i,...n()})));},executeTxAction:async({defaultTracker:r,actionFunction:i,params:c,...d})=>{let{desiredChainID:l,...p}=c,{onSuccess:g,onError:x,onReplaced:P}=d,f=C__default.default().unix();e({initialTx:{...c,actionFunction:i,localTimestamp:f,isInitializing:true}});let T=orbitCore.selectAdapterByKey({adapterKey:p.adapter,adapter:o}),v=a=>{let k=a instanceof Error?a.message:String(a);e(u=>immer.produce(u,m=>{m.initialTx&&(m.initialTx.isInitializing=false,m.initialTx.errorMessage=k);}));};if(!T){let a=new Error("No adapter found for this transaction.");throw v(a),a}try{let{connectorType:a,walletAddress:k}=T.getConnectorInfo();await T.checkChainForTx(l);let u=await i();if(!u){e({initialTx:void 0});return}let{tracker:m,txKey:S}=T.checkTransactionsTracker(u,a),w={...p,connectorType:a,from:k,tracker:m||r,chainId:orbitCore.setChainId(l),localTimestamp:f,txKey:S,hash:m==="ethereum"?u:void 0,pending:!1,isTrackedModalOpen:c.withTrackedModal};n().addTxToPool(w),e(F=>immer.produce(F,A=>{A.initialTx&&(A.initialTx.isInitializing=!1,A.initialTx.lastTxKey=S);}));let R=n().transactionsPool[S];await T.checkAndInitializeTrackerInStore({tx:R,onSuccess:g,onError:x,onReplaced:P,...n()});}catch(a){throw v(a),a}}}),{...s}))}var B=(n=>(n.Ethereum="ethereum",n.Safe="safe",n.Gelato="gelato",n.Solana="solana",n))(B||{}),L=(e=>(e.Failed="Failed",e.Success="Success",e.Replaced="Replaced",e))(L||{});var ie=(o=>t=>zustand.useStore(o,t));var j=5e3,G=10;function se(o){let{tx:t,fetcher:s,onInitialize:e,onSuccess:n,onFailure:r,onIntervalTick:i,onReplaced:c,removeTxFromPool:d,pollingInterval:l=j,maxRetries:p=G}=o;if(!t.pending)return;e?.();let g=p,x=true,P=T=>{x&&(x=false,d&&!T?.withoutRemoving&&d(t.txKey));};(async()=>{for(;x&&g>0;)try{if(await new Promise(T=>setTimeout(T,l)),!x)break;await s({tx:t,stopPolling:P,onSuccess:n,onFailure:r,onIntervalTick:i,onReplaced:c});}catch(T){console.error(`Polling fetcher for txKey ${t.txKey} threw an error:`,T),g--;}g<=0&&(console.warn(`Polling for txKey ${t.txKey} stopped after reaching the maximum number of retries.`),r(),P());})();}exports.TransactionStatus=L;exports.TransactionTracker=B;exports.createBoundedUseStore=ie;exports.createPulsarStore=ee;exports.initializePollingTracker=se;exports.initializeTxTrackingStore=h;exports.selectAllTransactions=b;exports.selectAllTransactionsByActiveWallet=O;exports.selectPendingTransactions=D;exports.selectPendingTransactionsByActiveWallet=H;exports.selectTxByKey=_;
1
+ 'use strict';var immer=require('immer'),orbitCore=require('@tuwaio/orbit-core'),C=require('dayjs'),middleware=require('zustand/middleware'),vanilla=require('zustand/vanilla'),zustand=require('zustand');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var C__default=/*#__PURE__*/_interopDefault(C);function h({maxTransactions:o}){return (t,a)=>({transactionsPool:{},lastAddedTxKey:void 0,initialTx:void 0,addTxToPool:e=>{t(r=>immer.produce(r,n=>{if(n.lastAddedTxKey=e.txKey,e.txKey){if(Object.keys(n.transactionsPool).length>=o){let d=Object.values(n.transactionsPool).sort((l,x)=>l.localTimestamp-x.localTimestamp);if(d.length>0){let l=d[0];delete n.transactionsPool[l.txKey];}}let s={...e,pending:true};n.transactionsPool[e.txKey]=s;}}));},updateTxParams:(e,r)=>{t(n=>immer.produce(n,i=>{let s=i.transactionsPool[e];s&&Object.assign(s,r);}));},removeTxFromPool:e=>{t(r=>immer.produce(r,n=>{delete n.transactionsPool[e];}));},closeTxTrackedModal:e=>{t(r=>immer.produce(r,n=>{if(e&&n.transactionsPool[e]){let i=n.transactionsPool[e];n.transactionsPool[e]={...i,isTrackedModalOpen:false};}n.initialTx=void 0;}));},getLastTxKey:()=>a().lastAddedTxKey})}var b=o=>Object.values(o).sort((t,a)=>Number(t.localTimestamp)-Number(a.localTimestamp)),_=o=>b(o).filter(t=>t.pending),H=(o,t)=>o[t],E=(o,t)=>b(o).filter(a=>a.from.toLowerCase()===t.toLowerCase()),V=(o,t)=>E(o,t).filter(a=>a.pending);function te({adapter:o,maxTransactions:t=50,...a}){return vanilla.createStore()(middleware.persist((e,r)=>({...h({maxTransactions:t})(e,r),getAdapter:()=>o,initializeTransactionsPool:async()=>{let n=Object.values(r().transactionsPool).filter(i=>i.pending);await Promise.all(n.map(i=>orbitCore.selectAdapterByKey({adapterKey:i.adapter,adapter:o})?.checkAndInitializeTrackerInStore({tx:i,...r()})));},executeTxAction:async({defaultTracker:n,actionFunction:i,params:s,...d})=>{let{desiredChainID:l,...x}=s,{onSuccess:g,onError:m,onReplaced:u}=d,y=C__default.default().unix();e({initialTx:{...s,actionFunction:i,localTimestamp:y,isInitializing:true}});let c=orbitCore.selectAdapterByKey({adapterKey:x.adapter,adapter:o}),A=T=>{e(f=>immer.produce(f,p=>{p.initialTx&&(p.initialTx.isInitializing=false,p.initialTx.error=orbitCore.normalizeError(T));}));};if(!c){let T=new Error("No adapter found for this transaction.");throw A(T),T}try{let{connectorType:T,walletAddress:f}=c.getConnectorInfo();await c.checkChainForTx(l);let p=await i();if(!p){e({initialTx:void 0});return}let{tracker:v,txKey:k}=c.checkTransactionsTracker(p,T),w={...x,connectorType:T,from:f,tracker:v||n,chainId:orbitCore.setChainId(l),localTimestamp:y,txKey:k,hash:v==="ethereum"?p:void 0,pending:!1,isTrackedModalOpen:s.withTrackedModal};r().addTxToPool(w),e(F=>immer.produce(F,S=>{S.initialTx&&(S.initialTx.isInitializing=!1,S.initialTx.lastTxKey=k);}));let R=r().transactionsPool[k];await c.checkAndInitializeTrackerInStore({tx:R,onSuccess:g,onError:m,onReplaced:u,...r()});}catch(T){throw A(T),T}}}),{...a}))}var U=(r=>(r.Ethereum="ethereum",r.Safe="safe",r.Gelato="gelato",r.Solana="solana",r))(U||{}),j=(e=>(e.Failed="Failed",e.Success="Success",e.Replaced="Replaced",e))(j||{});var ae=(o=>t=>zustand.useStore(o,t));var M=5e3,$=10;function ce(o){let{tx:t,fetcher:a,onInitialize:e,onSuccess:r,onFailure:n,onIntervalTick:i,onReplaced:s,removeTxFromPool:d,pollingInterval:l=M,maxRetries:x=$}=o;if(!t.pending)return;e?.();let g=x,m=true,u=c=>{m&&(m=false,d&&!c?.withoutRemoving&&d(t.txKey));};(async()=>{for(;m&&g>0;)try{if(await new Promise(c=>setTimeout(c,l)),!m)break;await a({tx:t,stopPolling:u,onSuccess:r,onFailure:n,onIntervalTick:i,onReplaced:s});}catch(c){console.error(`Polling fetcher for txKey ${t.txKey} threw an error:`,c),g--;}g<=0&&(console.warn(`Polling for txKey ${t.txKey} stopped after reaching the maximum number of retries.`),n(),u());})();}exports.TransactionStatus=j;exports.TransactionTracker=U;exports.createBoundedUseStore=ae;exports.createPulsarStore=te;exports.initializePollingTracker=ce;exports.initializeTxTrackingStore=h;exports.selectAllTransactions=b;exports.selectAllTransactionsByActiveWallet=E;exports.selectPendingTransactions=_;exports.selectPendingTransactionsByActiveWallet=V;exports.selectTxByKey=H;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import {produce}from'immer';import {selectAdapterByKey,setChainId}from'@tuwaio/orbit-core';import C from'dayjs';import {persist}from'zustand/middleware';import {createStore}from'zustand/vanilla';import {useStore}from'zustand';function h({maxTransactions:o}){return (t,s)=>({transactionsPool:{},lastAddedTxKey:void 0,initialTx:void 0,addTxToPool:e=>{t(n=>produce(n,r=>{if(r.lastAddedTxKey=e.txKey,e.txKey){if(Object.keys(r.transactionsPool).length>=o){let d=Object.values(r.transactionsPool).sort((l,p)=>l.localTimestamp-p.localTimestamp);if(d.length>0){let l=d[0];delete r.transactionsPool[l.txKey];}}let c={...e,pending:true};r.transactionsPool[e.txKey]=c;}}));},updateTxParams:(e,n)=>{t(r=>produce(r,i=>{let c=i.transactionsPool[e];c&&Object.assign(c,n);}));},removeTxFromPool:e=>{t(n=>produce(n,r=>{delete r.transactionsPool[e];}));},closeTxTrackedModal:e=>{t(n=>produce(n,r=>{if(e&&r.transactionsPool[e]){let i=r.transactionsPool[e];r.transactionsPool[e]={...i,isTrackedModalOpen:false};}r.initialTx=void 0;}));},getLastTxKey:()=>s().lastAddedTxKey})}var b=o=>Object.values(o).sort((t,s)=>Number(t.localTimestamp)-Number(s.localTimestamp)),D=o=>b(o).filter(t=>t.pending),_=(o,t)=>o[t],O=(o,t)=>b(o).filter(s=>s.from.toLowerCase()===t.toLowerCase()),H=(o,t)=>O(o,t).filter(s=>s.pending);function ee({adapter:o,maxTransactions:t=50,...s}){return createStore()(persist((e,n)=>({...h({maxTransactions:t})(e,n),getAdapter:()=>o,initializeTransactionsPool:async()=>{let r=Object.values(n().transactionsPool).filter(i=>i.pending);await Promise.all(r.map(i=>selectAdapterByKey({adapterKey:i.adapter,adapter:o})?.checkAndInitializeTrackerInStore({tx:i,...n()})));},executeTxAction:async({defaultTracker:r,actionFunction:i,params:c,...d})=>{let{desiredChainID:l,...p}=c,{onSuccess:g,onError:x,onReplaced:P}=d,f=C().unix();e({initialTx:{...c,actionFunction:i,localTimestamp:f,isInitializing:true}});let T=selectAdapterByKey({adapterKey:p.adapter,adapter:o}),v=a=>{let k=a instanceof Error?a.message:String(a);e(u=>produce(u,m=>{m.initialTx&&(m.initialTx.isInitializing=false,m.initialTx.errorMessage=k);}));};if(!T){let a=new Error("No adapter found for this transaction.");throw v(a),a}try{let{connectorType:a,walletAddress:k}=T.getConnectorInfo();await T.checkChainForTx(l);let u=await i();if(!u){e({initialTx:void 0});return}let{tracker:m,txKey:S}=T.checkTransactionsTracker(u,a),w={...p,connectorType:a,from:k,tracker:m||r,chainId:setChainId(l),localTimestamp:f,txKey:S,hash:m==="ethereum"?u:void 0,pending:!1,isTrackedModalOpen:c.withTrackedModal};n().addTxToPool(w),e(F=>produce(F,A=>{A.initialTx&&(A.initialTx.isInitializing=!1,A.initialTx.lastTxKey=S);}));let R=n().transactionsPool[S];await T.checkAndInitializeTrackerInStore({tx:R,onSuccess:g,onError:x,onReplaced:P,...n()});}catch(a){throw v(a),a}}}),{...s}))}var B=(n=>(n.Ethereum="ethereum",n.Safe="safe",n.Gelato="gelato",n.Solana="solana",n))(B||{}),L=(e=>(e.Failed="Failed",e.Success="Success",e.Replaced="Replaced",e))(L||{});var ie=(o=>t=>useStore(o,t));var j=5e3,G=10;function se(o){let{tx:t,fetcher:s,onInitialize:e,onSuccess:n,onFailure:r,onIntervalTick:i,onReplaced:c,removeTxFromPool:d,pollingInterval:l=j,maxRetries:p=G}=o;if(!t.pending)return;e?.();let g=p,x=true,P=T=>{x&&(x=false,d&&!T?.withoutRemoving&&d(t.txKey));};(async()=>{for(;x&&g>0;)try{if(await new Promise(T=>setTimeout(T,l)),!x)break;await s({tx:t,stopPolling:P,onSuccess:n,onFailure:r,onIntervalTick:i,onReplaced:c});}catch(T){console.error(`Polling fetcher for txKey ${t.txKey} threw an error:`,T),g--;}g<=0&&(console.warn(`Polling for txKey ${t.txKey} stopped after reaching the maximum number of retries.`),r(),P());})();}export{L as TransactionStatus,B as TransactionTracker,ie as createBoundedUseStore,ee as createPulsarStore,se as initializePollingTracker,h as initializeTxTrackingStore,b as selectAllTransactions,O as selectAllTransactionsByActiveWallet,D as selectPendingTransactions,H as selectPendingTransactionsByActiveWallet,_ as selectTxByKey};
1
+ import {produce}from'immer';import {selectAdapterByKey,setChainId,normalizeError}from'@tuwaio/orbit-core';import C from'dayjs';import {persist}from'zustand/middleware';import {createStore}from'zustand/vanilla';import {useStore}from'zustand';function h({maxTransactions:o}){return (t,a)=>({transactionsPool:{},lastAddedTxKey:void 0,initialTx:void 0,addTxToPool:e=>{t(r=>produce(r,n=>{if(n.lastAddedTxKey=e.txKey,e.txKey){if(Object.keys(n.transactionsPool).length>=o){let d=Object.values(n.transactionsPool).sort((l,x)=>l.localTimestamp-x.localTimestamp);if(d.length>0){let l=d[0];delete n.transactionsPool[l.txKey];}}let s={...e,pending:true};n.transactionsPool[e.txKey]=s;}}));},updateTxParams:(e,r)=>{t(n=>produce(n,i=>{let s=i.transactionsPool[e];s&&Object.assign(s,r);}));},removeTxFromPool:e=>{t(r=>produce(r,n=>{delete n.transactionsPool[e];}));},closeTxTrackedModal:e=>{t(r=>produce(r,n=>{if(e&&n.transactionsPool[e]){let i=n.transactionsPool[e];n.transactionsPool[e]={...i,isTrackedModalOpen:false};}n.initialTx=void 0;}));},getLastTxKey:()=>a().lastAddedTxKey})}var b=o=>Object.values(o).sort((t,a)=>Number(t.localTimestamp)-Number(a.localTimestamp)),_=o=>b(o).filter(t=>t.pending),H=(o,t)=>o[t],E=(o,t)=>b(o).filter(a=>a.from.toLowerCase()===t.toLowerCase()),V=(o,t)=>E(o,t).filter(a=>a.pending);function te({adapter:o,maxTransactions:t=50,...a}){return createStore()(persist((e,r)=>({...h({maxTransactions:t})(e,r),getAdapter:()=>o,initializeTransactionsPool:async()=>{let n=Object.values(r().transactionsPool).filter(i=>i.pending);await Promise.all(n.map(i=>selectAdapterByKey({adapterKey:i.adapter,adapter:o})?.checkAndInitializeTrackerInStore({tx:i,...r()})));},executeTxAction:async({defaultTracker:n,actionFunction:i,params:s,...d})=>{let{desiredChainID:l,...x}=s,{onSuccess:g,onError:m,onReplaced:u}=d,y=C().unix();e({initialTx:{...s,actionFunction:i,localTimestamp:y,isInitializing:true}});let c=selectAdapterByKey({adapterKey:x.adapter,adapter:o}),A=T=>{e(f=>produce(f,p=>{p.initialTx&&(p.initialTx.isInitializing=false,p.initialTx.error=normalizeError(T));}));};if(!c){let T=new Error("No adapter found for this transaction.");throw A(T),T}try{let{connectorType:T,walletAddress:f}=c.getConnectorInfo();await c.checkChainForTx(l);let p=await i();if(!p){e({initialTx:void 0});return}let{tracker:v,txKey:k}=c.checkTransactionsTracker(p,T),w={...x,connectorType:T,from:f,tracker:v||n,chainId:setChainId(l),localTimestamp:y,txKey:k,hash:v==="ethereum"?p:void 0,pending:!1,isTrackedModalOpen:s.withTrackedModal};r().addTxToPool(w),e(F=>produce(F,S=>{S.initialTx&&(S.initialTx.isInitializing=!1,S.initialTx.lastTxKey=k);}));let R=r().transactionsPool[k];await c.checkAndInitializeTrackerInStore({tx:R,onSuccess:g,onError:m,onReplaced:u,...r()});}catch(T){throw A(T),T}}}),{...a}))}var U=(r=>(r.Ethereum="ethereum",r.Safe="safe",r.Gelato="gelato",r.Solana="solana",r))(U||{}),j=(e=>(e.Failed="Failed",e.Success="Success",e.Replaced="Replaced",e))(j||{});var ae=(o=>t=>useStore(o,t));var M=5e3,$=10;function ce(o){let{tx:t,fetcher:a,onInitialize:e,onSuccess:r,onFailure:n,onIntervalTick:i,onReplaced:s,removeTxFromPool:d,pollingInterval:l=M,maxRetries:x=$}=o;if(!t.pending)return;e?.();let g=x,m=true,u=c=>{m&&(m=false,d&&!c?.withoutRemoving&&d(t.txKey));};(async()=>{for(;m&&g>0;)try{if(await new Promise(c=>setTimeout(c,l)),!m)break;await a({tx:t,stopPolling:u,onSuccess:r,onFailure:n,onIntervalTick:i,onReplaced:s});}catch(c){console.error(`Polling fetcher for txKey ${t.txKey} threw an error:`,c),g--;}g<=0&&(console.warn(`Polling for txKey ${t.txKey} stopped after reaching the maximum number of retries.`),n(),u());})();}export{j as TransactionStatus,U as TransactionTracker,ae as createBoundedUseStore,te as createPulsarStore,ce as initializePollingTracker,h as initializeTxTrackingStore,b as selectAllTransactions,E as selectAllTransactionsByActiveWallet,_ as selectPendingTransactions,V as selectPendingTransactionsByActiveWallet,H as selectTxByKey};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuwaio/pulsar-core",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",
@@ -40,18 +40,18 @@
40
40
  }
41
41
  ],
42
42
  "peerDependencies": {
43
- "@tuwaio/orbit-core": ">=0.2",
43
+ "@tuwaio/orbit-core": ">=0.2.7",
44
44
  "dayjs": "1.x.x",
45
45
  "immer": "11.x.x",
46
46
  "zustand": "5.x.x"
47
47
  },
48
48
  "devDependencies": {
49
- "@tuwaio/orbit-core": "^0.2.4",
49
+ "@tuwaio/orbit-core": "^0.2.7",
50
50
  "dayjs": "^1.11.19",
51
51
  "immer": "^11.1.3",
52
52
  "tsup": "^8.5.1",
53
53
  "typescript": "^5.9.3",
54
- "zustand": "^5.0.10"
54
+ "zustand": "^5.0.11"
55
55
  },
56
56
  "scripts": {
57
57
  "start": "tsup src/index.ts --watch",