@tuwaio/pulsar-evm 0.2.3 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -2
- package/dist/index.mjs +1 -2
- package/package.json +7 -7
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
1
|
'use strict';var orbitCore=require('@tuwaio/orbit-core'),orbitEvm=require('@tuwaio/orbit-evm'),pulsarCore=require('@tuwaio/pulsar-core'),core=require('@wagmi/core'),viem=require('viem'),actions=require('viem/actions'),m=require('dayjs'),chains=require('viem/chains');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var m__default=/*#__PURE__*/_interopDefault(m);var v=1.15;async function C({config:t,tx:e}){if(e.adapter!==orbitCore.OrbitAdapter.EVM)throw new Error(`Cancellation is only available for EVM transactions. Received adapter type: '${e.adapter}'.`);let{nonce:r,maxFeePerGas:o,maxPriorityFeePerGas:s,chainId:a}=e;if(r===void 0||!o||!s)throw new Error("Transaction is missing required fields for cancellation (nonce, maxFeePerGas, maxPriorityFeePerGas).");try{if(!t)throw new Error("Wagmi config is not provided.");let n=core.getAccount(t);if(!n.address)throw new Error("No connected account found.");let i=BigInt(Math.ceil(Number(s)*v)),c=BigInt(Math.ceil(Number(o)*v));return await core.sendTransaction(t,{to:n.address,value:0n,chainId:a,nonce:r,maxFeePerGas:c,maxPriorityFeePerGas:i})}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`Failed to cancel transaction: ${i}`)}}var de=10,ue=3e3;async function me(t){let{tx:e,config:r,onInitialize:o,onTxDetailsFetched:s,onSuccess:a,onFailure:n,onReplaced:i,retryCount:c=de,retryTimeout:p=ue,waitForTransactionReceiptParams:d}=t;if(o?.(),e.txKey===viem.zeroHash)return n(new Error("Transaction hash cannot be the zero hash."));let l=core.getClient(r,{chainId:e.chainId});if(!l)return n(new Error(`Could not create a viem client for chainId: ${e.chainId}`));let f=null;for(let u=0;u<c;u++)try{f=await actions.getTransaction(l,{hash:e.txKey}),s(f);break}catch(T){if(u===c-1)return console.error(`EVM tracker failed to fetch tx ${e.txKey} after ${c} retries:`,T),n(T);await new Promise(b=>setTimeout(b,p));}if(!f)return n(new Error("Transaction details could not be fetched."));try{let u=!1,T=await actions.waitForTransactionReceipt(l,{hash:f.hash,onReplaced:b=>{u=!0,i(b);},...d});if(u)return;await a(f,T,l);}catch(u){console.error(`Error waiting for receipt for tx ${e.txKey}:`,u),n(u);}}async function y(t){let{tx:e,config:r,updateTxParams:o,transactionsPool:s,onSuccessCallback:a}=t;return me({tx:e,config:r,onInitialize:()=>{o(e.txKey,{hash:e.txKey});},onTxDetailsFetched:n=>{o(e.txKey,{to:n.to??void 0,input:n.input,value:n.value?.toString(),nonce:n.nonce,maxFeePerGas:n.maxFeePerGas?.toString(),maxPriorityFeePerGas:n.maxPriorityFeePerGas?.toString()});},onSuccess:async(n,i,c)=>{let p=await actions.getBlock(c,{blockNumber:i.blockNumber}),d=Number(p.timestamp),l=i.status==="success";o(e.txKey,{status:l?pulsarCore.TransactionStatus.Success:pulsarCore.TransactionStatus.Failed,isError:!l,pending:false,finishedTimestamp:d});let f=s[e.txKey];l&&a&&f&&a(f);},onReplaced:n=>{o(e.txKey,{status:pulsarCore.TransactionStatus.Replaced,replacedTxHash:n.transaction.hash,pending:false});},onFailure:n=>{o(e.txKey,{status:pulsarCore.TransactionStatus.Failed,pending:false,isError:true,errorMessage:n instanceof Error?n.message:"Transaction failed or could not be tracked."});}})}function R(t){return typeof t=="object"&&t!==null&&"taskId"in t}var he=(i=>(i.CheckPending="CheckPending",i.ExecPending="ExecPending",i.WaitingForConfirmation="WaitingForConfirmation",i.ExecSuccess="ExecSuccess",i.ExecReverted="ExecReverted",i.Cancelled="Cancelled",i.NotFound="NotFound",i))(he||{}),xe="https://api.gelato.digital/tasks/status/",F=new Set(["ExecReverted","Cancelled","NotFound"]);function ge(t){return t!=="ExecSuccess"&&!F.has(t)}var ke=async({tx:t,stopPolling:e,onSuccess:r,onFailure:o,onIntervalTick:s})=>{let a=await fetch(`${xe}${t.txKey}`);if(!a.ok){if(a.status===404){o(),e();return}throw new Error(`Gelato API responded with status: ${a.status}`)}let n=await a.json(),{taskState:i,creationDate:c}=n.task;if(s?.(n),c&&m__default.default().diff(m__default.default(c),"hour")>=1&&ge(i)){e();return}i==="ExecSuccess"?(r(n),e({withoutRemoving:true})):F.has(i)&&(o(n),e({withoutRemoving:true}));};function I({tx:t,updateTxParams:e,removeTxFromPool:r,transactionsPool:o,onSuccessCallback:s}){return pulsarCore.initializePollingTracker({tx:t,fetcher:ke,removeTxFromPool:r,onSuccess:a=>{e(t.txKey,{status:pulsarCore.TransactionStatus.Success,pending:false,isError:false,hash:a.task.transactionHash,finishedTimestamp:a.task.executionDate?m__default.default(a.task.executionDate).unix():void 0});let n=o[t.txKey];s&&n&&s(n);},onIntervalTick:a=>{e(t.txKey,{hash:a.task.transactionHash});},onFailure:a=>{e(t.txKey,{status:pulsarCore.TransactionStatus.Failed,pending:false,isError:true,hash:a?.task.transactionHash,errorMessage:a?.task.lastCheckMessage??"Transaction failed or was not found.",finishedTimestamp:a?.task.executionDate?m__default.default(a.task.executionDate).unix():void 0});}})}var ft={allowedDomains:[/gnosis-safe.io$/,/app.safe.global$/,/metissafe.tech$/],debug:false},B={[chains.mainnet.id]:"https://app.safe.global/eth:",[chains.goerli.id]:"https://app.safe.global/gor:",[chains.sepolia.id]:"https://app.safe.global/sep:",[chains.polygon.id]:"https://app.safe.global/matic:",[chains.arbitrum.id]:"https://app.safe.global/arb1:",[chains.aurora.id]:"https://app.safe.global/aurora:",[chains.avalanche.id]:"https://app.safe.global/avax:",[chains.base.id]:"https://app.safe.global/base:",[chains.boba.id]:"https://app.safe.global/boba:",[chains.bsc.id]:"https://app.safe.global/bnb:",[chains.celo.id]:"https://app.safe.global/celo:",[chains.gnosis.id]:"https://app.safe.global/gno:",[chains.optimism.id]:"https://app.safe.global/oeth:",[chains.polygonZkEvm.id]:"https://app.safe.global/zkevm:",[chains.zksync.id]:"https://app.safe.global/zksync:"},W={[chains.mainnet.id]:"https://safe-transaction-mainnet.safe.global/api/v1",[chains.goerli.id]:"https://safe-transaction-goerli.safe.global/api/v1",[chains.sepolia.id]:"https://safe-transaction-sepolia.safe.global/api/v1",[chains.polygon.id]:"https://safe-transaction-polygon.safe.global/api/v1",[chains.arbitrum.id]:"https://safe-transaction-arbitrum.safe.global/api/v1",[chains.aurora.id]:"https://safe-transaction-aurora.safe.global/api/v1",[chains.avalanche.id]:"https://safe-transaction-avalanche.safe.global/api/v1",[chains.base.id]:"https://safe-transaction-base.safe.global/api/v1",[chains.boba.id]:"https://safe-transaction-boba.safe.global/api/v1",[chains.bsc.id]:"https://safe-transaction-bsc.safe.global/api/v1",[chains.celo.id]:"https://safe-transaction-celo.safe.global/api/v1",[chains.gnosis.id]:"https://safe-transaction-gnosis-chain.safe.global/api/v1",[chains.optimism.id]:"https://safe-transaction-optimism.safe.global/api/v1",[chains.polygonZkEvm.id]:"https://safe-transaction-zkevm.safe.global/api/v1",[chains.zksync.id]:"https://safe-transaction-zksync.safe.global/api/v1"};var Ee=async({tx:t,stopPolling:e,onSuccess:r,onFailure:o,onReplaced:s,onIntervalTick:a})=>{let n=W[t.chainId];if(!n)throw new Error(`Safe Transaction Service URL not found for chainId: ${t.chainId}`);let i=await fetch(`${n}/multisig-transactions/${t.txKey}/`);if(!i.ok)throw i.status===404&&(o(),e()),new Error(`Safe API responded with status: ${i.status}`);let c=await i.json();if(a?.(c),c.isExecuted){c.isSuccessful?r(c):o(c),e({withoutRemoving:true});return}let p=await fetch(`${n}/safes/${t.from}/multisig-transactions/?nonce=${c.nonce}`);if(!p.ok)throw new Error(`Safe API (nonce check) responded with status: ${p.status}`);let l=(await p.json()).results.find(f=>f.isExecuted);if(l){s?.(l),e({withoutRemoving:true});return}m__default.default().diff(m__default.default(c.submissionDate),"day")>=1&&e();};function Y({tx:t,updateTxParams:e,removeTxFromPool:r,transactionsPool:o,onSuccessCallback:s}){return pulsarCore.initializePollingTracker({tx:t,fetcher:Ee,removeTxFromPool:r,onSuccess:a=>{e(t.txKey,{status:pulsarCore.TransactionStatus.Success,pending:false,isError:false,hash:a.transactionHash??void 0,finishedTimestamp:a.executionDate?m__default.default(a.executionDate).unix():void 0});let n=o[t.txKey];s&&n&&s(n);},onIntervalTick:a=>{e(t.txKey,{hash:a.transactionHash??void 0});},onFailure:a=>{e(t.txKey,{status:pulsarCore.TransactionStatus.Failed,pending:false,isError:true,hash:a?.transactionHash??void 0,errorMessage:a?"Safe transaction failed or was rejected.":"Transaction not found.",finishedTimestamp:a?.executionDate?m__default.default(a.executionDate).unix():void 0});},onReplaced:a=>{e(t.txKey,{status:pulsarCore.TransactionStatus.Replaced,pending:false,hash:t.adapter===orbitCore.OrbitAdapter.EVM?t.hash:viem.zeroHash,replacedTxHash:a.safeTxHash??viem.zeroHash,finishedTimestamp:a.executionDate?m__default.default(a.executionDate).unix():void 0});}})}async function J({tracker:t,tx:e,config:r,transactionsPool:o,onSuccessCallback:s,...a}){switch(t){case pulsarCore.TransactionTracker.Ethereum:return y({tx:e,config:r,transactionsPool:o,onSuccessCallback:s,...a});case pulsarCore.TransactionTracker.Gelato:return I({tx:e,transactionsPool:o,onSuccessCallback:s,...a});case pulsarCore.TransactionTracker.Safe:return Y({tx:e,transactionsPool:o,onSuccessCallback:s,...a});default:return console.warn(`Unknown tracker type: '${t}'. Falling back to default EVM tracker.`),y({tx:e,config:r,transactionsPool:o,onSuccessCallback:s,...a})}}function Z(t,e){if(R(t))return {tracker:pulsarCore.TransactionTracker.Gelato,txKey:t.taskId};if(!viem.isHex(t))throw new Error(`Invalid transaction key format. Expected a Hex string or a GelatoTxKey object, but received: ${JSON.stringify(t)}`);let r=e.split(":");return (r.length>1?r[r.length-1]==="safe"||r[r.length-1]==="safewallet":e?.toLowerCase()==="safe")?{tracker:pulsarCore.TransactionTracker.Safe,txKey:t}:{tracker:pulsarCore.TransactionTracker.Ethereum,txKey:t}}var X=({chains:t,tx:e})=>{if(e.tracker===pulsarCore.TransactionTracker.Safe){let a=B[e.chainId];return a?`${a}${e.from}/transactions/tx?id=multisig_${e.from}_${e.txKey}`:""}let o=t.find(a=>a.id===e.chainId)?.blockExplorers?.default.url;if(!o)return "";let s=(e.adapter===orbitCore.OrbitAdapter.EVM?e.replacedTxHash:e.txKey)||(e.adapter===orbitCore.OrbitAdapter.EVM?e.hash:e.txKey);return s?`${o}/tx/${s}`:""};var ee=1.15;async function te({config:t,tx:e}){if(e.adapter!==orbitCore.OrbitAdapter.EVM)throw new Error(`Speed up is only available for EVM transactions. Received adapter type: '${e.adapter}'.`);let{nonce:r,from:o,to:s,value:a,input:n,maxFeePerGas:i,maxPriorityFeePerGas:c,chainId:p}=e;if(r===void 0||!o||!s||!a||!i||!c)throw new Error("Transaction is missing required fields for speed-up.");try{if(!t)throw new Error("Wagmi config is not provided.");if(!core.getAccount(t).address)throw new Error("No connected account found.");let l=BigInt(Math.ceil(Number(c)*ee)),f=BigInt(Math.ceil(Number(i)*ee));return await core.sendTransaction(t,{to:s,value:BigInt(a),data:n||"0x",chainId:p,nonce:r,maxFeePerGas:f,maxPriorityFeePerGas:l})}catch(d){let l=d instanceof Error?d.message:String(d);throw new Error(`Failed to speed up transaction: ${l}`)}}function oa(t,e){if(!t)throw new Error("EVM adapter requires a wagmi config object.");return {key:orbitCore.OrbitAdapter.EVM,getConnectorInfo:()=>{let r=core.getConnection(t),o=orbitCore.lastConnectedConnectorHelpers.getLastConnectedConnector();return {walletAddress:r.address??o?.address??viem.zeroAddress,connectorType:orbitCore.getConnectorTypeFromName(orbitCore.OrbitAdapter.EVM,r.connector?.name?.toLowerCase()??"unknown")}},checkChainForTx:r=>orbitEvm.checkAndSwitchChain(r,t),checkTransactionsTracker:(r,o)=>Z(r,o),checkAndInitializeTrackerInStore:({tx:r,...o})=>J({tracker:r.tracker,tx:r,config:t,...o}),getExplorerUrl:r=>{let{chain:o}=core.getConnection(t),s=o?.blockExplorers?.default.url;return r?`${s}/${r}`:s},getExplorerTxUrl:r=>X({chains:e,tx:r}),cancelTxAction:r=>C({config:t,tx:r}),speedUpTxAction:r=>te({config:t,tx:r}),retryTxAction:async({onClose:r,txKey:o,executeTxAction:s,tx:a})=>{if(r(o),!s){console.error("Retry failed: executeTxAction function is not provided.");return}await s({actionFunction:()=>a.actionFunction({config:t,...a.payload}),params:a,defaultTracker:pulsarCore.TransactionTracker.Ethereum});}}}var g=null,k=null,He=300*1e3,Ke="https://relay.gelato.digital/relays/v2/supported-chains";async function ia(t){let e=Date.now();if(g&&k&&e-k<He)return g.includes(t);try{let r=await fetch(Ke);if(!r.ok)throw new Error(`Gelato API responded with status: ${r.status}`);let s=(await r.json()).chains.map(Number);return g=s,k=e,s.includes(t)}catch(r){return console.error("Failed to fetch Gelato supported chains:",r),g=null,k=null,false}}
|
|
2
|
-
exports.GelatoTaskState=he;exports.SafeTransactionServiceUrls=W;exports.cancelTxAction=C;exports.checkAndInitializeTrackerInStore=J;exports.checkIsGelatoAvailable=ia;exports.checkTransactionsTracker=Z;exports.evmTracker=me;exports.evmTrackerForStore=y;exports.gelatoFetcher=ke;exports.gelatoTrackerForStore=I;exports.gnosisSafeLinksHelper=B;exports.isGelatoTxKey=R;exports.pulsarEvmAdapter=oa;exports.safeFetcher=Ee;exports.safeSdkOptions=ft;exports.safeTrackerForStore=Y;exports.selectEvmTxExplorerLink=X;exports.speedUpTxAction=te
|
|
3
|
-
//# sourceMappingURL=index.js.map
|
|
2
|
+
exports.GelatoTaskState=he;exports.SafeTransactionServiceUrls=W;exports.cancelTxAction=C;exports.checkAndInitializeTrackerInStore=J;exports.checkIsGelatoAvailable=ia;exports.checkTransactionsTracker=Z;exports.evmTracker=me;exports.evmTrackerForStore=y;exports.gelatoFetcher=ke;exports.gelatoTrackerForStore=I;exports.gnosisSafeLinksHelper=B;exports.isGelatoTxKey=R;exports.pulsarEvmAdapter=oa;exports.safeFetcher=Ee;exports.safeSdkOptions=ft;exports.safeTrackerForStore=Y;exports.selectEvmTxExplorerLink=X;exports.speedUpTxAction=te;
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
1
|
import {OrbitAdapter,lastConnectedConnectorHelpers,getConnectorTypeFromName}from'@tuwaio/orbit-core';import {checkAndSwitchChain}from'@tuwaio/orbit-evm';import {TransactionStatus,initializePollingTracker,TransactionTracker}from'@tuwaio/pulsar-core';import {getAccount,sendTransaction,getClient,getConnection}from'@wagmi/core';import {zeroHash,isHex,zeroAddress}from'viem';import {getTransaction,waitForTransactionReceipt,getBlock}from'viem/actions';import m from'dayjs';import {zksync,polygonZkEvm,optimism,gnosis,celo,bsc,boba,base,avalanche,aurora,arbitrum,polygon,sepolia,goerli,mainnet}from'viem/chains';var v=1.15;async function C({config:t,tx:e}){if(e.adapter!==OrbitAdapter.EVM)throw new Error(`Cancellation is only available for EVM transactions. Received adapter type: '${e.adapter}'.`);let{nonce:r,maxFeePerGas:o,maxPriorityFeePerGas:s,chainId:a}=e;if(r===void 0||!o||!s)throw new Error("Transaction is missing required fields for cancellation (nonce, maxFeePerGas, maxPriorityFeePerGas).");try{if(!t)throw new Error("Wagmi config is not provided.");let n=getAccount(t);if(!n.address)throw new Error("No connected account found.");let i=BigInt(Math.ceil(Number(s)*v)),c=BigInt(Math.ceil(Number(o)*v));return await sendTransaction(t,{to:n.address,value:0n,chainId:a,nonce:r,maxFeePerGas:c,maxPriorityFeePerGas:i})}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`Failed to cancel transaction: ${i}`)}}var de=10,ue=3e3;async function me(t){let{tx:e,config:r,onInitialize:o,onTxDetailsFetched:s,onSuccess:a,onFailure:n,onReplaced:i,retryCount:c=de,retryTimeout:p=ue,waitForTransactionReceiptParams:d}=t;if(o?.(),e.txKey===zeroHash)return n(new Error("Transaction hash cannot be the zero hash."));let l=getClient(r,{chainId:e.chainId});if(!l)return n(new Error(`Could not create a viem client for chainId: ${e.chainId}`));let f=null;for(let u=0;u<c;u++)try{f=await getTransaction(l,{hash:e.txKey}),s(f);break}catch(T){if(u===c-1)return console.error(`EVM tracker failed to fetch tx ${e.txKey} after ${c} retries:`,T),n(T);await new Promise(b=>setTimeout(b,p));}if(!f)return n(new Error("Transaction details could not be fetched."));try{let u=!1,T=await waitForTransactionReceipt(l,{hash:f.hash,onReplaced:b=>{u=!0,i(b);},...d});if(u)return;await a(f,T,l);}catch(u){console.error(`Error waiting for receipt for tx ${e.txKey}:`,u),n(u);}}async function y(t){let{tx:e,config:r,updateTxParams:o,transactionsPool:s,onSuccessCallback:a}=t;return me({tx:e,config:r,onInitialize:()=>{o(e.txKey,{hash:e.txKey});},onTxDetailsFetched:n=>{o(e.txKey,{to:n.to??void 0,input:n.input,value:n.value?.toString(),nonce:n.nonce,maxFeePerGas:n.maxFeePerGas?.toString(),maxPriorityFeePerGas:n.maxPriorityFeePerGas?.toString()});},onSuccess:async(n,i,c)=>{let p=await getBlock(c,{blockNumber:i.blockNumber}),d=Number(p.timestamp),l=i.status==="success";o(e.txKey,{status:l?TransactionStatus.Success:TransactionStatus.Failed,isError:!l,pending:false,finishedTimestamp:d});let f=s[e.txKey];l&&a&&f&&a(f);},onReplaced:n=>{o(e.txKey,{status:TransactionStatus.Replaced,replacedTxHash:n.transaction.hash,pending:false});},onFailure:n=>{o(e.txKey,{status:TransactionStatus.Failed,pending:false,isError:true,errorMessage:n instanceof Error?n.message:"Transaction failed or could not be tracked."});}})}function R(t){return typeof t=="object"&&t!==null&&"taskId"in t}var he=(i=>(i.CheckPending="CheckPending",i.ExecPending="ExecPending",i.WaitingForConfirmation="WaitingForConfirmation",i.ExecSuccess="ExecSuccess",i.ExecReverted="ExecReverted",i.Cancelled="Cancelled",i.NotFound="NotFound",i))(he||{}),xe="https://api.gelato.digital/tasks/status/",F=new Set(["ExecReverted","Cancelled","NotFound"]);function ge(t){return t!=="ExecSuccess"&&!F.has(t)}var ke=async({tx:t,stopPolling:e,onSuccess:r,onFailure:o,onIntervalTick:s})=>{let a=await fetch(`${xe}${t.txKey}`);if(!a.ok){if(a.status===404){o(),e();return}throw new Error(`Gelato API responded with status: ${a.status}`)}let n=await a.json(),{taskState:i,creationDate:c}=n.task;if(s?.(n),c&&m().diff(m(c),"hour")>=1&&ge(i)){e();return}i==="ExecSuccess"?(r(n),e({withoutRemoving:true})):F.has(i)&&(o(n),e({withoutRemoving:true}));};function I({tx:t,updateTxParams:e,removeTxFromPool:r,transactionsPool:o,onSuccessCallback:s}){return initializePollingTracker({tx:t,fetcher:ke,removeTxFromPool:r,onSuccess:a=>{e(t.txKey,{status:TransactionStatus.Success,pending:false,isError:false,hash:a.task.transactionHash,finishedTimestamp:a.task.executionDate?m(a.task.executionDate).unix():void 0});let n=o[t.txKey];s&&n&&s(n);},onIntervalTick:a=>{e(t.txKey,{hash:a.task.transactionHash});},onFailure:a=>{e(t.txKey,{status:TransactionStatus.Failed,pending:false,isError:true,hash:a?.task.transactionHash,errorMessage:a?.task.lastCheckMessage??"Transaction failed or was not found.",finishedTimestamp:a?.task.executionDate?m(a.task.executionDate).unix():void 0});}})}var ft={allowedDomains:[/gnosis-safe.io$/,/app.safe.global$/,/metissafe.tech$/],debug:false},B={[mainnet.id]:"https://app.safe.global/eth:",[goerli.id]:"https://app.safe.global/gor:",[sepolia.id]:"https://app.safe.global/sep:",[polygon.id]:"https://app.safe.global/matic:",[arbitrum.id]:"https://app.safe.global/arb1:",[aurora.id]:"https://app.safe.global/aurora:",[avalanche.id]:"https://app.safe.global/avax:",[base.id]:"https://app.safe.global/base:",[boba.id]:"https://app.safe.global/boba:",[bsc.id]:"https://app.safe.global/bnb:",[celo.id]:"https://app.safe.global/celo:",[gnosis.id]:"https://app.safe.global/gno:",[optimism.id]:"https://app.safe.global/oeth:",[polygonZkEvm.id]:"https://app.safe.global/zkevm:",[zksync.id]:"https://app.safe.global/zksync:"},W={[mainnet.id]:"https://safe-transaction-mainnet.safe.global/api/v1",[goerli.id]:"https://safe-transaction-goerli.safe.global/api/v1",[sepolia.id]:"https://safe-transaction-sepolia.safe.global/api/v1",[polygon.id]:"https://safe-transaction-polygon.safe.global/api/v1",[arbitrum.id]:"https://safe-transaction-arbitrum.safe.global/api/v1",[aurora.id]:"https://safe-transaction-aurora.safe.global/api/v1",[avalanche.id]:"https://safe-transaction-avalanche.safe.global/api/v1",[base.id]:"https://safe-transaction-base.safe.global/api/v1",[boba.id]:"https://safe-transaction-boba.safe.global/api/v1",[bsc.id]:"https://safe-transaction-bsc.safe.global/api/v1",[celo.id]:"https://safe-transaction-celo.safe.global/api/v1",[gnosis.id]:"https://safe-transaction-gnosis-chain.safe.global/api/v1",[optimism.id]:"https://safe-transaction-optimism.safe.global/api/v1",[polygonZkEvm.id]:"https://safe-transaction-zkevm.safe.global/api/v1",[zksync.id]:"https://safe-transaction-zksync.safe.global/api/v1"};var Ee=async({tx:t,stopPolling:e,onSuccess:r,onFailure:o,onReplaced:s,onIntervalTick:a})=>{let n=W[t.chainId];if(!n)throw new Error(`Safe Transaction Service URL not found for chainId: ${t.chainId}`);let i=await fetch(`${n}/multisig-transactions/${t.txKey}/`);if(!i.ok)throw i.status===404&&(o(),e()),new Error(`Safe API responded with status: ${i.status}`);let c=await i.json();if(a?.(c),c.isExecuted){c.isSuccessful?r(c):o(c),e({withoutRemoving:true});return}let p=await fetch(`${n}/safes/${t.from}/multisig-transactions/?nonce=${c.nonce}`);if(!p.ok)throw new Error(`Safe API (nonce check) responded with status: ${p.status}`);let l=(await p.json()).results.find(f=>f.isExecuted);if(l){s?.(l),e({withoutRemoving:true});return}m().diff(m(c.submissionDate),"day")>=1&&e();};function Y({tx:t,updateTxParams:e,removeTxFromPool:r,transactionsPool:o,onSuccessCallback:s}){return initializePollingTracker({tx:t,fetcher:Ee,removeTxFromPool:r,onSuccess:a=>{e(t.txKey,{status:TransactionStatus.Success,pending:false,isError:false,hash:a.transactionHash??void 0,finishedTimestamp:a.executionDate?m(a.executionDate).unix():void 0});let n=o[t.txKey];s&&n&&s(n);},onIntervalTick:a=>{e(t.txKey,{hash:a.transactionHash??void 0});},onFailure:a=>{e(t.txKey,{status:TransactionStatus.Failed,pending:false,isError:true,hash:a?.transactionHash??void 0,errorMessage:a?"Safe transaction failed or was rejected.":"Transaction not found.",finishedTimestamp:a?.executionDate?m(a.executionDate).unix():void 0});},onReplaced:a=>{e(t.txKey,{status:TransactionStatus.Replaced,pending:false,hash:t.adapter===OrbitAdapter.EVM?t.hash:zeroHash,replacedTxHash:a.safeTxHash??zeroHash,finishedTimestamp:a.executionDate?m(a.executionDate).unix():void 0});}})}async function J({tracker:t,tx:e,config:r,transactionsPool:o,onSuccessCallback:s,...a}){switch(t){case TransactionTracker.Ethereum:return y({tx:e,config:r,transactionsPool:o,onSuccessCallback:s,...a});case TransactionTracker.Gelato:return I({tx:e,transactionsPool:o,onSuccessCallback:s,...a});case TransactionTracker.Safe:return Y({tx:e,transactionsPool:o,onSuccessCallback:s,...a});default:return console.warn(`Unknown tracker type: '${t}'. Falling back to default EVM tracker.`),y({tx:e,config:r,transactionsPool:o,onSuccessCallback:s,...a})}}function Z(t,e){if(R(t))return {tracker:TransactionTracker.Gelato,txKey:t.taskId};if(!isHex(t))throw new Error(`Invalid transaction key format. Expected a Hex string or a GelatoTxKey object, but received: ${JSON.stringify(t)}`);let r=e.split(":");return (r.length>1?r[r.length-1]==="safe"||r[r.length-1]==="safewallet":e?.toLowerCase()==="safe")?{tracker:TransactionTracker.Safe,txKey:t}:{tracker:TransactionTracker.Ethereum,txKey:t}}var X=({chains:t,tx:e})=>{if(e.tracker===TransactionTracker.Safe){let a=B[e.chainId];return a?`${a}${e.from}/transactions/tx?id=multisig_${e.from}_${e.txKey}`:""}let o=t.find(a=>a.id===e.chainId)?.blockExplorers?.default.url;if(!o)return "";let s=(e.adapter===OrbitAdapter.EVM?e.replacedTxHash:e.txKey)||(e.adapter===OrbitAdapter.EVM?e.hash:e.txKey);return s?`${o}/tx/${s}`:""};var ee=1.15;async function te({config:t,tx:e}){if(e.adapter!==OrbitAdapter.EVM)throw new Error(`Speed up is only available for EVM transactions. Received adapter type: '${e.adapter}'.`);let{nonce:r,from:o,to:s,value:a,input:n,maxFeePerGas:i,maxPriorityFeePerGas:c,chainId:p}=e;if(r===void 0||!o||!s||!a||!i||!c)throw new Error("Transaction is missing required fields for speed-up.");try{if(!t)throw new Error("Wagmi config is not provided.");if(!getAccount(t).address)throw new Error("No connected account found.");let l=BigInt(Math.ceil(Number(c)*ee)),f=BigInt(Math.ceil(Number(i)*ee));return await sendTransaction(t,{to:s,value:BigInt(a),data:n||"0x",chainId:p,nonce:r,maxFeePerGas:f,maxPriorityFeePerGas:l})}catch(d){let l=d instanceof Error?d.message:String(d);throw new Error(`Failed to speed up transaction: ${l}`)}}function oa(t,e){if(!t)throw new Error("EVM adapter requires a wagmi config object.");return {key:OrbitAdapter.EVM,getConnectorInfo:()=>{let r=getConnection(t),o=lastConnectedConnectorHelpers.getLastConnectedConnector();return {walletAddress:r.address??o?.address??zeroAddress,connectorType:getConnectorTypeFromName(OrbitAdapter.EVM,r.connector?.name?.toLowerCase()??"unknown")}},checkChainForTx:r=>checkAndSwitchChain(r,t),checkTransactionsTracker:(r,o)=>Z(r,o),checkAndInitializeTrackerInStore:({tx:r,...o})=>J({tracker:r.tracker,tx:r,config:t,...o}),getExplorerUrl:r=>{let{chain:o}=getConnection(t),s=o?.blockExplorers?.default.url;return r?`${s}/${r}`:s},getExplorerTxUrl:r=>X({chains:e,tx:r}),cancelTxAction:r=>C({config:t,tx:r}),speedUpTxAction:r=>te({config:t,tx:r}),retryTxAction:async({onClose:r,txKey:o,executeTxAction:s,tx:a})=>{if(r(o),!s){console.error("Retry failed: executeTxAction function is not provided.");return}await s({actionFunction:()=>a.actionFunction({config:t,...a.payload}),params:a,defaultTracker:TransactionTracker.Ethereum});}}}var g=null,k=null,He=300*1e3,Ke="https://relay.gelato.digital/relays/v2/supported-chains";async function ia(t){let e=Date.now();if(g&&k&&e-k<He)return g.includes(t);try{let r=await fetch(Ke);if(!r.ok)throw new Error(`Gelato API responded with status: ${r.status}`);let s=(await r.json()).chains.map(Number);return g=s,k=e,s.includes(t)}catch(r){return console.error("Failed to fetch Gelato supported chains:",r),g=null,k=null,false}}
|
|
2
|
-
export{he as GelatoTaskState,W as SafeTransactionServiceUrls,C as cancelTxAction,J as checkAndInitializeTrackerInStore,ia as checkIsGelatoAvailable,Z as checkTransactionsTracker,me as evmTracker,y as evmTrackerForStore,ke as gelatoFetcher,I as gelatoTrackerForStore,B as gnosisSafeLinksHelper,R as isGelatoTxKey,oa as pulsarEvmAdapter,Ee as safeFetcher,ft as safeSdkOptions,Y as safeTrackerForStore,X as selectEvmTxExplorerLink,te as speedUpTxAction}
|
|
3
|
-
//# sourceMappingURL=index.mjs.map
|
|
2
|
+
export{he as GelatoTaskState,W as SafeTransactionServiceUrls,C as cancelTxAction,J as checkAndInitializeTrackerInStore,ia as checkIsGelatoAvailable,Z as checkTransactionsTracker,me as evmTracker,y as evmTrackerForStore,ke as gelatoFetcher,I as gelatoTrackerForStore,B as gnosisSafeLinksHelper,R as isGelatoTxKey,oa as pulsarEvmAdapter,Ee as safeFetcher,ft as safeSdkOptions,Y as safeTrackerForStore,X as selectEvmTxExplorerLink,te as speedUpTxAction};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tuwaio/pulsar-evm",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "Oleksandr Tkach",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -49,18 +49,18 @@
|
|
|
49
49
|
"zustand": "5.x.x"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
|
-
"@tuwaio/orbit-core": "^0.2.
|
|
53
|
-
"@tuwaio/orbit-evm": "^0.2.
|
|
54
|
-
"@wagmi/core": "^3.0
|
|
52
|
+
"@tuwaio/orbit-core": "^0.2.2",
|
|
53
|
+
"@tuwaio/orbit-evm": "^0.2.5",
|
|
54
|
+
"@wagmi/core": "^3.1.0",
|
|
55
55
|
"dayjs": "^1.11.19",
|
|
56
|
-
"immer": "^11.1.
|
|
56
|
+
"immer": "^11.1.3",
|
|
57
57
|
"jsdom": "^27.4.0",
|
|
58
58
|
"tsup": "^8.5.1",
|
|
59
59
|
"typescript": "^5.9.3",
|
|
60
|
-
"viem": "^2.43.
|
|
60
|
+
"viem": "^2.43.5",
|
|
61
61
|
"vitest": "^4.0.16",
|
|
62
62
|
"zustand": "^5.0.9",
|
|
63
|
-
"@tuwaio/pulsar-core": "^0.3.
|
|
63
|
+
"@tuwaio/pulsar-core": "^0.3.2"
|
|
64
64
|
},
|
|
65
65
|
"scripts": {
|
|
66
66
|
"start": "tsup src/index.ts --watch",
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/cancelTxAction.ts","../src/trackers/evmTracker.ts","../src/trackers/gelatoTracker.ts","../src/utils/safeConstants.ts","../src/trackers/safeTracker.ts","../src/utils/checkAndInitializeTrackerInStore.ts","../src/utils/checkTransactionsTracker.ts","../src/utils/selectEvmTxExplorerLink.ts","../src/utils/speedUpTxAction.ts","../src/adapters/evmAdapter.ts","../src/utils/checkIsGelatoAvailable.ts"],"names":["GAS_INCREASE_PERCENTAGE","cancelTxAction","config","tx","OrbitAdapter","nonce","maxFeePerGas","maxPriorityFeePerGas","chainId","account","getAccount","newPriorityFee","newMaxFee","sendTransaction","e","errorMessage","DEFAULT_RETRY_COUNT","DEFAULT_RETRY_TIMEOUT_MS","evmTracker","params","onInitialize","onTxDetailsFetched","onSuccess","onFailure","onReplaced","retryCount","retryTimeout","waitForTransactionReceiptParams","zeroHash","client","getClient","txDetails","i","getTransaction","error","resolve","wasReplaced","receipt","waitForTransactionReceipt","replacement","evmTrackerForStore","updateTxParams","transactionsPool","onSuccessCallback","block","getBlock","timestamp","isSuccess","TransactionStatus","updatedTx","isGelatoTxKey","txKey","GelatoTaskState","GELATO_API_BASE_URL","GELATO_TERMINAL_FAILURE_STATES","isGelatoTxPending","gelatoStatus","gelatoFetcher","stopPolling","onIntervalTick","response","data","taskState","creationDate","dayjs","gelatoTrackerForStore","removeTxFromPool","initializePollingTracker","safeSdkOptions","gnosisSafeLinksHelper","mainnet","goerli","sepolia","polygon","arbitrum","aurora","avalanche","base","boba","bsc","celo","gnosis","optimism","polygonZkEvm","zksync","SafeTransactionServiceUrls","safeFetcher","baseUrl","primaryTxResponse","safeStatus","nonceTxsResponse","executedTx","t","safeTrackerForStore","checkAndInitializeTrackerInStore","tracker","rest","TransactionTracker","checkTransactionsTracker","actionTxKey","connectorType","isHex","splittingConnectorType","selectEvmTxExplorerLink","chains","safeBaseUrl","explorerUrl","c","hash","speedUpTxAction","from","to","value","input","pulsarEvmAdapter","appChains","activeConnection","getConnection","localConnectedConnector","lastConnectedConnectorHelpers","zeroAddress","getConnectorTypeFromName","checkAndSwitchChain","url","chain","baseExplorerLink","onClose","executeTxAction","cachedRelayChainIds","cacheTimestamp","CACHE_DURATION_MS","GELATO_API_URL","checkIsGelatoAvailable","now","supportedChainIds"],"mappings":"2XAWA,IAAMA,CAAAA,CAA0B,IAAA,CAqChC,eAAsBC,CAAAA,CAAsC,CAAE,MAAA,CAAAC,CAAAA,CAAQ,EAAA,CAAAC,CAAG,CAAA,CAA4C,CAEnH,GAAIA,CAAAA,CAAG,OAAA,GAAYC,sBAAAA,CAAa,GAAA,CAC9B,MAAM,IAAI,KAAA,CAAM,CAAA,6EAAA,EAAgFD,CAAAA,CAAG,OAAO,CAAA,EAAA,CAAI,CAAA,CAIhH,GAAM,CAAE,MAAAE,CAAAA,CAAO,YAAA,CAAAC,CAAAA,CAAc,oBAAA,CAAAC,CAAAA,CAAsB,OAAA,CAAAC,CAAQ,CAAA,CAAIL,CAAAA,CAE/D,GAAIE,CAAAA,GAAU,MAAA,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AA,CAAG,OAAQ,CAAC,CAAA,CACjE,MAAA,CAAQA,CAAAA,CACR,cAAA,CAAgB8F,6BAAAA,CAAmB,QACrC,CAAC,EACH,CACF,CACF,CCtFA,IAAI+B,CAAAA,CAAuC,IAAA,CACvCC,CAAAA,CAAgC,IAAA,CAC9BC,EAAAA,CAAoB,GAAA,CAAS,GAAA,CAC7BC,EAAAA,CAAiB,yDAAA,CAWvB,eAAsBC,EAAAA,CAAuB5H,CAAAA,CAAmC,CAC9E,IAAM6H,EAAM,IAAA,CAAK,GAAA,EAAI,CAGrB,GAAIL,CAAAA,EAAuBC,CAAAA,EAAkBI,CAAAA,CAAMJ,CAAAA,CAAiBC,EAAAA,CAClE,OAAOF,CAAAA,CAAoB,QAAA,CAASxH,CAAO,CAAA,CAI7C,GAAI,CACF,IAAMoD,CAAAA,CAAW,MAAM,KAAA,CAAMuE,EAAc,CAAA,CAE3C,GAAI,CAACvE,CAAAA,CAAS,EAAA,CACZ,MAAM,IAAI,KAAA,CAAM,CAAA,kCAAA,EAAqCA,CAAAA,CAAS,MAAM,EAAE,CAAA,CAKxE,IAAM0E,CAAAA,CAAAA,CAFQ,MAAM1E,CAAAA,CAAS,IAAA,EAAK,EAEH,MAAA,CAAO,GAAA,CAAI,MAAM,CAAA,CAGhD,OAAAoE,CAAAA,CAAsBM,CAAAA,CACtBL,CAAAA,CAAiBI,CAAAA,CAEVC,CAAAA,CAAkB,QAAA,CAAS9H,CAAO,CAC3C,CAAA,MAAS0B,CAAAA,CAAO,CACd,OAAA,OAAA,CAAQ,KAAA,CAAM,0CAAA,CAA4CA,CAAK,CAAA,CAG/D8F,CAAAA,CAAsB,IAAA,CACtBC,CAAAA,CAAiB,IAAA,CAEV,KACT,CACF","file":"index.js","sourcesContent":["/**\n * @file This file contains a utility function for canceling a pending EVM transaction.\n */\n\nimport { OrbitAdapter } from '@tuwaio/orbit-core';\nimport { Transaction } from '@tuwaio/pulsar-core';\nimport { Config, getAccount, sendTransaction } from '@wagmi/core';\nimport { Hex } from 'viem';\n\n// A common strategy is to increase gas by at least 10% to ensure replacement.\n// We use 15% for a higher chance of success.\nconst GAS_INCREASE_PERCENTAGE = 1.15;\n\n/**\n * Cancels a pending EVM transaction by sending a new, zero-value transaction to oneself\n * with the same nonce but higher gas fees. This effectively replaces the original transaction.\n *\n * @template T - The transaction type, which must be a valid EVM transaction.\n *\n * @param {object} params - The parameters required to cancel the transaction.\n * @param {Config} params.config - The wagmi configuration object.\n * @param {T} params.tx - The original transaction object to be canceled. It must contain the nonce and gas fee fields.\n *\n * @returns {Promise<Hex>} A promise that resolves with the hash of the new cancellation transaction.\n *\n * @throws {Error} Throws an error if:\n * - The transaction is not an EVM transaction.\n * - The transaction is missing required fields (`nonce`, `maxFeePerGas`, etc.).\n * - The wagmi config is not provided.\n * - No connected account is found.\n * - The `sendTransaction` call fails.\n *\n * @example\n * ```ts\n * const handleCancel = async (stuckTransaction) => {\n * try {\n * const cancelTxHash = await cancelTxAction({\n * config: wagmiConfig,\n * tx: stuckTransaction,\n * });\n * console.log('Cancellation transaction sent with hash:', cancelTxHash);\n * // You should now update your state to track this new transaction.\n * } catch (error) {\n * console.error('Failed to cancel transaction:', error);\n * }\n * };\n * ```\n */\nexport async function cancelTxAction<T extends Transaction>({ config, tx }: { config: Config; tx: T }): Promise<Hex> {\n // 1. Validate the transaction type\n if (tx.adapter !== OrbitAdapter.EVM) {\n throw new Error(`Cancellation is only available for EVM transactions. Received adapter type: '${tx.adapter}'.`);\n }\n\n // 2. Ensure all necessary transaction details are present.\n const { nonce, maxFeePerGas, maxPriorityFeePerGas, chainId } = tx;\n\n if (nonce === undefined || !maxFeePerGas || !maxPriorityFeePerGas) {\n throw new Error(\n 'Transaction is missing required fields for cancellation (nonce, maxFeePerGas, maxPriorityFeePerGas).',\n );\n }\n\n try {\n // 3. Verify wagmi configuration and connected account\n if (!config) {\n throw new Error('Wagmi config is not provided.');\n }\n const account = getAccount(config);\n if (!account.address) {\n throw new Error('No connected account found.');\n }\n\n // 4. Calculate new gas fees.\n const newPriorityFee = BigInt(Math.ceil(Number(maxPriorityFeePerGas) * GAS_INCREASE_PERCENTAGE));\n const newMaxFee = BigInt(Math.ceil(Number(maxFeePerGas) * GAS_INCREASE_PERCENTAGE));\n\n // 5. Send a zero-value transaction to your own address with the same nonce and higher gas.\n return await sendTransaction(config, {\n to: account.address,\n value: 0n,\n chainId: chainId as number,\n nonce: nonce,\n maxFeePerGas: newMaxFee,\n maxPriorityFeePerGas: newPriorityFee,\n });\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : String(e);\n // Re-throw the error with more context for easier debugging.\n throw new Error(`Failed to cancel transaction: ${errorMessage}`);\n }\n}\n","/**\n * @file This file contains the tracker implementation for standard EVM transactions.\n * It uses viem's public actions (`getTransaction`, `waitForTransactionReceipt`) to monitor\n * a transaction's lifecycle from submission to finality.\n */\n\nimport { ITxTrackingStore, OnSuccessCallback, Transaction, TransactionStatus } from '@tuwaio/pulsar-core';\nimport { Config, getClient } from '@wagmi/core';\nimport {\n Client,\n GetTransactionReturnType,\n Hex,\n ReplacementReturnType,\n TransactionReceipt,\n WaitForTransactionReceiptParameters,\n zeroHash,\n} from 'viem';\nimport { getBlock, getTransaction, waitForTransactionReceipt } from 'viem/actions';\n\nconst DEFAULT_RETRY_COUNT = 10;\nconst DEFAULT_RETRY_TIMEOUT_MS = 3000;\n\n/**\n * Defines the parameters for the low-level EVM transaction tracker.\n */\nexport type EVMTrackerParams = {\n tx: Pick<Transaction, 'chainId' | 'txKey'>;\n config: Config;\n onTxDetailsFetched: (txDetails: GetTransactionReturnType) => void;\n onSuccess: (txDetails: GetTransactionReturnType, receipt: TransactionReceipt, client: Client) => Promise<void>;\n onReplaced: (replacement: ReplacementReturnType) => void;\n onFailure: (error?: unknown) => void;\n onInitialize?: () => void;\n retryCount?: number;\n retryTimeout?: number;\n waitForTransactionReceiptParams?: WaitForTransactionReceiptParameters;\n};\n\n/**\n * A low-level tracker for monitoring a standard EVM transaction by its hash.\n * It retries fetching the transaction and then waits for its receipt to determine the final status.\n *\n * @param {EVMTrackerParams} params - The configuration object for the tracker.\n */\nexport async function evmTracker(params: EVMTrackerParams): Promise<void> {\n const {\n tx,\n config,\n onInitialize,\n onTxDetailsFetched,\n onSuccess,\n onFailure,\n onReplaced,\n retryCount = DEFAULT_RETRY_COUNT,\n retryTimeout = DEFAULT_RETRY_TIMEOUT_MS,\n waitForTransactionReceiptParams,\n } = params;\n\n onInitialize?.();\n\n if (tx.txKey === zeroHash) {\n return onFailure(new Error('Transaction hash cannot be the zero hash.'));\n }\n\n const client = getClient(config, { chainId: tx.chainId as number });\n if (!client) {\n return onFailure(new Error(`Could not create a viem client for chainId: ${tx.chainId}`));\n }\n\n let txDetails: GetTransactionReturnType | null = null;\n\n // 1. Retry loop to fetch the transaction details.\n // This handles cases where the transaction is not immediately available on the RPC node.\n for (let i = 0; i < retryCount; i++) {\n try {\n txDetails = await getTransaction(client, { hash: tx.txKey as Hex });\n onTxDetailsFetched(txDetails);\n break; // Exit loop on success\n } catch (error) {\n if (i === retryCount - 1) {\n console.error(`EVM tracker failed to fetch tx ${tx.txKey} after ${retryCount} retries:`, error);\n return onFailure(error);\n }\n await new Promise((resolve) => setTimeout(resolve, retryTimeout));\n }\n }\n\n if (!txDetails) {\n // This should theoretically not be reached if the loop completes, but it's a good safeguard.\n return onFailure(new Error('Transaction details could not be fetched.'));\n }\n\n // 2. Wait for the transaction to be mined and get the receipt.\n try {\n let wasReplaced = false;\n const receipt = await waitForTransactionReceipt(client, {\n hash: txDetails.hash,\n onReplaced: (replacement) => {\n wasReplaced = true;\n onReplaced(replacement);\n },\n ...waitForTransactionReceiptParams,\n });\n\n // If onReplaced was called, the promise resolves but we should not proceed to onSuccess.\n if (wasReplaced) {\n return;\n }\n\n // 3. Transaction is mined, call the onSuccess callback.\n await onSuccess(txDetails, receipt, client);\n } catch (error) {\n console.error(`Error waiting for receipt for tx ${tx.txKey}:`, error);\n onFailure(error);\n }\n}\n\n/**\n * A higher-level wrapper for `evmTracker` that integrates directly with the Pulsar store.\n * It provides the necessary callbacks to update a transaction's state throughout its lifecycle.\n *\n * @template T - The application-specific transaction type.\n */\nexport async function evmTrackerForStore<T extends Transaction>(\n params: Pick<EVMTrackerParams, 'config'> &\n Pick<ITxTrackingStore<T>, 'updateTxParams' | 'transactionsPool'> & {\n tx: T;\n } & OnSuccessCallback<T>,\n) {\n const { tx, config, updateTxParams, transactionsPool, onSuccessCallback } = params;\n\n return evmTracker({\n tx,\n config,\n onInitialize: () => {\n // Set the initial hash, which is the same as the txKey for this tracker.\n updateTxParams(tx.txKey, { hash: tx.txKey as Hex });\n },\n onTxDetailsFetched: (txDetails) => {\n // Once we fetch details from the node, update the transaction with more info.\n updateTxParams(tx.txKey, {\n to: txDetails.to ?? undefined,\n input: txDetails.input,\n value: txDetails.value?.toString(),\n nonce: txDetails.nonce,\n maxFeePerGas: txDetails.maxFeePerGas?.toString(),\n maxPriorityFeePerGas: txDetails.maxPriorityFeePerGas?.toString(),\n });\n },\n onSuccess: async (txDetails, receipt, client) => {\n const block = await getBlock(client, { blockNumber: receipt.blockNumber });\n const timestamp = Number(block.timestamp);\n const isSuccess = receipt.status === 'success';\n\n updateTxParams(tx.txKey, {\n status: isSuccess ? TransactionStatus.Success : TransactionStatus.Failed,\n isError: !isSuccess,\n pending: false,\n finishedTimestamp: timestamp,\n });\n\n // After the final state update, retrieve the latest version of the transaction\n // and trigger the global success callback if applicable.\n const updatedTx = transactionsPool[tx.txKey];\n if (isSuccess && onSuccessCallback && updatedTx) {\n onSuccessCallback(updatedTx);\n }\n },\n onReplaced: (replacement) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Replaced,\n replacedTxHash: replacement.transaction.hash,\n pending: false,\n });\n },\n onFailure: (error) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Failed,\n pending: false,\n isError: true,\n errorMessage: error instanceof Error ? error.message : 'Transaction failed or could not be tracked.',\n });\n },\n });\n}\n","/**\n * @file This file implements the transaction tracking logic for meta-transactions relayed via the Gelato Network.\n * It uses a polling mechanism to check the status of a Gelato Task ID from the Gelato API.\n */\n\nimport {\n ActionTxKey,\n GelatoTxKey,\n initializePollingTracker,\n ITxTrackingStore,\n OnSuccessCallback,\n PollingTrackerConfig,\n Transaction,\n TransactionStatus,\n} from '@tuwaio/pulsar-core';\nimport dayjs from 'dayjs';\nimport { Hex } from 'viem';\n\n// =================================================================================================\n// 1. TYPES AND TYPE GUARDS\n// =================================================================================================\n\n/**\n * A type guard to determine if an ActionTxKey is a GelatoTxKey.\n * @param {ActionTxKey} txKey - The transaction key to check.\n * @returns {boolean} True if the key is for a Gelato transaction.\n */\nexport function isGelatoTxKey(txKey: ActionTxKey): txKey is GelatoTxKey {\n return typeof txKey === 'object' && txKey !== null && 'taskId' in txKey;\n}\n\n/**\n * Enum representing the possible states of a Gelato task.\n * @see https://docs.gelato.network/developer-services/relay/api/get-task-status\n */\nexport enum GelatoTaskState {\n CheckPending = 'CheckPending',\n ExecPending = 'ExecPending',\n WaitingForConfirmation = 'WaitingForConfirmation',\n ExecSuccess = 'ExecSuccess',\n ExecReverted = 'ExecReverted',\n Cancelled = 'Cancelled',\n NotFound = 'NotFound',\n}\n\n/**\n * Defines the shape of the response from the Gelato `getTaskStatus` API endpoint.\n */\nexport type GelatoTaskStatusResponse = {\n task: {\n chainId: number;\n taskId: string;\n taskState: GelatoTaskState;\n creationDate?: string;\n executionDate?: string;\n transactionHash?: Hex;\n blockNumber?: number;\n lastCheckMessage?: string;\n };\n};\n\nconst GELATO_API_BASE_URL = 'https://api.gelato.digital/tasks/status/';\n\n// =================================================================================================\n// 2. HELPER FUNCTIONS\n// =================================================================================================\n\nconst GELATO_TERMINAL_FAILURE_STATES = new Set([\n GelatoTaskState.ExecReverted,\n GelatoTaskState.Cancelled,\n GelatoTaskState.NotFound,\n]);\n\nfunction isGelatoTxPending(gelatoStatus: GelatoTaskState): boolean {\n return gelatoStatus !== GelatoTaskState.ExecSuccess && !GELATO_TERMINAL_FAILURE_STATES.has(gelatoStatus);\n}\n\n// =================================================================================================\n// 3. FETCHER IMPLEMENTATION\n// =================================================================================================\n\n/**\n * A reusable fetcher function for `initializePollingTracker` that queries the Gelato API for a task's status.\n * It handles the logic for interpreting Gelato's task states and calls the appropriate polling callbacks.\n */\nexport const gelatoFetcher: PollingTrackerConfig<GelatoTaskStatusResponse, Transaction>['fetcher'] = async ({\n tx,\n stopPolling,\n onSuccess,\n onFailure,\n onIntervalTick,\n}) => {\n const response = await fetch(`${GELATO_API_BASE_URL}${tx.txKey}`);\n\n if (!response.ok) {\n if (response.status === 404) {\n onFailure(); // Treat 404 as a terminal failure.\n stopPolling();\n return;\n }\n // For other errors, let the polling tracker's retry mechanism handle it.\n throw new Error(`Gelato API responded with status: ${response.status}`);\n }\n\n const data = (await response.json()) as GelatoTaskStatusResponse;\n const { taskState, creationDate } = data.task;\n\n onIntervalTick?.(data);\n\n // Safeguard: Stop polling for tasks that have been pending for over a hour.\n if (creationDate && dayjs().diff(dayjs(creationDate), 'hour') >= 1 && isGelatoTxPending(taskState)) {\n stopPolling();\n return;\n }\n\n // Check for terminal states to stop the polling.\n if (taskState === GelatoTaskState.ExecSuccess) {\n onSuccess(data);\n stopPolling({ withoutRemoving: true });\n } else if (GELATO_TERMINAL_FAILURE_STATES.has(taskState)) {\n onFailure(data);\n stopPolling({ withoutRemoving: true });\n }\n};\n\n// =================================================================================================\n// 4. STORE-CONNECTED TRACKER\n// =================================================================================================\n\n/**\n * A higher-level wrapper that integrates the Gelato polling logic with the Pulsar store.\n * It uses the generic `gelatoFetcher` and provides store-specific callbacks.\n *\n * @template T - The application-specific transaction type.\n */\nexport function gelatoTrackerForStore<T extends Transaction>({\n tx,\n updateTxParams,\n removeTxFromPool,\n transactionsPool,\n onSuccessCallback,\n}: Pick<ITxTrackingStore<T>, 'updateTxParams' | 'removeTxFromPool' | 'transactionsPool'> & {\n tx: T;\n} & OnSuccessCallback<T>) {\n return initializePollingTracker<GelatoTaskStatusResponse, T>({\n tx,\n fetcher: gelatoFetcher, // Use the exported, reusable fetcher\n removeTxFromPool,\n onSuccess: (response) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Success,\n pending: false,\n isError: false,\n hash: response.task.transactionHash,\n finishedTimestamp: response.task.executionDate ? dayjs(response.task.executionDate).unix() : undefined,\n });\n\n const updatedTx = transactionsPool[tx.txKey];\n if (onSuccessCallback && updatedTx) {\n onSuccessCallback(updatedTx);\n }\n },\n onIntervalTick: (response) => {\n updateTxParams(tx.txKey, {\n hash: response.task.transactionHash,\n });\n },\n onFailure: (response) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Failed,\n pending: false,\n isError: true,\n hash: response?.task.transactionHash,\n errorMessage: response?.task.lastCheckMessage ?? 'Transaction failed or was not found.',\n finishedTimestamp: response?.task.executionDate ? dayjs(response.task.executionDate).unix() : undefined,\n });\n },\n });\n}\n","/**\n * @file This file contains constants related to Safe (formerly Gnosis Safe) configuration,\n * including SDK options, web app URLs, and transaction service API endpoints for various chains.\n */\n\nimport {\n arbitrum,\n aurora,\n avalanche,\n base,\n boba,\n bsc,\n celo,\n gnosis,\n goerli,\n mainnet,\n optimism,\n polygon,\n polygonZkEvm,\n sepolia,\n zksync,\n} from 'viem/chains';\n\n/**\n * Configuration options for the Safe Apps SDK.\n * This is typically used when integrating with the Safe environment.\n */\nexport const safeSdkOptions = {\n // A list of allowed domains to interact with the Safe Apps SDK.\n allowedDomains: [/gnosis-safe.io$/, /app.safe.global$/, /metissafe.tech$/],\n // A flag to enable or disable debug logging for the SDK.\n debug: false,\n};\n\n/**\n * A mapping of chain IDs to their corresponding Safe web application URL prefixes.\n * Used by selectors like `selectTxExplorerLink` to build correct links for Safe transactions.\n * The prefixes (e.g., 'eth:', 'gor:') are part of the Safe URL scheme.\n * @type {Record<number, string>}\n */\nexport const gnosisSafeLinksHelper: Record<number, string> = {\n [mainnet.id]: 'https://app.safe.global/eth:',\n [goerli.id]: 'https://app.safe.global/gor:',\n [sepolia.id]: 'https://app.safe.global/sep:',\n [polygon.id]: 'https://app.safe.global/matic:',\n [arbitrum.id]: 'https://app.safe.global/arb1:',\n [aurora.id]: 'https://app.safe.global/aurora:',\n [avalanche.id]: 'https://app.safe.global/avax:',\n [base.id]: 'https://app.safe.global/base:',\n [boba.id]: 'https://app.safe.global/boba:',\n [bsc.id]: 'https://app.safe.global/bnb:',\n [celo.id]: 'https://app.safe.global/celo:',\n [gnosis.id]: 'https://app.safe.global/gno:',\n [optimism.id]: 'https://app.safe.global/oeth:',\n [polygonZkEvm.id]: 'https://app.safe.global/zkevm:',\n [zksync.id]: 'https://app.safe.global/zksync:',\n};\n\n/**\n * A comprehensive mapping of chain IDs to their corresponding Safe Transaction Service API endpoints.\n * This is used by the `safeTracker` to fetch the status of multisig transactions from the correct service.\n * @type {Record<number, string>}\n */\nexport const SafeTransactionServiceUrls: Record<number, string> = {\n [mainnet.id]: 'https://safe-transaction-mainnet.safe.global/api/v1',\n [goerli.id]: 'https://safe-transaction-goerli.safe.global/api/v1',\n [sepolia.id]: 'https://safe-transaction-sepolia.safe.global/api/v1',\n [polygon.id]: 'https://safe-transaction-polygon.safe.global/api/v1',\n [arbitrum.id]: 'https://safe-transaction-arbitrum.safe.global/api/v1',\n [aurora.id]: 'https://safe-transaction-aurora.safe.global/api/v1',\n [avalanche.id]: 'https://safe-transaction-avalanche.safe.global/api/v1',\n [base.id]: 'https://safe-transaction-base.safe.global/api/v1',\n [boba.id]: 'https://safe-transaction-boba.safe.global/api/v1',\n [bsc.id]: 'https://safe-transaction-bsc.safe.global/api/v1',\n [celo.id]: 'https://safe-transaction-celo.safe.global/api/v1',\n [gnosis.id]: 'https://safe-transaction-gnosis-chain.safe.global/api/v1',\n [optimism.id]: 'https://safe-transaction-optimism.safe.global/api/v1',\n [polygonZkEvm.id]: 'https://safe-transaction-zkevm.safe.global/api/v1',\n [zksync.id]: 'https://safe-transaction-zksync.safe.global/api/v1',\n};\n","/**\n * @file This file implements the transaction tracking logic for Safe (formerly Gnosis Safe) multisig transactions.\n * It uses a polling mechanism to query the Safe Transaction Service API for the status of a `safeTxHash`.\n */\n\nimport { OrbitAdapter } from '@tuwaio/orbit-core';\nimport {\n initializePollingTracker,\n ITxTrackingStore,\n OnSuccessCallback,\n PollingTrackerConfig,\n Transaction,\n TransactionStatus,\n} from '@tuwaio/pulsar-core';\nimport dayjs from 'dayjs';\nimport { Hex, zeroHash } from 'viem';\n\nimport { SafeTransactionServiceUrls } from '../utils/safeConstants';\n\n// =================================================================================================\n// 1. TYPES\n// =================================================================================================\n\n/**\n * Defines the shape of the primary response for a single transaction from the Safe Transaction Service API.\n */\nexport type SafeTxStatusResponse = {\n transactionHash: Hex | null;\n safeTxHash: Hex;\n isExecuted: boolean;\n isSuccessful: boolean | null;\n executionDate: string | null;\n submissionDate: string;\n modified: string;\n nonce: number;\n};\n\n/**\n * The response shape when querying for multiple transactions (e.g., by nonce).\n */\ntype SafeTxSameNonceResponse = {\n count: number;\n results: SafeTxStatusResponse[];\n};\n\n// =================================================================================================\n// 2. FETCHER IMPLEMENTATION\n// =================================================================================================\n\n/**\n * A reusable fetcher for `initializePollingTracker` that queries the Safe Transaction Service API.\n * It handles the complex logic of detecting executed, failed, and replaced multisig transactions.\n */\nexport const safeFetcher: PollingTrackerConfig<SafeTxStatusResponse, Transaction>['fetcher'] = async ({\n tx,\n stopPolling,\n onSuccess,\n onFailure,\n onReplaced,\n onIntervalTick,\n}) => {\n const baseUrl = SafeTransactionServiceUrls[tx.chainId as number];\n if (!baseUrl) {\n throw new Error(`Safe Transaction Service URL not found for chainId: ${tx.chainId}`);\n }\n\n // 1. Fetch the status of the primary transaction.\n const primaryTxResponse = await fetch(`${baseUrl}/multisig-transactions/${tx.txKey}/`);\n if (!primaryTxResponse.ok) {\n // Treat 404 as a terminal failure (transaction is lost).\n if (primaryTxResponse.status === 404) {\n onFailure();\n stopPolling();\n }\n throw new Error(`Safe API responded with status: ${primaryTxResponse.status}`);\n }\n const safeStatus = (await primaryTxResponse.json()) as SafeTxStatusResponse;\n onIntervalTick?.(safeStatus);\n\n // 2. Check if the primary transaction itself has been executed.\n if (safeStatus.isExecuted) {\n if (safeStatus.isSuccessful) {\n onSuccess(safeStatus);\n } else {\n onFailure(safeStatus);\n }\n stopPolling({ withoutRemoving: true });\n return;\n }\n\n // 3. If still pending, check for replacements.\n // This is necessary because another transaction with the same nonce might have been executed.\n const nonceTxsResponse = await fetch(`${baseUrl}/safes/${tx.from}/multisig-transactions/?nonce=${safeStatus.nonce}`);\n if (!nonceTxsResponse.ok) {\n throw new Error(`Safe API (nonce check) responded with status: ${nonceTxsResponse.status}`);\n }\n const sameNonceTxs = (await nonceTxsResponse.json()) as SafeTxSameNonceResponse;\n const executedTx = sameNonceTxs.results.find((t) => t.isExecuted);\n\n if (executedTx) {\n // If an executed transaction exists and it's not ours, our transaction was replaced.\n onReplaced?.(executedTx);\n stopPolling({ withoutRemoving: true });\n return;\n }\n\n // 4. Safeguard: Stop polling for very old pending transactions.\n if (dayjs().diff(dayjs(safeStatus.submissionDate), 'day') >= 1) {\n stopPolling();\n }\n};\n\n// =================================================================================================\n// 3. STORE-CONNECTED TRACKER\n// =================================================================================================\n\n/**\n * A higher-level wrapper that integrates the Safe polling logic with the Pulsar store.\n * It uses the generic `safeFetcher` and provides store-specific callbacks.\n *\n * @template T - The application-specific transaction type.\n */\nexport function safeTrackerForStore<T extends Transaction>({\n tx,\n updateTxParams,\n removeTxFromPool,\n transactionsPool,\n onSuccessCallback,\n}: Pick<ITxTrackingStore<T>, 'updateTxParams' | 'removeTxFromPool' | 'transactionsPool'> & {\n tx: T;\n} & OnSuccessCallback<T>) {\n return initializePollingTracker<SafeTxStatusResponse, T>({\n tx,\n fetcher: safeFetcher,\n removeTxFromPool,\n onSuccess: (response) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Success,\n pending: false,\n isError: false,\n hash: response.transactionHash ?? undefined,\n finishedTimestamp: response.executionDate ? dayjs(response.executionDate).unix() : undefined,\n });\n\n const updatedTx = transactionsPool[tx.txKey];\n if (onSuccessCallback && updatedTx) {\n onSuccessCallback(updatedTx);\n }\n },\n onIntervalTick: (response) => {\n // Only update fields that might change while pending.\n updateTxParams(tx.txKey, {\n hash: response.transactionHash ?? undefined,\n });\n },\n onFailure: (response) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Failed,\n pending: false,\n isError: true,\n hash: response?.transactionHash ?? undefined,\n errorMessage: response ? 'Safe transaction failed or was rejected.' : 'Transaction not found.',\n finishedTimestamp: response?.executionDate ? dayjs(response.executionDate).unix() : undefined,\n });\n },\n onReplaced: (response) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Replaced,\n pending: false,\n hash: tx.adapter === OrbitAdapter.EVM ? tx.hash : zeroHash,\n // The `replacedTxHash` is the `safeTxHash` of the transaction that was executed instead.\n replacedTxHash: response.safeTxHash ?? zeroHash,\n finishedTimestamp: response.executionDate ? dayjs(response.executionDate).unix() : undefined,\n });\n },\n });\n}\n","/**\n * @file This file contains a utility function that acts as a router to initialize the correct transaction tracker.\n * Based on a transaction's `tracker` property, it delegates the tracking task to the appropriate implementation.\n */\n\nimport { ITxTrackingStore, OnSuccessCallback, Transaction, TransactionTracker } from '@tuwaio/pulsar-core';\nimport { Config } from '@wagmi/core';\n\nimport { evmTrackerForStore } from '../trackers/evmTracker';\nimport { gelatoTrackerForStore } from '../trackers/gelatoTracker';\nimport { safeTrackerForStore } from '../trackers/safeTracker';\n\n/**\n * The parameters required to initialize a tracker.\n * @template T - The application-specific transaction type.\n */\ntype InitializeTrackerParams<T extends Transaction> = Pick<\n ITxTrackingStore<T>,\n 'updateTxParams' | 'removeTxFromPool' | 'transactionsPool'\n> & {\n config: Config;\n tx: T;\n tracker: TransactionTracker;\n} & OnSuccessCallback<T>;\n\n/**\n * Initializes the appropriate tracker for a given transaction based on its `tracker` type.\n * This function acts as a central router, delegating to the specific tracker implementation\n * (e.g., standard EVM, Gelato, or Safe).\n *\n * @template T - The application-specific transaction type, extending the base `Transaction`.\n * @param {InitializeTrackerParams<T>} params - The parameters for initializing the tracker.\n * @returns {Promise<void>} A promise that resolves once the tracking process has been successfully initiated.\n */\nexport async function checkAndInitializeTrackerInStore<T extends Transaction>({\n tracker,\n tx,\n config,\n transactionsPool,\n onSuccessCallback,\n ...rest\n}: InitializeTrackerParams<T>): Promise<void> {\n switch (tracker) {\n case TransactionTracker.Ethereum:\n return evmTrackerForStore({ tx, config, transactionsPool, onSuccessCallback, ...rest });\n\n case TransactionTracker.Gelato:\n // The Gelato tracker does not need the `chains` param as it uses its own API endpoints.\n return gelatoTrackerForStore({ tx, transactionsPool, onSuccessCallback, ...rest });\n\n case TransactionTracker.Safe:\n // The Safe tracker also uses its own API endpoints.\n return safeTrackerForStore({ tx, transactionsPool, onSuccessCallback, ...rest });\n\n // The default case handles any unknown or unspecified tracker types.\n // It logs a warning and treats them as standard EVM transactions.\n default:\n console.warn(`Unknown tracker type: '${tracker}'. Falling back to default EVM tracker.`);\n return evmTrackerForStore({ tx, config, transactionsPool, onSuccessCallback, ...rest });\n }\n}\n","/**\n * @file This file contains a utility function to determine the correct tracker for a transaction\n * based on the key returned by the submission function and the connector type.\n */\n\nimport { ActionTxKey, TransactionTracker } from '@tuwaio/pulsar-core';\nimport { isHex } from 'viem';\n\nimport { isGelatoTxKey } from '../trackers/gelatoTracker';\n\n/**\n * Determines which transaction tracker to use based on the format of the transaction key and the connector type.\n *\n * This function is a critical routing step after a transaction is submitted. It inspects\n * the key returned by the `actionFunction` and the connector type to decide the tracking strategy.\n * The logic follows a specific priority:\n * 1. Checks for a Gelato Task ID structure.\n * 2. Checks if the connector type indicates a Safe transaction.\n * 3. Defaults to the standard on-chain EVM hash tracker.\n *\n * @param {ActionTxKey} actionTxKey - The key returned from the transaction submission function (e.g., a hash or a Gelato task object).\n * @param {string} connectorType - The type of the connector that initiated the action (e.g., 'safe', 'injected').\n *\n * @returns {{ tracker: TransactionTracker; txKey: string }} An object containing the determined tracker type and the final string-based transaction key.\n *\n * @throws {Error} Throws an error if the `actionTxKey` is not a valid Hex string after failing the Gelato check.\n */\nexport function checkTransactionsTracker(\n actionTxKey: ActionTxKey,\n connectorType: string,\n): { tracker: TransactionTracker; txKey: string } {\n // 1. Highest priority: Check if the key matches the Gelato task structure.\n if (isGelatoTxKey(actionTxKey)) {\n return {\n tracker: TransactionTracker.Gelato,\n txKey: actionTxKey.taskId,\n };\n }\n\n // At this point, actionTxKey must be a Hex string (e.g., a transaction hash or SafeTxHash).\n // This check adds robustness in case of type mismatches.\n if (!isHex(actionTxKey)) {\n throw new Error(\n `Invalid transaction key format. Expected a Hex string or a GelatoTxKey object, but received: ${JSON.stringify(\n actionTxKey,\n )}`,\n );\n }\n\n // 2. Second priority: Check if the transaction came from a Safe wallet.\n // The check is case-insensitive for robustness.\n const splittingConnectorType = connectorType.split(':');\n if (\n splittingConnectorType.length > 1\n ? splittingConnectorType[splittingConnectorType.length - 1] === 'safe' ||\n splittingConnectorType[splittingConnectorType.length - 1] === 'safewallet'\n : connectorType?.toLowerCase() === 'safe'\n ) {\n return {\n tracker: TransactionTracker.Safe,\n txKey: actionTxKey,\n };\n }\n\n // 3. Default: Treat as a standard on-chain Ethereum transaction.\n return {\n tracker: TransactionTracker.Ethereum,\n txKey: actionTxKey,\n };\n}\n","/**\n * @file This file contains a selector utility for generating a block explorer URL for a given EVM transaction.\n */\n\nimport { OrbitAdapter } from '@tuwaio/orbit-core';\nimport { Transaction, TransactionTracker } from '@tuwaio/pulsar-core';\nimport { Chain } from 'viem';\n\nimport { gnosisSafeLinksHelper } from './safeConstants';\n\n/**\n * Generates a URL to a block explorer or Safe UI for a given transaction.\n * It handles different URL structures for standard EVM transactions and Safe multi-sig transactions.\n *\n * @template T - The transaction type, extending the base `Transaction`.\n *\n * @param {object} params - The parameters for the selection.\n * @param {TransactionPool<T>} params.transactionsPool - The entire pool of transactions from the store.\n * @param {Chain[]} params.chains - An array of supported chain objects, typically from `viem/chains`.\n * @param {Hex} params.txKey - The unique key (`txKey`) of the transaction for which to generate the link.\n * @param {Hex} [params.replacedTxHash] - Optional. If this is a speed-up/cancel transaction, this is the hash of the new transaction.\n *\n * @returns {string} The full URL to the transaction on the corresponding block explorer or Safe app,\n * or an empty string if the transaction or required chain configuration is not found.\n */\nexport const selectEvmTxExplorerLink = <T extends Transaction>({\n chains,\n tx,\n}: {\n chains: readonly [Chain, ...Chain[]];\n tx: T;\n}): string => {\n // Handle Safe transactions, which link to the Safe web app instead of a block explorer.\n if (tx.tracker === TransactionTracker.Safe) {\n const safeBaseUrl = gnosisSafeLinksHelper[tx.chainId as number];\n if (!safeBaseUrl) return '';\n\n return `${safeBaseUrl}${tx.from}/transactions/tx?id=multisig_${tx.from}_${tx.txKey}`;\n }\n\n // Handle standard EVM transactions.\n const chain = chains.find((c) => c.id === tx.chainId);\n const explorerUrl = chain?.blockExplorers?.default.url;\n\n if (!explorerUrl) {\n // Return empty string if the chain or its explorer URL is not configured.\n return '';\n }\n\n // Determine the correct hash to display. Prioritize the replaced hash for speed-up/cancel transactions.\n const hash =\n (tx.adapter === OrbitAdapter.EVM ? tx.replacedTxHash : tx.txKey) ||\n (tx.adapter === OrbitAdapter.EVM ? tx.hash : tx.txKey);\n\n if (!hash) return '';\n\n return `${explorerUrl}/tx/${hash}`;\n};\n","/**\n * @file This file contains a utility function for speeding up a pending EVM transaction.\n */\n\nimport { OrbitAdapter } from '@tuwaio/orbit-core';\nimport { Transaction } from '@tuwaio/pulsar-core';\nimport { Config, getAccount, sendTransaction } from '@wagmi/core';\nimport { Hex } from 'viem';\n\n// A common strategy is to increase gas by at least 10% to ensure replacement.\n// We use 15% for a higher chance of success.\nconst GAS_INCREASE_PERCENTAGE = 1.15;\n\n/**\n * Speeds up a pending EVM transaction by resubmitting it with the same nonce but higher gas fees.\n * This function is designed to work with wagmi's configuration and actions.\n *\n * @template T - The transaction type, which must be a valid EVM transaction.\n *\n * @param {object} params - The parameters required to speed up the transaction.\n * @param {Config} params.config - The wagmi configuration object.\n * @param {T} params.tx - The original transaction object that needs to be sped up. It must contain all necessary EVM fields.\n *\n * @returns {Promise<Hex>} A promise that resolves with the hash of the new, speed-up transaction.\n *\n * @throws {Error} Throws an error if:\n * - The transaction is not an EVM transaction.\n * - The transaction is missing required fields (`nonce`, `from`, `to`, `value`, `maxFeePerGas`, etc.).\n * - The wagmi config is not provided.\n * - No connected account is found.\n * - The `sendTransaction` call fails for any reason.\n *\n * @example\n * ```ts\n * const handleSpeedUp = async (stuckTransaction) => {\n * try {\n * const newTxHash = await speedUpTxAction({\n * config: wagmiConfig,\n * tx: stuckTransaction,\n * });\n * console.log('Transaction sped up with new hash:', newTxHash);\n * // You should now update your state to track this new transaction hash.\n * } catch (error) {\n * console.error('Failed to speed up transaction:', error);\n * }\n * };\n * ```\n */\nexport async function speedUpTxAction<T extends Transaction>({ config, tx }: { config: Config; tx: T }): Promise<Hex> {\n // 1. Validate the transaction type\n if (tx.adapter !== OrbitAdapter.EVM) {\n throw new Error(`Speed up is only available for EVM transactions. Received adapter type: '${tx.adapter}'.`);\n }\n\n // 2. Ensure all necessary transaction details are present.\n const { nonce, from, to, value, input, maxFeePerGas, maxPriorityFeePerGas, chainId } = tx;\n\n if (nonce === undefined || !from || !to || !value || !maxFeePerGas || !maxPriorityFeePerGas) {\n throw new Error('Transaction is missing required fields for speed-up.');\n }\n\n try {\n // 3. Verify wagmi configuration and connected account\n if (!config) {\n throw new Error('Wagmi config is not provided.');\n }\n const account = getAccount(config);\n if (!account.address) {\n throw new Error('No connected account found.');\n }\n\n // 4. Calculate new gas fees.\n // We increase both fees to ensure the new transaction replaces the old one.\n // Using floating point for calculation and converting back to BigInt at the end.\n const newPriorityFee = BigInt(Math.ceil(Number(maxPriorityFeePerGas) * GAS_INCREASE_PERCENTAGE));\n const newMaxFee = BigInt(Math.ceil(Number(maxFeePerGas) * GAS_INCREASE_PERCENTAGE));\n\n // 5. Resubmit the transaction with the same details but higher gas fees.\n return await sendTransaction(config, {\n to: to as Hex,\n value: BigInt(value),\n data: (input as Hex) || '0x',\n chainId: chainId as number,\n nonce: nonce,\n maxFeePerGas: newMaxFee,\n maxPriorityFeePerGas: newPriorityFee,\n });\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : String(e);\n // Re-throw the error with more context for easier debugging.\n throw new Error(`Failed to speed up transaction: ${errorMessage}`);\n }\n}\n","/**\n * @file This file contains the factory function for creating the EVM (Ethereum Virtual Machine) transaction adapter.\n * This adapter encapsulates all the logic required to interact with EVM-based chains using wagmi.\n */\n\nimport { getConnectorTypeFromName, lastConnectedConnectorHelpers, OrbitAdapter } from '@tuwaio/orbit-core';\nimport { checkAndSwitchChain } from '@tuwaio/orbit-evm';\nimport { Transaction, TransactionTracker, TxAdapter } from '@tuwaio/pulsar-core';\nimport { Config, getConnection } from '@wagmi/core';\nimport { Chain, zeroAddress } from 'viem';\n\nimport { cancelTxAction } from '../utils/cancelTxAction';\nimport { checkAndInitializeTrackerInStore } from '../utils/checkAndInitializeTrackerInStore';\nimport { checkTransactionsTracker } from '../utils/checkTransactionsTracker';\nimport { selectEvmTxExplorerLink } from '../utils/selectEvmTxExplorerLink';\nimport { speedUpTxAction } from '../utils/speedUpTxAction';\n\n/**\n * Creates an EVM-specific transaction adapter.\n *\n * This function acts as a constructor for the EVM adapter, bundling all the necessary\n * chain-specific utilities (like checking chain, ENS resolution, speeding up transactions, etc.)\n * into a single object that conforms to the `TxAdapter` interface.\n *\n * @template T - The application-specific transaction type.\n * @param {Config} config - The wagmi configuration object.\n * @param {Chain[]} appChains - An array of viem `Chain` objects supported by the application.\n *\n * @returns {TxAdapter<T>} The configured EVM transaction adapter.\n *\n * @throws {Error} Throws an error if the wagmi `config` is not provided.\n */\nexport function pulsarEvmAdapter<T extends Transaction>(\n config: Config,\n appChains: readonly [Chain, ...Chain[]],\n): TxAdapter<T> {\n if (!config) {\n throw new Error('EVM adapter requires a wagmi config object.');\n }\n\n return {\n key: OrbitAdapter.EVM,\n\n getConnectorInfo: () => {\n const activeConnection = getConnection(config);\n const localConnectedConnector = lastConnectedConnectorHelpers.getLastConnectedConnector();\n return {\n walletAddress: activeConnection.address ?? localConnectedConnector?.address ?? zeroAddress,\n connectorType: getConnectorTypeFromName(\n OrbitAdapter.EVM,\n activeConnection.connector?.name?.toLowerCase() ?? 'unknown',\n ),\n };\n },\n\n // --- Core Methods ---\n checkChainForTx: (chainId: string | number) => checkAndSwitchChain(chainId as number, config),\n checkTransactionsTracker: (actionTxKey, connectorType) => checkTransactionsTracker(actionTxKey, connectorType),\n checkAndInitializeTrackerInStore: ({ tx, ...rest }) =>\n checkAndInitializeTrackerInStore({ tracker: tx.tracker, tx, config, ...rest }),\n\n // --- UI & Explorer Methods ---\n getExplorerUrl: (url) => {\n const { chain } = getConnection(config);\n const baseExplorerLink = chain?.blockExplorers?.default.url;\n return url ? `${baseExplorerLink}/${url}` : baseExplorerLink;\n },\n getExplorerTxUrl: (tx) =>\n selectEvmTxExplorerLink({\n chains: appChains,\n tx,\n }),\n\n // --- Optional Actions ---\n cancelTxAction: (tx) => cancelTxAction({ config, tx: tx as T }),\n speedUpTxAction: (tx) => speedUpTxAction({ config, tx: tx as T }),\n retryTxAction: async ({ onClose, txKey, executeTxAction, tx }) => {\n onClose(txKey);\n\n if (!executeTxAction) {\n console.error('Retry failed: executeTxAction function is not provided.');\n return;\n }\n\n await executeTxAction({\n actionFunction: () => tx.actionFunction({ config, ...tx.payload }),\n params: tx,\n defaultTracker: TransactionTracker.Ethereum,\n });\n },\n };\n}\n","/**\n * @file This file contains a utility to check if the Gelato Relay service is available for a specific chain.\n */\n\n// --- In-memory cache to store the list of supported chains ---\nlet cachedRelayChainIds: number[] | null = null;\nlet cacheTimestamp: number | null = null;\nconst CACHE_DURATION_MS = 5 * 60 * 1000; // Cache the list for 5 minutes\nconst GELATO_API_URL = 'https://relay.gelato.digital/relays/v2/supported-chains';\n\n/**\n * Checks if the Gelato Relay service supports a given chain ID.\n *\n * This function fetches the list of supported chain IDs from the Gelato API and\n * caches the result in memory for 5 minutes to reduce network requests.\n *\n * @param {number} chainId - The chain identifier to check.\n * @returns {Promise<boolean>} A promise that resolves to `true` if Gelato supports the chain, `false` otherwise.\n */\nexport async function checkIsGelatoAvailable(chainId: number): Promise<boolean> {\n const now = Date.now();\n\n // 1. Check if a valid, non-expired cache exists.\n if (cachedRelayChainIds && cacheTimestamp && now - cacheTimestamp < CACHE_DURATION_MS) {\n return cachedRelayChainIds.includes(chainId);\n }\n\n // 2. If no valid cache, fetch the list from the Gelato API.\n try {\n const response = await fetch(GELATO_API_URL);\n\n if (!response.ok) {\n throw new Error(`Gelato API responded with status: ${response.status}`);\n }\n\n const data = (await response.json()) as { chains: string[] };\n // The endpoint returns an array of strings, which we convert to numbers.\n const supportedChainIds = data.chains.map(Number);\n\n // 3. Update the cache with the new data and timestamp.\n cachedRelayChainIds = supportedChainIds;\n cacheTimestamp = now;\n\n return supportedChainIds.includes(chainId);\n } catch (error) {\n console.error('Failed to fetch Gelato supported chains:', error);\n\n // In case of an error, clear the cache to allow for a retry on the next call.\n cachedRelayChainIds = null;\n cacheTimestamp = null;\n\n return false;\n }\n}\n"]}
|
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/cancelTxAction.ts","../src/trackers/evmTracker.ts","../src/trackers/gelatoTracker.ts","../src/utils/safeConstants.ts","../src/trackers/safeTracker.ts","../src/utils/checkAndInitializeTrackerInStore.ts","../src/utils/checkTransactionsTracker.ts","../src/utils/selectEvmTxExplorerLink.ts","../src/utils/speedUpTxAction.ts","../src/adapters/evmAdapter.ts","../src/utils/checkIsGelatoAvailable.ts"],"names":["GAS_INCREASE_PERCENTAGE","cancelTxAction","config","tx","OrbitAdapter","nonce","maxFeePerGas","maxPriorityFeePerGas","chainId","account","getAccount","newPriorityFee","newMaxFee","sendTransaction","e","errorMessage","DEFAULT_RETRY_COUNT","DEFAULT_RETRY_TIMEOUT_MS","evmTracker","params","onInitialize","onTxDetailsFetched","onSuccess","onFailure","onReplaced","retryCount","retryTimeout","waitForTransactionReceiptParams","zeroHash","client","getClient","txDetails","i","getTransaction","error","resolve","wasReplaced","receipt","waitForTransactionReceipt","replacement","evmTrackerForStore","updateTxParams","transactionsPool","onSuccessCallback","block","getBlock","timestamp","isSuccess","TransactionStatus","updatedTx","isGelatoTxKey","txKey","GelatoTaskState","GELATO_API_BASE_URL","GELATO_TERMINAL_FAILURE_STATES","isGelatoTxPending","gelatoStatus","gelatoFetcher","stopPolling","onIntervalTick","response","data","taskState","creationDate","dayjs","gelatoTrackerForStore","removeTxFromPool","initializePollingTracker","safeSdkOptions","gnosisSafeLinksHelper","mainnet","goerli","sepolia","polygon","arbitrum","aurora","avalanche","base","boba","bsc","celo","gnosis","optimism","polygonZkEvm","zksync","SafeTransactionServiceUrls","safeFetcher","baseUrl","primaryTxResponse","safeStatus","nonceTxsResponse","executedTx","t","safeTrackerForStore","checkAndInitializeTrackerInStore","tracker","rest","TransactionTracker","checkTransactionsTracker","actionTxKey","connectorType","isHex","splittingConnectorType","selectEvmTxExplorerLink","chains","safeBaseUrl","explorerUrl","c","hash","speedUpTxAction","from","to","value","input","pulsarEvmAdapter","appChains","activeConnection","getConnection","localConnectedConnector","lastConnectedConnectorHelpers","zeroAddress","getConnectorTypeFromName","checkAndSwitchChain","url","chain","baseExplorerLink","onClose","executeTxAction","cachedRelayChainIds","cacheTimestamp","CACHE_DURATION_MS","GELATO_API_URL","checkIsGelatoAvailable","now","supportedChainIds"],"mappings":"gmBAWA,IAAMA,CAAAA,CAA0B,IAAA,CAqChC,eAAsBC,CAAAA,CAAsC,CAAE,MAAA,CAAAC,CAAAA,CAAQ,EAAA,CAAAC,CAAG,CAAA,CAA4C,CAEnH,GAAIA,CAAAA,CAAG,OAAA,GAAYC,YAAAA,CAAa,GAAA,CAC9B,MAAM,IAAI,KAAA,CAAM,CAAA,6EAAA,EAAgFD,CAAAA,CAAG,OAAO,CAAA,EAA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mjs","sourcesContent":["/**\n * @file This file contains a utility function for canceling a pending EVM transaction.\n */\n\nimport { OrbitAdapter } from '@tuwaio/orbit-core';\nimport { Transaction } from '@tuwaio/pulsar-core';\nimport { Config, getAccount, sendTransaction } from '@wagmi/core';\nimport { Hex } from 'viem';\n\n// A common strategy is to increase gas by at least 10% to ensure replacement.\n// We use 15% for a higher chance of success.\nconst GAS_INCREASE_PERCENTAGE = 1.15;\n\n/**\n * Cancels a pending EVM transaction by sending a new, zero-value transaction to oneself\n * with the same nonce but higher gas fees. This effectively replaces the original transaction.\n *\n * @template T - The transaction type, which must be a valid EVM transaction.\n *\n * @param {object} params - The parameters required to cancel the transaction.\n * @param {Config} params.config - The wagmi configuration object.\n * @param {T} params.tx - The original transaction object to be canceled. It must contain the nonce and gas fee fields.\n *\n * @returns {Promise<Hex>} A promise that resolves with the hash of the new cancellation transaction.\n *\n * @throws {Error} Throws an error if:\n * - The transaction is not an EVM transaction.\n * - The transaction is missing required fields (`nonce`, `maxFeePerGas`, etc.).\n * - The wagmi config is not provided.\n * - No connected account is found.\n * - The `sendTransaction` call fails.\n *\n * @example\n * ```ts\n * const handleCancel = async (stuckTransaction) => {\n * try {\n * const cancelTxHash = await cancelTxAction({\n * config: wagmiConfig,\n * tx: stuckTransaction,\n * });\n * console.log('Cancellation transaction sent with hash:', cancelTxHash);\n * // You should now update your state to track this new transaction.\n * } catch (error) {\n * console.error('Failed to cancel transaction:', error);\n * }\n * };\n * ```\n */\nexport async function cancelTxAction<T extends Transaction>({ config, tx }: { config: Config; tx: T }): Promise<Hex> {\n // 1. Validate the transaction type\n if (tx.adapter !== OrbitAdapter.EVM) {\n throw new Error(`Cancellation is only available for EVM transactions. Received adapter type: '${tx.adapter}'.`);\n }\n\n // 2. Ensure all necessary transaction details are present.\n const { nonce, maxFeePerGas, maxPriorityFeePerGas, chainId } = tx;\n\n if (nonce === undefined || !maxFeePerGas || !maxPriorityFeePerGas) {\n throw new Error(\n 'Transaction is missing required fields for cancellation (nonce, maxFeePerGas, maxPriorityFeePerGas).',\n );\n }\n\n try {\n // 3. Verify wagmi configuration and connected account\n if (!config) {\n throw new Error('Wagmi config is not provided.');\n }\n const account = getAccount(config);\n if (!account.address) {\n throw new Error('No connected account found.');\n }\n\n // 4. Calculate new gas fees.\n const newPriorityFee = BigInt(Math.ceil(Number(maxPriorityFeePerGas) * GAS_INCREASE_PERCENTAGE));\n const newMaxFee = BigInt(Math.ceil(Number(maxFeePerGas) * GAS_INCREASE_PERCENTAGE));\n\n // 5. Send a zero-value transaction to your own address with the same nonce and higher gas.\n return await sendTransaction(config, {\n to: account.address,\n value: 0n,\n chainId: chainId as number,\n nonce: nonce,\n maxFeePerGas: newMaxFee,\n maxPriorityFeePerGas: newPriorityFee,\n });\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : String(e);\n // Re-throw the error with more context for easier debugging.\n throw new Error(`Failed to cancel transaction: ${errorMessage}`);\n }\n}\n","/**\n * @file This file contains the tracker implementation for standard EVM transactions.\n * It uses viem's public actions (`getTransaction`, `waitForTransactionReceipt`) to monitor\n * a transaction's lifecycle from submission to finality.\n */\n\nimport { ITxTrackingStore, OnSuccessCallback, Transaction, TransactionStatus } from '@tuwaio/pulsar-core';\nimport { Config, getClient } from '@wagmi/core';\nimport {\n Client,\n GetTransactionReturnType,\n Hex,\n ReplacementReturnType,\n TransactionReceipt,\n WaitForTransactionReceiptParameters,\n zeroHash,\n} from 'viem';\nimport { getBlock, getTransaction, waitForTransactionReceipt } from 'viem/actions';\n\nconst DEFAULT_RETRY_COUNT = 10;\nconst DEFAULT_RETRY_TIMEOUT_MS = 3000;\n\n/**\n * Defines the parameters for the low-level EVM transaction tracker.\n */\nexport type EVMTrackerParams = {\n tx: Pick<Transaction, 'chainId' | 'txKey'>;\n config: Config;\n onTxDetailsFetched: (txDetails: GetTransactionReturnType) => void;\n onSuccess: (txDetails: GetTransactionReturnType, receipt: TransactionReceipt, client: Client) => Promise<void>;\n onReplaced: (replacement: ReplacementReturnType) => void;\n onFailure: (error?: unknown) => void;\n onInitialize?: () => void;\n retryCount?: number;\n retryTimeout?: number;\n waitForTransactionReceiptParams?: WaitForTransactionReceiptParameters;\n};\n\n/**\n * A low-level tracker for monitoring a standard EVM transaction by its hash.\n * It retries fetching the transaction and then waits for its receipt to determine the final status.\n *\n * @param {EVMTrackerParams} params - The configuration object for the tracker.\n */\nexport async function evmTracker(params: EVMTrackerParams): Promise<void> {\n const {\n tx,\n config,\n onInitialize,\n onTxDetailsFetched,\n onSuccess,\n onFailure,\n onReplaced,\n retryCount = DEFAULT_RETRY_COUNT,\n retryTimeout = DEFAULT_RETRY_TIMEOUT_MS,\n waitForTransactionReceiptParams,\n } = params;\n\n onInitialize?.();\n\n if (tx.txKey === zeroHash) {\n return onFailure(new Error('Transaction hash cannot be the zero hash.'));\n }\n\n const client = getClient(config, { chainId: tx.chainId as number });\n if (!client) {\n return onFailure(new Error(`Could not create a viem client for chainId: ${tx.chainId}`));\n }\n\n let txDetails: GetTransactionReturnType | null = null;\n\n // 1. Retry loop to fetch the transaction details.\n // This handles cases where the transaction is not immediately available on the RPC node.\n for (let i = 0; i < retryCount; i++) {\n try {\n txDetails = await getTransaction(client, { hash: tx.txKey as Hex });\n onTxDetailsFetched(txDetails);\n break; // Exit loop on success\n } catch (error) {\n if (i === retryCount - 1) {\n console.error(`EVM tracker failed to fetch tx ${tx.txKey} after ${retryCount} retries:`, error);\n return onFailure(error);\n }\n await new Promise((resolve) => setTimeout(resolve, retryTimeout));\n }\n }\n\n if (!txDetails) {\n // This should theoretically not be reached if the loop completes, but it's a good safeguard.\n return onFailure(new Error('Transaction details could not be fetched.'));\n }\n\n // 2. Wait for the transaction to be mined and get the receipt.\n try {\n let wasReplaced = false;\n const receipt = await waitForTransactionReceipt(client, {\n hash: txDetails.hash,\n onReplaced: (replacement) => {\n wasReplaced = true;\n onReplaced(replacement);\n },\n ...waitForTransactionReceiptParams,\n });\n\n // If onReplaced was called, the promise resolves but we should not proceed to onSuccess.\n if (wasReplaced) {\n return;\n }\n\n // 3. Transaction is mined, call the onSuccess callback.\n await onSuccess(txDetails, receipt, client);\n } catch (error) {\n console.error(`Error waiting for receipt for tx ${tx.txKey}:`, error);\n onFailure(error);\n }\n}\n\n/**\n * A higher-level wrapper for `evmTracker` that integrates directly with the Pulsar store.\n * It provides the necessary callbacks to update a transaction's state throughout its lifecycle.\n *\n * @template T - The application-specific transaction type.\n */\nexport async function evmTrackerForStore<T extends Transaction>(\n params: Pick<EVMTrackerParams, 'config'> &\n Pick<ITxTrackingStore<T>, 'updateTxParams' | 'transactionsPool'> & {\n tx: T;\n } & OnSuccessCallback<T>,\n) {\n const { tx, config, updateTxParams, transactionsPool, onSuccessCallback } = params;\n\n return evmTracker({\n tx,\n config,\n onInitialize: () => {\n // Set the initial hash, which is the same as the txKey for this tracker.\n updateTxParams(tx.txKey, { hash: tx.txKey as Hex });\n },\n onTxDetailsFetched: (txDetails) => {\n // Once we fetch details from the node, update the transaction with more info.\n updateTxParams(tx.txKey, {\n to: txDetails.to ?? undefined,\n input: txDetails.input,\n value: txDetails.value?.toString(),\n nonce: txDetails.nonce,\n maxFeePerGas: txDetails.maxFeePerGas?.toString(),\n maxPriorityFeePerGas: txDetails.maxPriorityFeePerGas?.toString(),\n });\n },\n onSuccess: async (txDetails, receipt, client) => {\n const block = await getBlock(client, { blockNumber: receipt.blockNumber });\n const timestamp = Number(block.timestamp);\n const isSuccess = receipt.status === 'success';\n\n updateTxParams(tx.txKey, {\n status: isSuccess ? TransactionStatus.Success : TransactionStatus.Failed,\n isError: !isSuccess,\n pending: false,\n finishedTimestamp: timestamp,\n });\n\n // After the final state update, retrieve the latest version of the transaction\n // and trigger the global success callback if applicable.\n const updatedTx = transactionsPool[tx.txKey];\n if (isSuccess && onSuccessCallback && updatedTx) {\n onSuccessCallback(updatedTx);\n }\n },\n onReplaced: (replacement) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Replaced,\n replacedTxHash: replacement.transaction.hash,\n pending: false,\n });\n },\n onFailure: (error) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Failed,\n pending: false,\n isError: true,\n errorMessage: error instanceof Error ? error.message : 'Transaction failed or could not be tracked.',\n });\n },\n });\n}\n","/**\n * @file This file implements the transaction tracking logic for meta-transactions relayed via the Gelato Network.\n * It uses a polling mechanism to check the status of a Gelato Task ID from the Gelato API.\n */\n\nimport {\n ActionTxKey,\n GelatoTxKey,\n initializePollingTracker,\n ITxTrackingStore,\n OnSuccessCallback,\n PollingTrackerConfig,\n Transaction,\n TransactionStatus,\n} from '@tuwaio/pulsar-core';\nimport dayjs from 'dayjs';\nimport { Hex } from 'viem';\n\n// =================================================================================================\n// 1. TYPES AND TYPE GUARDS\n// =================================================================================================\n\n/**\n * A type guard to determine if an ActionTxKey is a GelatoTxKey.\n * @param {ActionTxKey} txKey - The transaction key to check.\n * @returns {boolean} True if the key is for a Gelato transaction.\n */\nexport function isGelatoTxKey(txKey: ActionTxKey): txKey is GelatoTxKey {\n return typeof txKey === 'object' && txKey !== null && 'taskId' in txKey;\n}\n\n/**\n * Enum representing the possible states of a Gelato task.\n * @see https://docs.gelato.network/developer-services/relay/api/get-task-status\n */\nexport enum GelatoTaskState {\n CheckPending = 'CheckPending',\n ExecPending = 'ExecPending',\n WaitingForConfirmation = 'WaitingForConfirmation',\n ExecSuccess = 'ExecSuccess',\n ExecReverted = 'ExecReverted',\n Cancelled = 'Cancelled',\n NotFound = 'NotFound',\n}\n\n/**\n * Defines the shape of the response from the Gelato `getTaskStatus` API endpoint.\n */\nexport type GelatoTaskStatusResponse = {\n task: {\n chainId: number;\n taskId: string;\n taskState: GelatoTaskState;\n creationDate?: string;\n executionDate?: string;\n transactionHash?: Hex;\n blockNumber?: number;\n lastCheckMessage?: string;\n };\n};\n\nconst GELATO_API_BASE_URL = 'https://api.gelato.digital/tasks/status/';\n\n// =================================================================================================\n// 2. HELPER FUNCTIONS\n// =================================================================================================\n\nconst GELATO_TERMINAL_FAILURE_STATES = new Set([\n GelatoTaskState.ExecReverted,\n GelatoTaskState.Cancelled,\n GelatoTaskState.NotFound,\n]);\n\nfunction isGelatoTxPending(gelatoStatus: GelatoTaskState): boolean {\n return gelatoStatus !== GelatoTaskState.ExecSuccess && !GELATO_TERMINAL_FAILURE_STATES.has(gelatoStatus);\n}\n\n// =================================================================================================\n// 3. FETCHER IMPLEMENTATION\n// =================================================================================================\n\n/**\n * A reusable fetcher function for `initializePollingTracker` that queries the Gelato API for a task's status.\n * It handles the logic for interpreting Gelato's task states and calls the appropriate polling callbacks.\n */\nexport const gelatoFetcher: PollingTrackerConfig<GelatoTaskStatusResponse, Transaction>['fetcher'] = async ({\n tx,\n stopPolling,\n onSuccess,\n onFailure,\n onIntervalTick,\n}) => {\n const response = await fetch(`${GELATO_API_BASE_URL}${tx.txKey}`);\n\n if (!response.ok) {\n if (response.status === 404) {\n onFailure(); // Treat 404 as a terminal failure.\n stopPolling();\n return;\n }\n // For other errors, let the polling tracker's retry mechanism handle it.\n throw new Error(`Gelato API responded with status: ${response.status}`);\n }\n\n const data = (await response.json()) as GelatoTaskStatusResponse;\n const { taskState, creationDate } = data.task;\n\n onIntervalTick?.(data);\n\n // Safeguard: Stop polling for tasks that have been pending for over a hour.\n if (creationDate && dayjs().diff(dayjs(creationDate), 'hour') >= 1 && isGelatoTxPending(taskState)) {\n stopPolling();\n return;\n }\n\n // Check for terminal states to stop the polling.\n if (taskState === GelatoTaskState.ExecSuccess) {\n onSuccess(data);\n stopPolling({ withoutRemoving: true });\n } else if (GELATO_TERMINAL_FAILURE_STATES.has(taskState)) {\n onFailure(data);\n stopPolling({ withoutRemoving: true });\n }\n};\n\n// =================================================================================================\n// 4. STORE-CONNECTED TRACKER\n// =================================================================================================\n\n/**\n * A higher-level wrapper that integrates the Gelato polling logic with the Pulsar store.\n * It uses the generic `gelatoFetcher` and provides store-specific callbacks.\n *\n * @template T - The application-specific transaction type.\n */\nexport function gelatoTrackerForStore<T extends Transaction>({\n tx,\n updateTxParams,\n removeTxFromPool,\n transactionsPool,\n onSuccessCallback,\n}: Pick<ITxTrackingStore<T>, 'updateTxParams' | 'removeTxFromPool' | 'transactionsPool'> & {\n tx: T;\n} & OnSuccessCallback<T>) {\n return initializePollingTracker<GelatoTaskStatusResponse, T>({\n tx,\n fetcher: gelatoFetcher, // Use the exported, reusable fetcher\n removeTxFromPool,\n onSuccess: (response) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Success,\n pending: false,\n isError: false,\n hash: response.task.transactionHash,\n finishedTimestamp: response.task.executionDate ? dayjs(response.task.executionDate).unix() : undefined,\n });\n\n const updatedTx = transactionsPool[tx.txKey];\n if (onSuccessCallback && updatedTx) {\n onSuccessCallback(updatedTx);\n }\n },\n onIntervalTick: (response) => {\n updateTxParams(tx.txKey, {\n hash: response.task.transactionHash,\n });\n },\n onFailure: (response) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Failed,\n pending: false,\n isError: true,\n hash: response?.task.transactionHash,\n errorMessage: response?.task.lastCheckMessage ?? 'Transaction failed or was not found.',\n finishedTimestamp: response?.task.executionDate ? dayjs(response.task.executionDate).unix() : undefined,\n });\n },\n });\n}\n","/**\n * @file This file contains constants related to Safe (formerly Gnosis Safe) configuration,\n * including SDK options, web app URLs, and transaction service API endpoints for various chains.\n */\n\nimport {\n arbitrum,\n aurora,\n avalanche,\n base,\n boba,\n bsc,\n celo,\n gnosis,\n goerli,\n mainnet,\n optimism,\n polygon,\n polygonZkEvm,\n sepolia,\n zksync,\n} from 'viem/chains';\n\n/**\n * Configuration options for the Safe Apps SDK.\n * This is typically used when integrating with the Safe environment.\n */\nexport const safeSdkOptions = {\n // A list of allowed domains to interact with the Safe Apps SDK.\n allowedDomains: [/gnosis-safe.io$/, /app.safe.global$/, /metissafe.tech$/],\n // A flag to enable or disable debug logging for the SDK.\n debug: false,\n};\n\n/**\n * A mapping of chain IDs to their corresponding Safe web application URL prefixes.\n * Used by selectors like `selectTxExplorerLink` to build correct links for Safe transactions.\n * The prefixes (e.g., 'eth:', 'gor:') are part of the Safe URL scheme.\n * @type {Record<number, string>}\n */\nexport const gnosisSafeLinksHelper: Record<number, string> = {\n [mainnet.id]: 'https://app.safe.global/eth:',\n [goerli.id]: 'https://app.safe.global/gor:',\n [sepolia.id]: 'https://app.safe.global/sep:',\n [polygon.id]: 'https://app.safe.global/matic:',\n [arbitrum.id]: 'https://app.safe.global/arb1:',\n [aurora.id]: 'https://app.safe.global/aurora:',\n [avalanche.id]: 'https://app.safe.global/avax:',\n [base.id]: 'https://app.safe.global/base:',\n [boba.id]: 'https://app.safe.global/boba:',\n [bsc.id]: 'https://app.safe.global/bnb:',\n [celo.id]: 'https://app.safe.global/celo:',\n [gnosis.id]: 'https://app.safe.global/gno:',\n [optimism.id]: 'https://app.safe.global/oeth:',\n [polygonZkEvm.id]: 'https://app.safe.global/zkevm:',\n [zksync.id]: 'https://app.safe.global/zksync:',\n};\n\n/**\n * A comprehensive mapping of chain IDs to their corresponding Safe Transaction Service API endpoints.\n * This is used by the `safeTracker` to fetch the status of multisig transactions from the correct service.\n * @type {Record<number, string>}\n */\nexport const SafeTransactionServiceUrls: Record<number, string> = {\n [mainnet.id]: 'https://safe-transaction-mainnet.safe.global/api/v1',\n [goerli.id]: 'https://safe-transaction-goerli.safe.global/api/v1',\n [sepolia.id]: 'https://safe-transaction-sepolia.safe.global/api/v1',\n [polygon.id]: 'https://safe-transaction-polygon.safe.global/api/v1',\n [arbitrum.id]: 'https://safe-transaction-arbitrum.safe.global/api/v1',\n [aurora.id]: 'https://safe-transaction-aurora.safe.global/api/v1',\n [avalanche.id]: 'https://safe-transaction-avalanche.safe.global/api/v1',\n [base.id]: 'https://safe-transaction-base.safe.global/api/v1',\n [boba.id]: 'https://safe-transaction-boba.safe.global/api/v1',\n [bsc.id]: 'https://safe-transaction-bsc.safe.global/api/v1',\n [celo.id]: 'https://safe-transaction-celo.safe.global/api/v1',\n [gnosis.id]: 'https://safe-transaction-gnosis-chain.safe.global/api/v1',\n [optimism.id]: 'https://safe-transaction-optimism.safe.global/api/v1',\n [polygonZkEvm.id]: 'https://safe-transaction-zkevm.safe.global/api/v1',\n [zksync.id]: 'https://safe-transaction-zksync.safe.global/api/v1',\n};\n","/**\n * @file This file implements the transaction tracking logic for Safe (formerly Gnosis Safe) multisig transactions.\n * It uses a polling mechanism to query the Safe Transaction Service API for the status of a `safeTxHash`.\n */\n\nimport { OrbitAdapter } from '@tuwaio/orbit-core';\nimport {\n initializePollingTracker,\n ITxTrackingStore,\n OnSuccessCallback,\n PollingTrackerConfig,\n Transaction,\n TransactionStatus,\n} from '@tuwaio/pulsar-core';\nimport dayjs from 'dayjs';\nimport { Hex, zeroHash } from 'viem';\n\nimport { SafeTransactionServiceUrls } from '../utils/safeConstants';\n\n// =================================================================================================\n// 1. TYPES\n// =================================================================================================\n\n/**\n * Defines the shape of the primary response for a single transaction from the Safe Transaction Service API.\n */\nexport type SafeTxStatusResponse = {\n transactionHash: Hex | null;\n safeTxHash: Hex;\n isExecuted: boolean;\n isSuccessful: boolean | null;\n executionDate: string | null;\n submissionDate: string;\n modified: string;\n nonce: number;\n};\n\n/**\n * The response shape when querying for multiple transactions (e.g., by nonce).\n */\ntype SafeTxSameNonceResponse = {\n count: number;\n results: SafeTxStatusResponse[];\n};\n\n// =================================================================================================\n// 2. FETCHER IMPLEMENTATION\n// =================================================================================================\n\n/**\n * A reusable fetcher for `initializePollingTracker` that queries the Safe Transaction Service API.\n * It handles the complex logic of detecting executed, failed, and replaced multisig transactions.\n */\nexport const safeFetcher: PollingTrackerConfig<SafeTxStatusResponse, Transaction>['fetcher'] = async ({\n tx,\n stopPolling,\n onSuccess,\n onFailure,\n onReplaced,\n onIntervalTick,\n}) => {\n const baseUrl = SafeTransactionServiceUrls[tx.chainId as number];\n if (!baseUrl) {\n throw new Error(`Safe Transaction Service URL not found for chainId: ${tx.chainId}`);\n }\n\n // 1. Fetch the status of the primary transaction.\n const primaryTxResponse = await fetch(`${baseUrl}/multisig-transactions/${tx.txKey}/`);\n if (!primaryTxResponse.ok) {\n // Treat 404 as a terminal failure (transaction is lost).\n if (primaryTxResponse.status === 404) {\n onFailure();\n stopPolling();\n }\n throw new Error(`Safe API responded with status: ${primaryTxResponse.status}`);\n }\n const safeStatus = (await primaryTxResponse.json()) as SafeTxStatusResponse;\n onIntervalTick?.(safeStatus);\n\n // 2. Check if the primary transaction itself has been executed.\n if (safeStatus.isExecuted) {\n if (safeStatus.isSuccessful) {\n onSuccess(safeStatus);\n } else {\n onFailure(safeStatus);\n }\n stopPolling({ withoutRemoving: true });\n return;\n }\n\n // 3. If still pending, check for replacements.\n // This is necessary because another transaction with the same nonce might have been executed.\n const nonceTxsResponse = await fetch(`${baseUrl}/safes/${tx.from}/multisig-transactions/?nonce=${safeStatus.nonce}`);\n if (!nonceTxsResponse.ok) {\n throw new Error(`Safe API (nonce check) responded with status: ${nonceTxsResponse.status}`);\n }\n const sameNonceTxs = (await nonceTxsResponse.json()) as SafeTxSameNonceResponse;\n const executedTx = sameNonceTxs.results.find((t) => t.isExecuted);\n\n if (executedTx) {\n // If an executed transaction exists and it's not ours, our transaction was replaced.\n onReplaced?.(executedTx);\n stopPolling({ withoutRemoving: true });\n return;\n }\n\n // 4. Safeguard: Stop polling for very old pending transactions.\n if (dayjs().diff(dayjs(safeStatus.submissionDate), 'day') >= 1) {\n stopPolling();\n }\n};\n\n// =================================================================================================\n// 3. STORE-CONNECTED TRACKER\n// =================================================================================================\n\n/**\n * A higher-level wrapper that integrates the Safe polling logic with the Pulsar store.\n * It uses the generic `safeFetcher` and provides store-specific callbacks.\n *\n * @template T - The application-specific transaction type.\n */\nexport function safeTrackerForStore<T extends Transaction>({\n tx,\n updateTxParams,\n removeTxFromPool,\n transactionsPool,\n onSuccessCallback,\n}: Pick<ITxTrackingStore<T>, 'updateTxParams' | 'removeTxFromPool' | 'transactionsPool'> & {\n tx: T;\n} & OnSuccessCallback<T>) {\n return initializePollingTracker<SafeTxStatusResponse, T>({\n tx,\n fetcher: safeFetcher,\n removeTxFromPool,\n onSuccess: (response) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Success,\n pending: false,\n isError: false,\n hash: response.transactionHash ?? undefined,\n finishedTimestamp: response.executionDate ? dayjs(response.executionDate).unix() : undefined,\n });\n\n const updatedTx = transactionsPool[tx.txKey];\n if (onSuccessCallback && updatedTx) {\n onSuccessCallback(updatedTx);\n }\n },\n onIntervalTick: (response) => {\n // Only update fields that might change while pending.\n updateTxParams(tx.txKey, {\n hash: response.transactionHash ?? undefined,\n });\n },\n onFailure: (response) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Failed,\n pending: false,\n isError: true,\n hash: response?.transactionHash ?? undefined,\n errorMessage: response ? 'Safe transaction failed or was rejected.' : 'Transaction not found.',\n finishedTimestamp: response?.executionDate ? dayjs(response.executionDate).unix() : undefined,\n });\n },\n onReplaced: (response) => {\n updateTxParams(tx.txKey, {\n status: TransactionStatus.Replaced,\n pending: false,\n hash: tx.adapter === OrbitAdapter.EVM ? tx.hash : zeroHash,\n // The `replacedTxHash` is the `safeTxHash` of the transaction that was executed instead.\n replacedTxHash: response.safeTxHash ?? zeroHash,\n finishedTimestamp: response.executionDate ? dayjs(response.executionDate).unix() : undefined,\n });\n },\n });\n}\n","/**\n * @file This file contains a utility function that acts as a router to initialize the correct transaction tracker.\n * Based on a transaction's `tracker` property, it delegates the tracking task to the appropriate implementation.\n */\n\nimport { ITxTrackingStore, OnSuccessCallback, Transaction, TransactionTracker } from '@tuwaio/pulsar-core';\nimport { Config } from '@wagmi/core';\n\nimport { evmTrackerForStore } from '../trackers/evmTracker';\nimport { gelatoTrackerForStore } from '../trackers/gelatoTracker';\nimport { safeTrackerForStore } from '../trackers/safeTracker';\n\n/**\n * The parameters required to initialize a tracker.\n * @template T - The application-specific transaction type.\n */\ntype InitializeTrackerParams<T extends Transaction> = Pick<\n ITxTrackingStore<T>,\n 'updateTxParams' | 'removeTxFromPool' | 'transactionsPool'\n> & {\n config: Config;\n tx: T;\n tracker: TransactionTracker;\n} & OnSuccessCallback<T>;\n\n/**\n * Initializes the appropriate tracker for a given transaction based on its `tracker` type.\n * This function acts as a central router, delegating to the specific tracker implementation\n * (e.g., standard EVM, Gelato, or Safe).\n *\n * @template T - The application-specific transaction type, extending the base `Transaction`.\n * @param {InitializeTrackerParams<T>} params - The parameters for initializing the tracker.\n * @returns {Promise<void>} A promise that resolves once the tracking process has been successfully initiated.\n */\nexport async function checkAndInitializeTrackerInStore<T extends Transaction>({\n tracker,\n tx,\n config,\n transactionsPool,\n onSuccessCallback,\n ...rest\n}: InitializeTrackerParams<T>): Promise<void> {\n switch (tracker) {\n case TransactionTracker.Ethereum:\n return evmTrackerForStore({ tx, config, transactionsPool, onSuccessCallback, ...rest });\n\n case TransactionTracker.Gelato:\n // The Gelato tracker does not need the `chains` param as it uses its own API endpoints.\n return gelatoTrackerForStore({ tx, transactionsPool, onSuccessCallback, ...rest });\n\n case TransactionTracker.Safe:\n // The Safe tracker also uses its own API endpoints.\n return safeTrackerForStore({ tx, transactionsPool, onSuccessCallback, ...rest });\n\n // The default case handles any unknown or unspecified tracker types.\n // It logs a warning and treats them as standard EVM transactions.\n default:\n console.warn(`Unknown tracker type: '${tracker}'. Falling back to default EVM tracker.`);\n return evmTrackerForStore({ tx, config, transactionsPool, onSuccessCallback, ...rest });\n }\n}\n","/**\n * @file This file contains a utility function to determine the correct tracker for a transaction\n * based on the key returned by the submission function and the connector type.\n */\n\nimport { ActionTxKey, TransactionTracker } from '@tuwaio/pulsar-core';\nimport { isHex } from 'viem';\n\nimport { isGelatoTxKey } from '../trackers/gelatoTracker';\n\n/**\n * Determines which transaction tracker to use based on the format of the transaction key and the connector type.\n *\n * This function is a critical routing step after a transaction is submitted. It inspects\n * the key returned by the `actionFunction` and the connector type to decide the tracking strategy.\n * The logic follows a specific priority:\n * 1. Checks for a Gelato Task ID structure.\n * 2. Checks if the connector type indicates a Safe transaction.\n * 3. Defaults to the standard on-chain EVM hash tracker.\n *\n * @param {ActionTxKey} actionTxKey - The key returned from the transaction submission function (e.g., a hash or a Gelato task object).\n * @param {string} connectorType - The type of the connector that initiated the action (e.g., 'safe', 'injected').\n *\n * @returns {{ tracker: TransactionTracker; txKey: string }} An object containing the determined tracker type and the final string-based transaction key.\n *\n * @throws {Error} Throws an error if the `actionTxKey` is not a valid Hex string after failing the Gelato check.\n */\nexport function checkTransactionsTracker(\n actionTxKey: ActionTxKey,\n connectorType: string,\n): { tracker: TransactionTracker; txKey: string } {\n // 1. Highest priority: Check if the key matches the Gelato task structure.\n if (isGelatoTxKey(actionTxKey)) {\n return {\n tracker: TransactionTracker.Gelato,\n txKey: actionTxKey.taskId,\n };\n }\n\n // At this point, actionTxKey must be a Hex string (e.g., a transaction hash or SafeTxHash).\n // This check adds robustness in case of type mismatches.\n if (!isHex(actionTxKey)) {\n throw new Error(\n `Invalid transaction key format. Expected a Hex string or a GelatoTxKey object, but received: ${JSON.stringify(\n actionTxKey,\n )}`,\n );\n }\n\n // 2. Second priority: Check if the transaction came from a Safe wallet.\n // The check is case-insensitive for robustness.\n const splittingConnectorType = connectorType.split(':');\n if (\n splittingConnectorType.length > 1\n ? splittingConnectorType[splittingConnectorType.length - 1] === 'safe' ||\n splittingConnectorType[splittingConnectorType.length - 1] === 'safewallet'\n : connectorType?.toLowerCase() === 'safe'\n ) {\n return {\n tracker: TransactionTracker.Safe,\n txKey: actionTxKey,\n };\n }\n\n // 3. Default: Treat as a standard on-chain Ethereum transaction.\n return {\n tracker: TransactionTracker.Ethereum,\n txKey: actionTxKey,\n };\n}\n","/**\n * @file This file contains a selector utility for generating a block explorer URL for a given EVM transaction.\n */\n\nimport { OrbitAdapter } from '@tuwaio/orbit-core';\nimport { Transaction, TransactionTracker } from '@tuwaio/pulsar-core';\nimport { Chain } from 'viem';\n\nimport { gnosisSafeLinksHelper } from './safeConstants';\n\n/**\n * Generates a URL to a block explorer or Safe UI for a given transaction.\n * It handles different URL structures for standard EVM transactions and Safe multi-sig transactions.\n *\n * @template T - The transaction type, extending the base `Transaction`.\n *\n * @param {object} params - The parameters for the selection.\n * @param {TransactionPool<T>} params.transactionsPool - The entire pool of transactions from the store.\n * @param {Chain[]} params.chains - An array of supported chain objects, typically from `viem/chains`.\n * @param {Hex} params.txKey - The unique key (`txKey`) of the transaction for which to generate the link.\n * @param {Hex} [params.replacedTxHash] - Optional. If this is a speed-up/cancel transaction, this is the hash of the new transaction.\n *\n * @returns {string} The full URL to the transaction on the corresponding block explorer or Safe app,\n * or an empty string if the transaction or required chain configuration is not found.\n */\nexport const selectEvmTxExplorerLink = <T extends Transaction>({\n chains,\n tx,\n}: {\n chains: readonly [Chain, ...Chain[]];\n tx: T;\n}): string => {\n // Handle Safe transactions, which link to the Safe web app instead of a block explorer.\n if (tx.tracker === TransactionTracker.Safe) {\n const safeBaseUrl = gnosisSafeLinksHelper[tx.chainId as number];\n if (!safeBaseUrl) return '';\n\n return `${safeBaseUrl}${tx.from}/transactions/tx?id=multisig_${tx.from}_${tx.txKey}`;\n }\n\n // Handle standard EVM transactions.\n const chain = chains.find((c) => c.id === tx.chainId);\n const explorerUrl = chain?.blockExplorers?.default.url;\n\n if (!explorerUrl) {\n // Return empty string if the chain or its explorer URL is not configured.\n return '';\n }\n\n // Determine the correct hash to display. Prioritize the replaced hash for speed-up/cancel transactions.\n const hash =\n (tx.adapter === OrbitAdapter.EVM ? tx.replacedTxHash : tx.txKey) ||\n (tx.adapter === OrbitAdapter.EVM ? tx.hash : tx.txKey);\n\n if (!hash) return '';\n\n return `${explorerUrl}/tx/${hash}`;\n};\n","/**\n * @file This file contains a utility function for speeding up a pending EVM transaction.\n */\n\nimport { OrbitAdapter } from '@tuwaio/orbit-core';\nimport { Transaction } from '@tuwaio/pulsar-core';\nimport { Config, getAccount, sendTransaction } from '@wagmi/core';\nimport { Hex } from 'viem';\n\n// A common strategy is to increase gas by at least 10% to ensure replacement.\n// We use 15% for a higher chance of success.\nconst GAS_INCREASE_PERCENTAGE = 1.15;\n\n/**\n * Speeds up a pending EVM transaction by resubmitting it with the same nonce but higher gas fees.\n * This function is designed to work with wagmi's configuration and actions.\n *\n * @template T - The transaction type, which must be a valid EVM transaction.\n *\n * @param {object} params - The parameters required to speed up the transaction.\n * @param {Config} params.config - The wagmi configuration object.\n * @param {T} params.tx - The original transaction object that needs to be sped up. It must contain all necessary EVM fields.\n *\n * @returns {Promise<Hex>} A promise that resolves with the hash of the new, speed-up transaction.\n *\n * @throws {Error} Throws an error if:\n * - The transaction is not an EVM transaction.\n * - The transaction is missing required fields (`nonce`, `from`, `to`, `value`, `maxFeePerGas`, etc.).\n * - The wagmi config is not provided.\n * - No connected account is found.\n * - The `sendTransaction` call fails for any reason.\n *\n * @example\n * ```ts\n * const handleSpeedUp = async (stuckTransaction) => {\n * try {\n * const newTxHash = await speedUpTxAction({\n * config: wagmiConfig,\n * tx: stuckTransaction,\n * });\n * console.log('Transaction sped up with new hash:', newTxHash);\n * // You should now update your state to track this new transaction hash.\n * } catch (error) {\n * console.error('Failed to speed up transaction:', error);\n * }\n * };\n * ```\n */\nexport async function speedUpTxAction<T extends Transaction>({ config, tx }: { config: Config; tx: T }): Promise<Hex> {\n // 1. Validate the transaction type\n if (tx.adapter !== OrbitAdapter.EVM) {\n throw new Error(`Speed up is only available for EVM transactions. Received adapter type: '${tx.adapter}'.`);\n }\n\n // 2. Ensure all necessary transaction details are present.\n const { nonce, from, to, value, input, maxFeePerGas, maxPriorityFeePerGas, chainId } = tx;\n\n if (nonce === undefined || !from || !to || !value || !maxFeePerGas || !maxPriorityFeePerGas) {\n throw new Error('Transaction is missing required fields for speed-up.');\n }\n\n try {\n // 3. Verify wagmi configuration and connected account\n if (!config) {\n throw new Error('Wagmi config is not provided.');\n }\n const account = getAccount(config);\n if (!account.address) {\n throw new Error('No connected account found.');\n }\n\n // 4. Calculate new gas fees.\n // We increase both fees to ensure the new transaction replaces the old one.\n // Using floating point for calculation and converting back to BigInt at the end.\n const newPriorityFee = BigInt(Math.ceil(Number(maxPriorityFeePerGas) * GAS_INCREASE_PERCENTAGE));\n const newMaxFee = BigInt(Math.ceil(Number(maxFeePerGas) * GAS_INCREASE_PERCENTAGE));\n\n // 5. Resubmit the transaction with the same details but higher gas fees.\n return await sendTransaction(config, {\n to: to as Hex,\n value: BigInt(value),\n data: (input as Hex) || '0x',\n chainId: chainId as number,\n nonce: nonce,\n maxFeePerGas: newMaxFee,\n maxPriorityFeePerGas: newPriorityFee,\n });\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : String(e);\n // Re-throw the error with more context for easier debugging.\n throw new Error(`Failed to speed up transaction: ${errorMessage}`);\n }\n}\n","/**\n * @file This file contains the factory function for creating the EVM (Ethereum Virtual Machine) transaction adapter.\n * This adapter encapsulates all the logic required to interact with EVM-based chains using wagmi.\n */\n\nimport { getConnectorTypeFromName, lastConnectedConnectorHelpers, OrbitAdapter } from '@tuwaio/orbit-core';\nimport { checkAndSwitchChain } from '@tuwaio/orbit-evm';\nimport { Transaction, TransactionTracker, TxAdapter } from '@tuwaio/pulsar-core';\nimport { Config, getConnection } from '@wagmi/core';\nimport { Chain, zeroAddress } from 'viem';\n\nimport { cancelTxAction } from '../utils/cancelTxAction';\nimport { checkAndInitializeTrackerInStore } from '../utils/checkAndInitializeTrackerInStore';\nimport { checkTransactionsTracker } from '../utils/checkTransactionsTracker';\nimport { selectEvmTxExplorerLink } from '../utils/selectEvmTxExplorerLink';\nimport { speedUpTxAction } from '../utils/speedUpTxAction';\n\n/**\n * Creates an EVM-specific transaction adapter.\n *\n * This function acts as a constructor for the EVM adapter, bundling all the necessary\n * chain-specific utilities (like checking chain, ENS resolution, speeding up transactions, etc.)\n * into a single object that conforms to the `TxAdapter` interface.\n *\n * @template T - The application-specific transaction type.\n * @param {Config} config - The wagmi configuration object.\n * @param {Chain[]} appChains - An array of viem `Chain` objects supported by the application.\n *\n * @returns {TxAdapter<T>} The configured EVM transaction adapter.\n *\n * @throws {Error} Throws an error if the wagmi `config` is not provided.\n */\nexport function pulsarEvmAdapter<T extends Transaction>(\n config: Config,\n appChains: readonly [Chain, ...Chain[]],\n): TxAdapter<T> {\n if (!config) {\n throw new Error('EVM adapter requires a wagmi config object.');\n }\n\n return {\n key: OrbitAdapter.EVM,\n\n getConnectorInfo: () => {\n const activeConnection = getConnection(config);\n const localConnectedConnector = lastConnectedConnectorHelpers.getLastConnectedConnector();\n return {\n walletAddress: activeConnection.address ?? localConnectedConnector?.address ?? zeroAddress,\n connectorType: getConnectorTypeFromName(\n OrbitAdapter.EVM,\n activeConnection.connector?.name?.toLowerCase() ?? 'unknown',\n ),\n };\n },\n\n // --- Core Methods ---\n checkChainForTx: (chainId: string | number) => checkAndSwitchChain(chainId as number, config),\n checkTransactionsTracker: (actionTxKey, connectorType) => checkTransactionsTracker(actionTxKey, connectorType),\n checkAndInitializeTrackerInStore: ({ tx, ...rest }) =>\n checkAndInitializeTrackerInStore({ tracker: tx.tracker, tx, config, ...rest }),\n\n // --- UI & Explorer Methods ---\n getExplorerUrl: (url) => {\n const { chain } = getConnection(config);\n const baseExplorerLink = chain?.blockExplorers?.default.url;\n return url ? `${baseExplorerLink}/${url}` : baseExplorerLink;\n },\n getExplorerTxUrl: (tx) =>\n selectEvmTxExplorerLink({\n chains: appChains,\n tx,\n }),\n\n // --- Optional Actions ---\n cancelTxAction: (tx) => cancelTxAction({ config, tx: tx as T }),\n speedUpTxAction: (tx) => speedUpTxAction({ config, tx: tx as T }),\n retryTxAction: async ({ onClose, txKey, executeTxAction, tx }) => {\n onClose(txKey);\n\n if (!executeTxAction) {\n console.error('Retry failed: executeTxAction function is not provided.');\n return;\n }\n\n await executeTxAction({\n actionFunction: () => tx.actionFunction({ config, ...tx.payload }),\n params: tx,\n defaultTracker: TransactionTracker.Ethereum,\n });\n },\n };\n}\n","/**\n * @file This file contains a utility to check if the Gelato Relay service is available for a specific chain.\n */\n\n// --- In-memory cache to store the list of supported chains ---\nlet cachedRelayChainIds: number[] | null = null;\nlet cacheTimestamp: number | null = null;\nconst CACHE_DURATION_MS = 5 * 60 * 1000; // Cache the list for 5 minutes\nconst GELATO_API_URL = 'https://relay.gelato.digital/relays/v2/supported-chains';\n\n/**\n * Checks if the Gelato Relay service supports a given chain ID.\n *\n * This function fetches the list of supported chain IDs from the Gelato API and\n * caches the result in memory for 5 minutes to reduce network requests.\n *\n * @param {number} chainId - The chain identifier to check.\n * @returns {Promise<boolean>} A promise that resolves to `true` if Gelato supports the chain, `false` otherwise.\n */\nexport async function checkIsGelatoAvailable(chainId: number): Promise<boolean> {\n const now = Date.now();\n\n // 1. Check if a valid, non-expired cache exists.\n if (cachedRelayChainIds && cacheTimestamp && now - cacheTimestamp < CACHE_DURATION_MS) {\n return cachedRelayChainIds.includes(chainId);\n }\n\n // 2. If no valid cache, fetch the list from the Gelato API.\n try {\n const response = await fetch(GELATO_API_URL);\n\n if (!response.ok) {\n throw new Error(`Gelato API responded with status: ${response.status}`);\n }\n\n const data = (await response.json()) as { chains: string[] };\n // The endpoint returns an array of strings, which we convert to numbers.\n const supportedChainIds = data.chains.map(Number);\n\n // 3. Update the cache with the new data and timestamp.\n cachedRelayChainIds = supportedChainIds;\n cacheTimestamp = now;\n\n return supportedChainIds.includes(chainId);\n } catch (error) {\n console.error('Failed to fetch Gelato supported chains:', error);\n\n // In case of an error, clear the cache to allow for a retry on the next call.\n cachedRelayChainIds = null;\n cacheTimestamp = null;\n\n return false;\n }\n}\n"]}
|