@swapkit/helpers 4.15.2 → 4.15.3

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 CHANGED
@@ -1 +1 @@
1
- import{$ as Zg,A as hf,Aa as hg,B as of,Ba as og,C as uf,Ca as ug,D as sf,Da as sg,E as df,Ea as dg,F as lf,Fa as lg,G as nf,Ga as ng,H as pf,Ha as pg,I as tf,Ia as ig,J as af,Ja as tg,K as ef,Ka as ag,L as $g,La as eg,M as P,Ma as $R,N as fg,Na as fR,O as gg,Oa as gR,P as Rg,Pa as RR,Q as xg,Qa as xR,R as Bg,S as Mg,T as Yg,U as Gg,V as zg,W as Jg,X as Lg,Y as Pg,Z as Qg,_ as Xg,a as X,aa as _g,b as Ef,ba as Vg,c as If,ca as Wg,d as Tf,da as Cg,e as Sf,ea as jg,f as b,fa as Fg,g as qf,ga as Hg,h as i,ha as Eg,i as e,ia as Ig,j as Nf,ja as Tg,k as Kf,ka as Sg,l as E,la as qg,m as _,ma as Ng,n as Af,na as Kg,o as Of,oa as Ag,p as Uf,pa as Og,q as Df,qa as Ug,r as yf,ra as Dg,s as N,sa as yg,t as kf,ta as kg,u as bf,ua as bg,v as mf,va as mg,w as wf,wa as wg,x as vf,xa as vg,y as cf,ya as cg,z as rf,za as rg}from"./chunk-tf9f4rzs.js";export*from"@swapkit/tokens";export*from"@swapkit/types";var m={average:1,fast:1.5,fastest:2};function I($="average"){let f=E.get("feeMultipliers");if(f&&f[$]!==void 0)return f[$];return m[$]}function w($="average"){let f=I($),g=10n,R=BigInt(Math.round(f*10));return{denominator:g,numerator:R}}function Y$($,f="average"){let{numerator:g,denominator:R}=w(f);return $*g/R}function G$($,f="average",g=!1){let R=I(f),x=$*R;return g?Math.floor(x):x}import{Chain as T,EVMChains as v}from"@swapkit/types";function j($,f){if("index"in f)return[...$.slice(0,$.length-1),f.index];if("change"in f){let[g,R,x,,B]=$;return[g,R,x,f.change,B]}if("account"in f){let[g,R,,x,B]=$;return[g,R,f.account,x,B]}return $}function c([$,f,g,R,x],{allHardened:B}={}){let Y=B?"'":"",G=typeof x!=="number";if(typeof R!=="number")return`m/${$}'/${f}'/${g}'`;return`m/${$}'/${f}'/${g}'/${R}${Y}${G?"":`/${x}${Y}`}`}function P$({chain:$,index:f,addressIndex:g=0,type:R}){if(v.includes($)){if(R&&["legacy","account"].includes(R))return[44,60,0,f];if(R==="ledgerLive")return[44,60,f,0,g];return j(X[$],{index:f})}if($===T.Solana){if(R==="account")return[44,501,0,f];return j(X[$],{index:f})}let x=$===T.Litecoin?2:0;switch(R){case"nativeSegwitMiddleAccount":return[84,x,f,0,g];case"segwit":return[49,x,0,0,f];case"legacy":return[44,x,0,0,f];default:return j(X[$],{index:f})}}function Q$($){let[f,g,R]=$.split("/").map((x)=>Number.parseInt(x,10));switch(g){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var X$=Object.keys(X).reduce(($,f)=>{return $[f]=c(X[f]),$},{});import{Chain as z,CosmosChains as r,EVMChains as h,getChainConfig as S,SubstrateChains as o,UTXOChains as u}from"@swapkit/types";import{match as q}from"ts-pattern";function W$({chain:$,txHash:f}){let{explorerUrl:g}=S($);return q($).with(...r,z.Solana,()=>`${g}/tx/${f.startsWith("0x")?f.slice(2):f}`).with(...h,...o,()=>`${g}/tx/${f.startsWith("0x")?f:`0x${f}`}`).with(...u,z.Radix,z.Tron,()=>`${g}/transaction/${f.toLowerCase()}`).with(z.Near,()=>`${g}/txns/${f}`).with(z.Ripple,()=>`${g}/transactions/${f}`).with(z.Stellar,()=>`${g}/explorer/public/tx/${f}`).with(z.Sui,()=>`${g}/txblock/${f}`).with(z.Cardano,z.Hype,z.Spark,z.Ton,()=>`${g}/tx/${f}`).otherwise(()=>"")}function C$({chain:$,address:f}){let{explorerUrl:g}=S($);return q($).with(z.Solana,z.Sui,z.Radix,()=>`${g}/account/${f}`).with(z.Stellar,()=>`${g}/explorer/public/account/${f}`).otherwise(()=>`${g}/address/${f}`)}import{Chain as s,getChainConfig as d}from"@swapkit/types";function l({liquidityUnits:$,poolUnits:f,runeDepth:g}){let R=J($),x=J(f),B=J(g),Y=R.mul(B),G=x.mul(x).mul(2),M=x.mul(R).mul(2),L=R.mul(R),Q=x.mul(x).mul(x);return Y.mul(G.sub(M).add(L)).div(Q)}function n({liquidityUnits:$,poolUnits:f,assetDepth:g}){let R=J($),x=J(f),B=J(g),Y=R.mul(B),G=x.mul(x).mul(2),M=x.mul(R).mul(2),L=R.mul(R),Q=Y.mul(G.sub(M).add(L)),Z=x.mul(x).mul(x);return Q.div(Z)}function E$({percent:$,runeDepth:f,liquidityUnits:g,poolUnits:R}){return l({liquidityUnits:g,poolUnits:R,runeDepth:f}).mul($)}function I$({percent:$,assetDepth:f,liquidityUnits:g,poolUnits:R}){return n({assetDepth:f,liquidityUnits:g,poolUnits:R}).mul($)}function J($){return P.fromBigInt(BigInt($),d(s.THORChain).baseDecimal)}function p({liquidityUnits:$,poolUnits:f,runeDepth:g,assetDepth:R}){return{assetAmount:J(R).mul($).div(f),runeAmount:J(g).mul($).div(f)}}function T$({liquidityUnits:$,poolUnits:f,runeDepth:g,assetDepth:R,percent:x}){return Object.fromEntries(Object.entries(p({assetDepth:R,liquidityUnits:$,poolUnits:f,runeDepth:g})).map(([B,Y])=>[B,Y.mul(x)]))}function S$({runeDepth:$,poolUnits:f,assetDepth:g,liquidityUnits:R,runeAmount:x,assetAmount:B}){let Y=new P({decimal:8,value:$}),G=new P({decimal:8,value:g}),M=new P({decimal:8,value:f}),L=new P({decimal:8,value:x}),Q=new P({decimal:8,value:B}),Z=L.mul(G),F=Q.mul(Y),O=L.mul(Q),U=Y.mul(G),D=M.mul(Z.add(F.add(O.mul(2)))),y=Z.add(F.add(U.mul(2))),H=D.div(y),C=J(R).add(H);if(H.getBaseValue("number")===0)return C.div(M).getBaseValue("number");let k=M.add(C);return C.div(k).getBaseValue("number")}function q$({runeAmount:$,assetAmount:f,runeDepth:g,assetDepth:R}){if($==="0"||f==="0"||g==="0"||R==="0")return 0;let x=J(g),B=J(R),Y=J(f),G=J($),M=Y.mul(x).sub(B.mul(G)),L=B.mul(G).add(x.mul(B));return Math.abs(M.div(L).getBaseValue("number"))}import{Chain as V}from"@swapkit/types";import{match as t}from"ts-pattern";function U$({type:$,address:f}){return`${$}:${f}`}function D$({address:$,unbondAmount:f}){return`${"UNBOND"}:${$}:${f}`}function y$($){return W("POOL+",$)}function k$({chain:$,symbol:f,address:g,...R}){let x=a({chain:$,symbol:f}),B=g?`:${g}:`:":";return W(`${"+"}:${x}${B}`,R)}function b$({chain:$,symbol:f,ticker:g,basisPoints:R,targetAsset:x}){let B=$==="ETH"&&g!=="ETH"?`${g}-${f.slice(-3)}`:f,Y=x?`:${x}`:"";return`${"-"}:${$}.${B}:${R}${Y}`}function m$({basisPoints:$,...f}){return W(`${"POOL-"}:${$}`,f)}function w$({name:$,chain:f,address:g,owner:R}){let x=`${"~"}:${$}:${f}:${g}`,B=R?`:${R}`:"";return`${x}${B}`}function v$({name:$,chain:f,asset:g,payout:R,owner:x}){return`${"~"}:${$}:${f}:${R}:${x}:${g}`}function c$($,{address:f}){return`${$}:${f}`}function r$($,{unstakeBps:f,...g}){let R=f?`:${f}`:"",x=`${$}${R}`;return W(`${x}`,g)}function W($,{affiliateAddress:f,affiliateBasisPoints:g}={}){let R=`${$}${f?`:${f}:${g||0}`:""}`;return R.endsWith(":")?R.slice(0,-1):R}function a({chain:$,symbol:f}){return t($).with(V.Bitcoin,V.Dogecoin,V.Litecoin,()=>$.slice(0,1).toLowerCase()).with(V.BitcoinCash,()=>"c").otherwise(()=>`${$}.${f}`)}import{getChainConfig as K}from"@swapkit/types";function l$(){return typeof window.ethereum<"u"}function n$($){return $$().includes($)}function $$(){let $=window?.ethereum&&!window.ethereum?.isBraveWallet,f=window?.ctrl||window?.ethereum?.__XDEFI,g=window?.vultisig,R=window?.ethereum?.isBraveWallet,x=window?.ethereum?.isTrust||window?.trustwallet,B=window?.ethereum?.overrideIsMetaMask&&window?.ethereum?.selectedProvider?.isCoinbaseWallet||window?.coinbaseWalletExtension,Y=window?.bitkeep?.ethereum,G=window?.$onekey?.ethereum,M=[];if($)M.push("METAMASK");if(f)M.push("CTRL");if(g)M.push("VULTISIG");if(R)M.push("BRAVE");if(x)M.push("TRUSTWALLET_WEB");if(B)M.push("COINBASE_WEB");if(x$())M.push("OKX_MOBILE");if(Y)M.push("BITGET");if(G)M.push("ONEKEY");return M}async function f$($,f,g){let R=K(f);try{await A({method:"wallet_switchEthereumChain",params:[{chainId:R.chainIdHex}],provider:$})}catch(x){if(!g)throw new _("helpers_failed_to_switch_network",{error:x,reason:"networkParams not provided"});await R$($,g)}}function p$({chains:$,supportedChains:f,walletType:g}){let R=$.filter((B)=>!B||f.includes(B));if(R.length===0)throw new _("wallet_chain_not_supported",{chain:$.join(", "),wallet:g});let x=$.filter((B)=>!f.includes(B));return N({condition:x.length>0,id:`wallet_chain_not_supported_${g}`,warning:`${g} wallet does not support the following chains: ${x.join(", ")}. These chains will be ignored.`}),R}function g$($,f,g){return async(...R)=>{let{chainIdHex:x}=K(g);if((await f.getNetwork()).chainId.toString()===x)return $(...R);try{await f$(f,g)}catch(B){throw new _({errorKey:"helpers_failed_to_switch_network",info:{error:B}})}return $(...R)}}function i$({toolbox:$,chain:f,provider:g,methodNames:R=[]}){let B=[...R,"approve","approvedAmount","call","sendTransaction","transfer","isApproved","approvedAmount","EIP1193SendTransaction","getFeeData","broadcastTransaction","estimateCall","estimateGasLimit","estimateGasPrices","createContractTxObject"].reduce((Y,G)=>{if(!$[G])return Y;let M=$[G];if(typeof M!=="function")return Y;let L=g$(M,g,f);return{...Y,[G]:L}},{});return{...$,...B}}function R$($,f){return A({method:"wallet_addEthereumChain",params:[f],provider:$})}function t$($){window.ethereum?.on("accountsChanged",()=>$()),window.ctrl?.ethereum.on("accountsChanged",()=>$())}function a$(){let{isTrust:$,isBraveWallet:f,__XDEFI:g,overrideIsMetaMask:R,selectedProvider:x}=window?.ethereum||{};if($)return"TRUSTWALLET_WEB";if(f)return"BRAVE";if(R&&x?.isCoinbaseWallet)return"COINBASE_WEB";if(g)return"CTRL";if(window?.$onekey?.ethereum)return"ONEKEY";return"METAMASK"}function e$(){let $=[];function f(R){if($.map((x)=>x.info.uuid).includes(R.detail.info.uuid))return;$.push(R.detail)}window.addEventListener("eip6963:announceProvider",f),window.dispatchEvent(new Event("eip6963:requestProvider"));function g(){window.removeEventListener("eip6963:announceProvider",f)}return{providers:$,removeEIP6963EventListener:g}}function x$(){let $=navigator.userAgent,f=/iphone|ipad|ipod|ios/i.test($),g=/android|XiaoMi|MiuiBrowser/i.test($),R=f||g,x=/OKApp/i.test($);return R&&x}function A({provider:$,params:f,method:g}){if(!$?.send)throw new _("helpers_not_found_provider");let R=f?Array.isArray(f)?f:[f]:[];return $.send(g,R)}export{Df as wrapWithThrow,g$ as wrapMethodWithNetworkSwitch,N as warnOnce,pf as validateTNS,nf as validateIdentifier,j as updateDerivationPath,f$ as switchEVMWalletNetwork,Kf as swapKitConfigStore,fg as signWidgetRequest,A as providerRequest,i$ as prepareNetworkSwitch,sf as parseSymbolForAddress,x$ as okxMobileEnabled,$$ as listWeb3EVMWallets,l$ as isWeb3Detected,rf as isGasAsset,n$ as isDetected,wf as initializeRPCUrlsWithFallback,Q$ as getWalletFormatFor,df as getTokenLogoURI,Of as getTHORNameCost,T$ as getSymmetricWithdraw,p as getSymmetricPoolShare,bf as getRPCUrlSync,mf as getRPCUrl,$g as getMinAmountByChain,b$ as getMemoForWithdraw,D$ as getMemoForUnbond,r$ as getMemoForTcyStake,c$ as getMemoForTcyClaim,m$ as getMemoForRunePoolWithdraw,y$ as getMemoForRunePoolDeposit,w$ as getMemoForNameRegister,v$ as getMemoForNamePreferredAssetRegister,U$ as getMemoForLeaveAndBond,k$ as getMemoForDeposit,Uf as getMAYANameCost,q$ as getLiquiditySlippage,w as getFeeMultiplierAsBigInt,I as getFeeMultiplier,W$ as getExplorerTxUrl,C$ as getExplorerAddressUrl,S$ as getEstimatedPoolShare,a$ as getETHDefaultWallet,e$ as getEIP6963Wallets,P$ as getDerivationPathFor,hf as getCommonAssetInfo,yf as getChainIdentifier,E$ as getAsymmetricRuneWithdrawAmount,l as getAsymmetricRuneShare,I$ as getAsymmetricAssetWithdrawAmount,n as getAsymmetricAssetShare,of as getAssetType,tf as formatBigIntToSafeValue,lf as findAssetBy,p$ as filterSupportedChains,cf as fetchTokenInfo,c as derivationPathToString,uf as assetFromString,Y$ as applyFeeMultiplierToBigInt,G$ as applyFeeMultiplier,R$ as addEVMWalletNetwork,t$ as addAccountsChangedCallback,kf as _rpcCache,If as WarningCodeEnum,e as WalletOption,xg as TxnType,Mg as TxnStatus,Ag as TronTransactionSchema,Tg as TransactionSchema,Sg as TransactionDTOSchema,Yg as TrackingStatus,zg as TrackingRequestSchema,Jg as TrackingRequestQuerySchema,Ig as TrackerResponseSchema,Gg as TokenSchema,Xg as TokenDetailsMetadataSchema,kg as TONTransactionSchema,eg as SwapToResponseSchema,tg as SwapToRequestSchema,ag as SwapToAssetSchema,RR as SwapRouteV2ResponseSchema,P as SwapKitNumber,_ as SwapKitError,xR as SwapKitApi,yg as StarknetTransactionSchema,E as SKConfig,hg as RouteQuoteWarningSchema,Rg as RouteQuoteTxType,fR as RouteQuoteProviderErrorSchema,rg as RouteQuoteMetadataV2Schema,cg as RouteQuoteMetadataSchema,wg as RouteQuoteMetadataAssetSchema,mg as RouteLegWithoutAddressesSchema,bg as RouteLegSchema,Af as RequestClient,ig as QuoteV3ResponseSchema,gR as QuoteV2ResponseSchema,$R as QuoteRouteV2Response,ug as QuoteResponseSchema,og as QuoteResponseRouteItem,_g as QuoteRequestSchema,Tf as ProviderName,Bg as ProviderAction,gg as PriorityLabel,Zg as PriceResponseSchema,Vg as PriceRequestSchema,X as NetworkDerivationPath,Eg as NearSwapResponseSchema,Hg as NearDepositChannelResultSchema,Fg as NearDepositChannelParamsSchema,i as MemoType,Nf as LedgerErrorCode,sg as GasSchema,dg as GasResponseSchema,qg as FeesSchema,Sf as FeeTypeEnum,b as FeeOption,Ng as EstimatedTimeSchema,Ef as ErrorCode,Kg as EVMTransactionSchema,Ug as EVMTransactionDetailsSchema,Og as EVMTransactionDetailsParamsSchema,X$ as DerivationPath,jg as DepositChannelResponseSchema,Wg as DepositChannelParamsSchema,m as DEFAULT_FEE_MULTIPLIERS,Dg as CosmosTransactionSchema,vf as CommonAssetStrings,Qg as CoinGeckoMetadataSchema,vg as ChainflipMetadataSchema,Cg as BrokerDepositChannelParamsSchema,af as BigIntArithmetics,Pg as AssetValueSchema,ef as AssetValue,ng as ApproveResponseSchema,lg as ApproveRequestParams,qf as ApproveMode,pg as ApprovalTransactionSchema,Lg as ApiV2ErrorSchema};
1
+ import{$ as Zg,A as hf,Aa as hg,B as of,Ba as og,C as uf,Ca as ug,D as sf,Da as sg,E as df,Ea as dg,F as lf,Fa as lg,G as nf,Ga as ng,H as pf,Ha as pg,I as tf,Ia as ig,J as af,Ja as tg,K as ef,Ka as ag,L as $g,La as eg,M as P,Ma as $R,N as fg,Na as fR,O as gg,Oa as gR,P as Rg,Pa as RR,Q as xg,Qa as xR,R as Bg,Ra as BR,S as Mg,Sa as MR,T as Yg,Ta as YR,U as Gg,Ua as GR,V as zg,W as Jg,X as Lg,Y as Pg,Z as Qg,_ as Xg,a as X,aa as _g,b as Ef,ba as Vg,c as If,ca as Wg,d as Tf,da as Cg,e as Sf,ea as jg,f as b,fa as Fg,g as qf,ga as Hg,h as i,ha as Eg,i as e,ia as Ig,j as Nf,ja as Tg,k as Kf,ka as Sg,l as E,la as qg,m as _,ma as Ng,n as Af,na as Kg,o as Of,oa as Ag,p as Uf,pa as Og,q as Df,qa as Ug,r as yf,ra as Dg,s as N,sa as yg,t as kf,ta as kg,u as bf,ua as bg,v as mf,va as mg,w as wf,wa as wg,x as vf,xa as vg,y as cf,ya as cg,z as rf,za as rg}from"./chunk-hma0zdy9.js";export*from"@swapkit/tokens";export*from"@swapkit/types";var m={average:1,fast:1.5,fastest:2};function I($="average"){let f=E.get("feeMultipliers");if(f&&f[$]!==void 0)return f[$];return m[$]}function w($="average"){let f=I($),g=10n,R=BigInt(Math.round(f*10));return{denominator:g,numerator:R}}function Y$($,f="average"){let{numerator:g,denominator:R}=w(f);return $*g/R}function G$($,f="average",g=!1){let R=I(f),x=$*R;return g?Math.floor(x):x}import{Chain as T,EVMChains as v}from"@swapkit/types";function j($,f){if("index"in f)return[...$.slice(0,$.length-1),f.index];if("change"in f){let[g,R,x,,B]=$;return[g,R,x,f.change,B]}if("account"in f){let[g,R,,x,B]=$;return[g,R,f.account,x,B]}return $}function c([$,f,g,R,x],{allHardened:B}={}){let Y=B?"'":"",G=typeof x!=="number";if(typeof R!=="number")return`m/${$}'/${f}'/${g}'`;return`m/${$}'/${f}'/${g}'/${R}${Y}${G?"":`/${x}${Y}`}`}function P$({chain:$,index:f,addressIndex:g=0,type:R}){if(v.includes($)){if(R&&["legacy","account"].includes(R))return[44,60,0,f];if(R==="ledgerLive")return[44,60,f,0,g];return j(X[$],{index:f})}if($===T.Solana){if(R==="account")return[44,501,0,f];return j(X[$],{index:f})}let x=$===T.Litecoin?2:0;switch(R){case"nativeSegwitMiddleAccount":return[84,x,f,0,g];case"segwit":return[49,x,0,0,f];case"legacy":return[44,x,0,0,f];default:return j(X[$],{index:f})}}function Q$($){let[f,g,R]=$.split("/").map((x)=>Number.parseInt(x,10));switch(g){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var X$=Object.keys(X).reduce(($,f)=>{return $[f]=c(X[f]),$},{});import{Chain as z,CosmosChains as r,EVMChains as h,getChainConfig as S,SubstrateChains as o,UTXOChains as u}from"@swapkit/types";import{match as q}from"ts-pattern";function W$({chain:$,txHash:f}){let{explorerUrl:g}=S($);return q($).with(...r,z.Solana,()=>`${g}/tx/${f.startsWith("0x")?f.slice(2):f}`).with(...h,...o,()=>`${g}/tx/${f.startsWith("0x")?f:`0x${f}`}`).with(...u,z.Radix,z.Tron,()=>`${g}/transaction/${f.toLowerCase()}`).with(z.Near,()=>`${g}/txns/${f}`).with(z.Ripple,()=>`${g}/transactions/${f}`).with(z.Stellar,()=>`${g}/explorer/public/tx/${f}`).with(z.Sui,()=>`${g}/txblock/${f}`).with(z.Cardano,z.Hype,z.Spark,z.Ton,()=>`${g}/tx/${f}`).otherwise(()=>"")}function C$({chain:$,address:f}){let{explorerUrl:g}=S($);return q($).with(z.Solana,z.Sui,z.Radix,()=>`${g}/account/${f}`).with(z.Stellar,()=>`${g}/explorer/public/account/${f}`).otherwise(()=>`${g}/address/${f}`)}import{Chain as s,getChainConfig as d}from"@swapkit/types";function l({liquidityUnits:$,poolUnits:f,runeDepth:g}){let R=J($),x=J(f),B=J(g),Y=R.mul(B),G=x.mul(x).mul(2),M=x.mul(R).mul(2),L=R.mul(R),Q=x.mul(x).mul(x);return Y.mul(G.sub(M).add(L)).div(Q)}function n({liquidityUnits:$,poolUnits:f,assetDepth:g}){let R=J($),x=J(f),B=J(g),Y=R.mul(B),G=x.mul(x).mul(2),M=x.mul(R).mul(2),L=R.mul(R),Q=Y.mul(G.sub(M).add(L)),Z=x.mul(x).mul(x);return Q.div(Z)}function E$({percent:$,runeDepth:f,liquidityUnits:g,poolUnits:R}){return l({liquidityUnits:g,poolUnits:R,runeDepth:f}).mul($)}function I$({percent:$,assetDepth:f,liquidityUnits:g,poolUnits:R}){return n({assetDepth:f,liquidityUnits:g,poolUnits:R}).mul($)}function J($){return P.fromBigInt(BigInt($),d(s.THORChain).baseDecimal)}function p({liquidityUnits:$,poolUnits:f,runeDepth:g,assetDepth:R}){return{assetAmount:J(R).mul($).div(f),runeAmount:J(g).mul($).div(f)}}function T$({liquidityUnits:$,poolUnits:f,runeDepth:g,assetDepth:R,percent:x}){return Object.fromEntries(Object.entries(p({assetDepth:R,liquidityUnits:$,poolUnits:f,runeDepth:g})).map(([B,Y])=>[B,Y.mul(x)]))}function S$({runeDepth:$,poolUnits:f,assetDepth:g,liquidityUnits:R,runeAmount:x,assetAmount:B}){let Y=new P({decimal:8,value:$}),G=new P({decimal:8,value:g}),M=new P({decimal:8,value:f}),L=new P({decimal:8,value:x}),Q=new P({decimal:8,value:B}),Z=L.mul(G),F=Q.mul(Y),O=L.mul(Q),U=Y.mul(G),D=M.mul(Z.add(F.add(O.mul(2)))),y=Z.add(F.add(U.mul(2))),H=D.div(y),C=J(R).add(H);if(H.getBaseValue("number")===0)return C.div(M).getBaseValue("number");let k=M.add(C);return C.div(k).getBaseValue("number")}function q$({runeAmount:$,assetAmount:f,runeDepth:g,assetDepth:R}){if($==="0"||f==="0"||g==="0"||R==="0")return 0;let x=J(g),B=J(R),Y=J(f),G=J($),M=Y.mul(x).sub(B.mul(G)),L=B.mul(G).add(x.mul(B));return Math.abs(M.div(L).getBaseValue("number"))}import{Chain as V}from"@swapkit/types";import{match as t}from"ts-pattern";function U$({type:$,address:f}){return`${$}:${f}`}function D$({address:$,unbondAmount:f}){return`${"UNBOND"}:${$}:${f}`}function y$($){return W("POOL+",$)}function k$({chain:$,symbol:f,address:g,...R}){let x=a({chain:$,symbol:f}),B=g?`:${g}:`:":";return W(`${"+"}:${x}${B}`,R)}function b$({chain:$,symbol:f,ticker:g,basisPoints:R,targetAsset:x}){let B=$==="ETH"&&g!=="ETH"?`${g}-${f.slice(-3)}`:f,Y=x?`:${x}`:"";return`${"-"}:${$}.${B}:${R}${Y}`}function m$({basisPoints:$,...f}){return W(`${"POOL-"}:${$}`,f)}function w$({name:$,chain:f,address:g,owner:R}){let x=`${"~"}:${$}:${f}:${g}`,B=R?`:${R}`:"";return`${x}${B}`}function v$({name:$,chain:f,asset:g,payout:R,owner:x}){return`${"~"}:${$}:${f}:${R}:${x}:${g}`}function c$($,{address:f}){return`${$}:${f}`}function r$($,{unstakeBps:f,...g}){let R=f?`:${f}`:"",x=`${$}${R}`;return W(`${x}`,g)}function W($,{affiliateAddress:f,affiliateBasisPoints:g}={}){let R=`${$}${f?`:${f}:${g||0}`:""}`;return R.endsWith(":")?R.slice(0,-1):R}function a({chain:$,symbol:f}){return t($).with(V.Bitcoin,V.Dogecoin,V.Litecoin,()=>$.slice(0,1).toLowerCase()).with(V.BitcoinCash,()=>"c").otherwise(()=>`${$}.${f}`)}import{getChainConfig as K}from"@swapkit/types";function l$(){return typeof window.ethereum<"u"}function n$($){return $$().includes($)}function $$(){let $=window?.ethereum&&!window.ethereum?.isBraveWallet,f=window?.ctrl||window?.ethereum?.__XDEFI,g=window?.vultisig,R=window?.ethereum?.isBraveWallet,x=window?.ethereum?.isTrust||window?.trustwallet,B=window?.ethereum?.overrideIsMetaMask&&window?.ethereum?.selectedProvider?.isCoinbaseWallet||window?.coinbaseWalletExtension,Y=window?.bitkeep?.ethereum,G=window?.$onekey?.ethereum,M=[];if($)M.push("METAMASK");if(f)M.push("CTRL");if(g)M.push("VULTISIG");if(R)M.push("BRAVE");if(x)M.push("TRUSTWALLET_WEB");if(B)M.push("COINBASE_WEB");if(x$())M.push("OKX_MOBILE");if(Y)M.push("BITGET");if(G)M.push("ONEKEY");return M}async function f$($,f,g){let R=K(f);try{await A({method:"wallet_switchEthereumChain",params:[{chainId:R.chainIdHex}],provider:$})}catch(x){if(!g)throw new _("helpers_failed_to_switch_network",{error:x,reason:"networkParams not provided"});await R$($,g)}}function p$({chains:$,supportedChains:f,walletType:g}){let R=$.filter((B)=>!B||f.includes(B));if(R.length===0)throw new _("wallet_chain_not_supported",{chain:$.join(", "),wallet:g});let x=$.filter((B)=>!f.includes(B));return N({condition:x.length>0,id:`wallet_chain_not_supported_${g}`,warning:`${g} wallet does not support the following chains: ${x.join(", ")}. These chains will be ignored.`}),R}function g$($,f,g){return async(...R)=>{let{chainIdHex:x}=K(g);if((await f.getNetwork()).chainId.toString()===x)return $(...R);try{await f$(f,g)}catch(B){throw new _({errorKey:"helpers_failed_to_switch_network",info:{error:B}})}return $(...R)}}function i$({toolbox:$,chain:f,provider:g,methodNames:R=[]}){let B=[...R,"approve","approvedAmount","call","sendTransaction","transfer","isApproved","approvedAmount","EIP1193SendTransaction","getFeeData","broadcastTransaction","estimateCall","estimateGasLimit","estimateGasPrices","createContractTxObject"].reduce((Y,G)=>{if(!$[G])return Y;let M=$[G];if(typeof M!=="function")return Y;let L=g$(M,g,f);return{...Y,[G]:L}},{});return{...$,...B}}function R$($,f){return A({method:"wallet_addEthereumChain",params:[f],provider:$})}function t$($){window.ethereum?.on("accountsChanged",()=>$()),window.ctrl?.ethereum.on("accountsChanged",()=>$())}function a$(){let{isTrust:$,isBraveWallet:f,__XDEFI:g,overrideIsMetaMask:R,selectedProvider:x}=window?.ethereum||{};if($)return"TRUSTWALLET_WEB";if(f)return"BRAVE";if(R&&x?.isCoinbaseWallet)return"COINBASE_WEB";if(g)return"CTRL";if(window?.$onekey?.ethereum)return"ONEKEY";return"METAMASK"}function e$(){let $=[];function f(R){if($.map((x)=>x.info.uuid).includes(R.detail.info.uuid))return;$.push(R.detail)}window.addEventListener("eip6963:announceProvider",f),window.dispatchEvent(new Event("eip6963:requestProvider"));function g(){window.removeEventListener("eip6963:announceProvider",f)}return{providers:$,removeEIP6963EventListener:g}}function x$(){let $=navigator.userAgent,f=/iphone|ipad|ipod|ios/i.test($),g=/android|XiaoMi|MiuiBrowser/i.test($),R=f||g,x=/OKApp/i.test($);return R&&x}function A({provider:$,params:f,method:g}){if(!$?.send)throw new _("helpers_not_found_provider");let R=f?Array.isArray(f)?f:[f]:[];return $.send(g,R)}export{Df as wrapWithThrow,g$ as wrapMethodWithNetworkSwitch,N as warnOnce,pf as validateTNS,nf as validateIdentifier,j as updateDerivationPath,Og as toHexTransactionValue,f$ as switchEVMWalletNetwork,Kf as swapKitConfigStore,fg as signWidgetRequest,A as providerRequest,i$ as prepareNetworkSwitch,Ag as parseTransactionValue,sf as parseSymbolForAddress,x$ as okxMobileEnabled,$$ as listWeb3EVMWallets,l$ as isWeb3Detected,Kg as isTransactionValue,rf as isGasAsset,n$ as isDetected,wf as initializeRPCUrlsWithFallback,Q$ as getWalletFormatFor,df as getTokenLogoURI,Of as getTHORNameCost,T$ as getSymmetricWithdraw,p as getSymmetricPoolShare,bf as getRPCUrlSync,mf as getRPCUrl,$g as getMinAmountByChain,b$ as getMemoForWithdraw,D$ as getMemoForUnbond,r$ as getMemoForTcyStake,c$ as getMemoForTcyClaim,m$ as getMemoForRunePoolWithdraw,y$ as getMemoForRunePoolDeposit,w$ as getMemoForNameRegister,v$ as getMemoForNamePreferredAssetRegister,U$ as getMemoForLeaveAndBond,k$ as getMemoForDeposit,Uf as getMAYANameCost,q$ as getLiquiditySlippage,w as getFeeMultiplierAsBigInt,I as getFeeMultiplier,W$ as getExplorerTxUrl,C$ as getExplorerAddressUrl,S$ as getEstimatedPoolShare,a$ as getETHDefaultWallet,e$ as getEIP6963Wallets,P$ as getDerivationPathFor,hf as getCommonAssetInfo,yf as getChainIdentifier,E$ as getAsymmetricRuneWithdrawAmount,l as getAsymmetricRuneShare,I$ as getAsymmetricAssetWithdrawAmount,n as getAsymmetricAssetShare,of as getAssetType,tf as formatBigIntToSafeValue,lf as findAssetBy,p$ as filterSupportedChains,cf as fetchTokenInfo,c as derivationPathToString,uf as assetFromString,Y$ as applyFeeMultiplierToBigInt,G$ as applyFeeMultiplier,R$ as addEVMWalletNetwork,t$ as addAccountsChangedCallback,kf as _rpcCache,If as WarningCodeEnum,e as WalletOption,xg as TxnType,Mg as TxnStatus,Dg as TronTransactionSchema,Tg as TransactionSchema,Sg as TransactionDTOSchema,Yg as TrackingStatus,zg as TrackingRequestSchema,Jg as TrackingRequestQuerySchema,Ig as TrackerResponseSchema,Gg as TokenSchema,Xg as TokenDetailsMetadataSchema,vg as TONTransactionSchema,wg as TONTransactionMessageSchema,RR as SwapToResponseSchema,fR as SwapToRequestSchema,gR as SwapToAssetSchema,YR as SwapRouteV2ResponseSchema,P as SwapKitNumber,_ as SwapKitError,GR as SwapKitApi,mg as StarknetTransactionSchema,E as SKConfig,dg as RouteQuoteWarningSchema,Rg as RouteQuoteTxType,BR as RouteQuoteProviderErrorSchema,sg as RouteQuoteMetadataV2Schema,ug as RouteQuoteMetadataSchema,hg as RouteQuoteMetadataAssetSchema,rg as RouteLegWithoutAddressesSchema,cg as RouteLegSchema,Af as RequestClient,$R as QuoteV3ResponseSchema,MR as QuoteV2ResponseSchema,xR as QuoteRouteV2Response,ng as QuoteResponseSchema,lg as QuoteResponseRouteItem,_g as QuoteRequestSchema,Tf as ProviderName,Bg as ProviderAction,gg as PriorityLabel,Zg as PriceResponseSchema,Vg as PriceRequestSchema,X as NetworkDerivationPath,Eg as NearSwapResponseSchema,Hg as NearDepositChannelResultSchema,Fg as NearDepositChannelParamsSchema,i as MemoType,Nf as LedgerErrorCode,pg as GasSchema,ig as GasResponseSchema,qg as FeesSchema,Sf as FeeTypeEnum,b as FeeOption,Ng as EstimatedTimeSchema,Ef as ErrorCode,Ug as EVMTransactionSchema,kg as EVMTransactionDetailsSchema,yg as EVMTransactionDetailsParamsSchema,X$ as DerivationPath,jg as DepositChannelResponseSchema,Wg as DepositChannelParamsSchema,m as DEFAULT_FEE_MULTIPLIERS,bg as CosmosTransactionSchema,vf as CommonAssetStrings,Qg as CoinGeckoMetadataSchema,og as ChainflipMetadataSchema,Cg as BrokerDepositChannelParamsSchema,af as BigIntArithmetics,Pg as AssetValueSchema,ef as AssetValue,ag as ApproveResponseSchema,tg as ApproveRequestParams,qf as ApproveMode,eg as ApprovalTransactionSchema,Lg as ApiV2ErrorSchema};
@@ -254,12 +254,17 @@ export declare const SwapKitApi: {
254
254
  raw_data_hex: string;
255
255
  txID: string;
256
256
  visible: boolean;
257
+ data?: string | undefined;
258
+ value?: string | undefined;
259
+ } | {
260
+ messages: {
261
+ address: string;
262
+ amount: string;
263
+ payload?: string | undefined;
264
+ stateInit?: string | undefined;
265
+ }[];
266
+ sendMode: number;
257
267
  } | {
258
- address: string;
259
- amount: string;
260
- payload?: string | undefined;
261
- stateInit?: string | undefined;
262
- }[] | {
263
268
  calldata: string[];
264
269
  contractAddress: string;
265
270
  entrypoint: string;
@@ -228,12 +228,17 @@ export declare function getSwapQuote(json: QuoteRequest): Promise<{
228
228
  raw_data_hex: string;
229
229
  txID: string;
230
230
  visible: boolean;
231
+ data?: string | undefined;
232
+ value?: string | undefined;
233
+ } | {
234
+ messages: {
235
+ address: string;
236
+ amount: string;
237
+ payload?: string | undefined;
238
+ stateInit?: string | undefined;
239
+ }[];
240
+ sendMode: number;
231
241
  } | {
232
- address: string;
233
- amount: string;
234
- payload?: string | undefined;
235
- stateInit?: string | undefined;
236
- }[] | {
237
242
  calldata: string[];
238
243
  contractAddress: string;
239
244
  entrypoint: string;
@@ -11,7 +11,9 @@ export declare enum RouteQuoteTxType {
11
11
  EVM = "EVM",
12
12
  COSMOS = "COSMOS",
13
13
  RADIX = "RADIX",
14
- NEAR = "NEAR"
14
+ NEAR = "NEAR",
15
+ TON = "TON",
16
+ TRON = "TRON"
15
17
  }
16
18
  export declare enum TxnType {
17
19
  approve = "approve",
@@ -961,6 +963,9 @@ export declare const EstimatedTimeSchema: z.ZodObject<{
961
963
  total: z.ZodNumber;
962
964
  }, z.core.$strip>;
963
965
  export type EstimatedTime = z.infer<typeof EstimatedTimeSchema>;
966
+ export declare function isTransactionValue(value: string): boolean;
967
+ export declare function parseTransactionValue(value?: string | null): bigint;
968
+ export declare function toHexTransactionValue(value: string | number | bigint): string;
964
969
  export declare const EVMTransactionSchema: z.ZodObject<{
965
970
  data: z.ZodString;
966
971
  from: z.ZodString;
@@ -969,6 +974,7 @@ export declare const EVMTransactionSchema: z.ZodObject<{
969
974
  }, z.core.$strip>;
970
975
  export type EVMTransaction = z.infer<typeof EVMTransactionSchema>;
971
976
  export declare const TronTransactionSchema: z.ZodObject<{
977
+ data: z.ZodOptional<z.ZodString>;
972
978
  raw_data: z.ZodObject<{
973
979
  contract: z.ZodAny;
974
980
  data: z.ZodOptional<z.ZodString>;
@@ -980,6 +986,7 @@ export declare const TronTransactionSchema: z.ZodObject<{
980
986
  }, z.core.$loose>;
981
987
  raw_data_hex: z.ZodString;
982
988
  txID: z.ZodString;
989
+ value: z.ZodOptional<z.ZodString>;
983
990
  visible: z.ZodBoolean;
984
991
  }, z.core.$strip>;
985
992
  export type ApiTronTransaction = z.infer<typeof TronTransactionSchema>;
@@ -1096,12 +1103,21 @@ export declare const StarknetTransactionSchema: z.ZodArray<z.ZodObject<{
1096
1103
  entrypoint: z.ZodString;
1097
1104
  }, z.core.$strip>>;
1098
1105
  export type StarknetTransaction = z.infer<typeof StarknetTransactionSchema>;
1099
- export declare const TONTransactionSchema: z.ZodArray<z.ZodObject<{
1106
+ export declare const TONTransactionMessageSchema: z.ZodObject<{
1100
1107
  address: z.ZodString;
1101
1108
  amount: z.ZodString;
1102
1109
  payload: z.ZodOptional<z.ZodString>;
1103
1110
  stateInit: z.ZodOptional<z.ZodString>;
1104
- }, z.core.$strip>>;
1111
+ }, z.core.$strip>;
1112
+ export declare const TONTransactionSchema: z.ZodObject<{
1113
+ messages: z.ZodArray<z.ZodObject<{
1114
+ address: z.ZodString;
1115
+ amount: z.ZodString;
1116
+ payload: z.ZodOptional<z.ZodString>;
1117
+ stateInit: z.ZodOptional<z.ZodString>;
1118
+ }, z.core.$strip>>;
1119
+ sendMode: z.ZodNumber;
1120
+ }, z.core.$strip>;
1105
1121
  export type TONTransaction = z.infer<typeof TONTransactionSchema>;
1106
1122
  export declare const RouteLegSchema: z.ZodObject<{
1107
1123
  affiliate: z.ZodOptional<z.ZodString>;
@@ -1430,6 +1446,7 @@ export declare const QuoteResponseRouteItem: z.ZodObject<{
1430
1446
  }, z.core.$strip>>;
1431
1447
  sequence: z.ZodNumber;
1432
1448
  }, z.core.$strip>, z.ZodObject<{
1449
+ data: z.ZodOptional<z.ZodString>;
1433
1450
  raw_data: z.ZodObject<{
1434
1451
  contract: z.ZodAny;
1435
1452
  data: z.ZodOptional<z.ZodString>;
@@ -1441,17 +1458,21 @@ export declare const QuoteResponseRouteItem: z.ZodObject<{
1441
1458
  }, z.core.$loose>;
1442
1459
  raw_data_hex: z.ZodString;
1443
1460
  txID: z.ZodString;
1461
+ value: z.ZodOptional<z.ZodString>;
1444
1462
  visible: z.ZodBoolean;
1445
1463
  }, z.core.$strip>, z.ZodArray<z.ZodObject<{
1446
1464
  calldata: z.ZodArray<z.ZodString>;
1447
1465
  contractAddress: z.ZodString;
1448
1466
  entrypoint: z.ZodString;
1449
- }, z.core.$strip>>, z.ZodArray<z.ZodObject<{
1450
- address: z.ZodString;
1451
- amount: z.ZodString;
1452
- payload: z.ZodOptional<z.ZodString>;
1453
- stateInit: z.ZodOptional<z.ZodString>;
1454
- }, z.core.$strip>>, z.ZodString]>>;
1467
+ }, z.core.$strip>>, z.ZodObject<{
1468
+ messages: z.ZodArray<z.ZodObject<{
1469
+ address: z.ZodString;
1470
+ amount: z.ZodString;
1471
+ payload: z.ZodOptional<z.ZodString>;
1472
+ stateInit: z.ZodOptional<z.ZodString>;
1473
+ }, z.core.$strip>>;
1474
+ sendMode: z.ZodNumber;
1475
+ }, z.core.$strip>, z.ZodString]>>;
1455
1476
  txType: z.ZodOptional<z.ZodEnum<typeof RouteQuoteTxType>>;
1456
1477
  warnings: z.ZodArray<z.ZodObject<{
1457
1478
  code: z.ZodEnum<typeof WarningCodeEnum>;
@@ -1622,6 +1643,7 @@ export declare const QuoteResponseSchema: z.ZodObject<{
1622
1643
  }, z.core.$strip>>;
1623
1644
  sequence: z.ZodNumber;
1624
1645
  }, z.core.$strip>, z.ZodObject<{
1646
+ data: z.ZodOptional<z.ZodString>;
1625
1647
  raw_data: z.ZodObject<{
1626
1648
  contract: z.ZodAny;
1627
1649
  data: z.ZodOptional<z.ZodString>;
@@ -1633,17 +1655,21 @@ export declare const QuoteResponseSchema: z.ZodObject<{
1633
1655
  }, z.core.$loose>;
1634
1656
  raw_data_hex: z.ZodString;
1635
1657
  txID: z.ZodString;
1658
+ value: z.ZodOptional<z.ZodString>;
1636
1659
  visible: z.ZodBoolean;
1637
1660
  }, z.core.$strip>, z.ZodArray<z.ZodObject<{
1638
1661
  calldata: z.ZodArray<z.ZodString>;
1639
1662
  contractAddress: z.ZodString;
1640
1663
  entrypoint: z.ZodString;
1641
- }, z.core.$strip>>, z.ZodArray<z.ZodObject<{
1642
- address: z.ZodString;
1643
- amount: z.ZodString;
1644
- payload: z.ZodOptional<z.ZodString>;
1645
- stateInit: z.ZodOptional<z.ZodString>;
1646
- }, z.core.$strip>>, z.ZodString]>>;
1664
+ }, z.core.$strip>>, z.ZodObject<{
1665
+ messages: z.ZodArray<z.ZodObject<{
1666
+ address: z.ZodString;
1667
+ amount: z.ZodString;
1668
+ payload: z.ZodOptional<z.ZodString>;
1669
+ stateInit: z.ZodOptional<z.ZodString>;
1670
+ }, z.core.$strip>>;
1671
+ sendMode: z.ZodNumber;
1672
+ }, z.core.$strip>, z.ZodString]>>;
1647
1673
  txType: z.ZodOptional<z.ZodEnum<typeof RouteQuoteTxType>>;
1648
1674
  warnings: z.ZodArray<z.ZodObject<{
1649
1675
  code: z.ZodEnum<typeof WarningCodeEnum>;
@@ -2055,6 +2081,7 @@ export declare const QuoteRouteV2Response: z.ZodObject<{
2055
2081
  }, z.core.$strip>>;
2056
2082
  sequence: z.ZodNumber;
2057
2083
  }, z.core.$strip>, z.ZodObject<{
2084
+ data: z.ZodOptional<z.ZodString>;
2058
2085
  raw_data: z.ZodObject<{
2059
2086
  contract: z.ZodAny;
2060
2087
  data: z.ZodOptional<z.ZodString>;
@@ -2066,13 +2093,17 @@ export declare const QuoteRouteV2Response: z.ZodObject<{
2066
2093
  }, z.core.$loose>;
2067
2094
  raw_data_hex: z.ZodString;
2068
2095
  txID: z.ZodString;
2096
+ value: z.ZodOptional<z.ZodString>;
2069
2097
  visible: z.ZodBoolean;
2070
- }, z.core.$strip>, z.ZodArray<z.ZodObject<{
2071
- address: z.ZodString;
2072
- amount: z.ZodString;
2073
- payload: z.ZodOptional<z.ZodString>;
2074
- stateInit: z.ZodOptional<z.ZodString>;
2075
- }, z.core.$strip>>, z.ZodString]>>;
2098
+ }, z.core.$strip>, z.ZodObject<{
2099
+ messages: z.ZodArray<z.ZodObject<{
2100
+ address: z.ZodString;
2101
+ amount: z.ZodString;
2102
+ payload: z.ZodOptional<z.ZodString>;
2103
+ stateInit: z.ZodOptional<z.ZodString>;
2104
+ }, z.core.$strip>>;
2105
+ sendMode: z.ZodNumber;
2106
+ }, z.core.$strip>, z.ZodString]>>;
2076
2107
  txType: z.ZodOptional<z.ZodEnum<typeof RouteQuoteTxType>>;
2077
2108
  }, z.core.$strip>;
2078
2109
  export declare const RouteQuoteProviderErrorSchema: z.ZodObject<{
@@ -2255,6 +2286,7 @@ export declare const QuoteV2ResponseSchema: z.ZodObject<{
2255
2286
  }, z.core.$strip>>;
2256
2287
  sequence: z.ZodNumber;
2257
2288
  }, z.core.$strip>, z.ZodObject<{
2289
+ data: z.ZodOptional<z.ZodString>;
2258
2290
  raw_data: z.ZodObject<{
2259
2291
  contract: z.ZodAny;
2260
2292
  data: z.ZodOptional<z.ZodString>;
@@ -2266,13 +2298,17 @@ export declare const QuoteV2ResponseSchema: z.ZodObject<{
2266
2298
  }, z.core.$loose>;
2267
2299
  raw_data_hex: z.ZodString;
2268
2300
  txID: z.ZodString;
2301
+ value: z.ZodOptional<z.ZodString>;
2269
2302
  visible: z.ZodBoolean;
2270
- }, z.core.$strip>, z.ZodArray<z.ZodObject<{
2271
- address: z.ZodString;
2272
- amount: z.ZodString;
2273
- payload: z.ZodOptional<z.ZodString>;
2274
- stateInit: z.ZodOptional<z.ZodString>;
2275
- }, z.core.$strip>>, z.ZodString]>>;
2303
+ }, z.core.$strip>, z.ZodObject<{
2304
+ messages: z.ZodArray<z.ZodObject<{
2305
+ address: z.ZodString;
2306
+ amount: z.ZodString;
2307
+ payload: z.ZodOptional<z.ZodString>;
2308
+ stateInit: z.ZodOptional<z.ZodString>;
2309
+ }, z.core.$strip>>;
2310
+ sendMode: z.ZodNumber;
2311
+ }, z.core.$strip>, z.ZodString]>>;
2276
2312
  txType: z.ZodOptional<z.ZodEnum<typeof RouteQuoteTxType>>;
2277
2313
  }, z.core.$strip>>;
2278
2314
  }, z.core.$strip>;
@@ -2442,6 +2478,7 @@ export declare const SwapRouteV2ResponseSchema: z.ZodObject<{
2442
2478
  }, z.core.$strip>>;
2443
2479
  sequence: z.ZodNumber;
2444
2480
  }, z.core.$strip>, z.ZodObject<{
2481
+ data: z.ZodOptional<z.ZodString>;
2445
2482
  raw_data: z.ZodObject<{
2446
2483
  contract: z.ZodAny;
2447
2484
  data: z.ZodOptional<z.ZodString>;
@@ -2453,13 +2490,17 @@ export declare const SwapRouteV2ResponseSchema: z.ZodObject<{
2453
2490
  }, z.core.$loose>;
2454
2491
  raw_data_hex: z.ZodString;
2455
2492
  txID: z.ZodString;
2493
+ value: z.ZodOptional<z.ZodString>;
2456
2494
  visible: z.ZodBoolean;
2457
- }, z.core.$strip>, z.ZodArray<z.ZodObject<{
2458
- address: z.ZodString;
2459
- amount: z.ZodString;
2460
- payload: z.ZodOptional<z.ZodString>;
2461
- stateInit: z.ZodOptional<z.ZodString>;
2462
- }, z.core.$strip>>, z.ZodString]>>;
2495
+ }, z.core.$strip>, z.ZodObject<{
2496
+ messages: z.ZodArray<z.ZodObject<{
2497
+ address: z.ZodString;
2498
+ amount: z.ZodString;
2499
+ payload: z.ZodOptional<z.ZodString>;
2500
+ stateInit: z.ZodOptional<z.ZodString>;
2501
+ }, z.core.$strip>>;
2502
+ sendMode: z.ZodNumber;
2503
+ }, z.core.$strip>, z.ZodString]>>;
2463
2504
  txType: z.ZodOptional<z.ZodEnum<typeof RouteQuoteTxType>>;
2464
2505
  approvalTx: z.ZodOptional<z.ZodObject<{
2465
2506
  data: z.ZodString;
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "author": "swapkit-dev",
3
3
  "dependencies": { "@swapkit/contracts": "4.1.5", "@swapkit/tokens": "4.3.1", "@swapkit/types": "0.9.0" },
4
4
  "description": "SwapKit - Helpers",
5
- "devDependencies": { "@near-js/providers": "2.5.1", "@swapkit/toolboxes": "4.20.0", "ethers": "6.16.0" },
5
+ "devDependencies": { "@near-js/providers": "2.5.1", "@swapkit/toolboxes": "4.20.1", "ethers": "6.16.0" },
6
6
  "exports": {
7
7
  ".": { "default": "./dist/index.js", "require": "./dist/index.cjs", "types": "./dist/types/index.d.ts" },
8
8
  "./api": {
@@ -39,5 +39,5 @@
39
39
  "type-check:go": "tsgo"
40
40
  },
41
41
  "type": "module",
42
- "version": "4.15.2"
42
+ "version": "4.15.3"
43
43
  }
@@ -1,5 +0,0 @@
1
- var sA=Object.defineProperty;var eA=(N)=>N;function aA(N,A){this[N]=eA.bind(null,A)}var dN=(N,A)=>{for(var T in A)sA(N,T,{get:A[T],enumerable:!0,configurable:!0,set:aA.bind(A,T)})};var LN=((N)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(N,{get:(A,T)=>(typeof require<"u"?require:A)[T]}):N)(function(N){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+N+'" is not supported')});import{Chain as XN,getChainConfig as rT}from"@swapkit/types";import{AllChains as KT,Chain as b,EVMChains as mT,getChainConfig as nN}from"@swapkit/types";import{getAddress as BA}from"ethers";import{match as vN}from"ts-pattern";import{Chain as n,EVMChains as xT,getChainConfig as o,UTXOChains as QT}from"@swapkit/types";import{match as FN}from"ts-pattern";import{AllChains as lN,Chain as cN,getChainConfig as RT,MAYAConfig as FT,StagenetChain as MN,StagenetMAYAConfig as rN,StagenetTHORConfig as iN,THORConfig as uT}from"@swapkit/types";import{createStore as IT}from"zustand/vanilla";import{AllChains as NT,getChainConfig as AT}from"@swapkit/types";var wP=NT.reduce((N,A)=>{return N[A]=AT(A).networkDerivationPath,N},{});var RN;((u)=>{u.unknownError="unknownError";u.test_error="test_error";u.providerDetailsError="providerDetailsError";u.blockHeaderNotFound="blockHeaderNotFound";u.blockHashNotFoundAtHeight="blockHashNotFoundAtHeight";u.blockHashNotFoundAtHash="blockHashNotFoundAtHash";u.txHashMissing="txHashMissing";u.assetValueMissingInfo="assetValueMissingInfo";u.invalidAsset="invalidAsset";u.blockIsRequired="blockIsRequired";u.currentBlockHeaderNotFound="currentBlockHeaderNotFound";u.failedToRetrieveBalance="failedToRetrieveBalance";u.failedToRetrieveBlock="failedToRetrieveBlock";u.failedToRetrieveFees="failedToRetrieveFees";u.notImplementedBCH="notImplementedBCH";u.notImplementedDoge="notImplementedDoge";u.noPoolsFound="noPoolsFound";u.noVaultsFound="noVaultsFound";u.noTxFound="noTxFound";u.noInputCoinFound="noInputCoinFound";u.noBlockDataFound="noBlockDataFound";u.multipleCosmosMessages="multipleCosmosMessages";u.heightOrHashNotProvided="heightOrHashNotProvided";u.unknownDenom="unknownDenom";u.invalidBlockHeight="invalidBlockHeight";u.timestampExtrinsicNoArgumentsForBlock="timestampExtrinsicNoArgumentsForBlock";u.timestampExtrinsicNoTimestampForBlock="timestampExtrinsicNoTimestampForBlock";u.noTimestampExtrinsicForHash="noTimestampExtrinsicForHash";u.timestampExtrinsicNoArgumentsForHash="timestampExtrinsicNoArgumentsForHash";u.txMemoUndefined="txMemoUndefined";u.txMemoIncorrect="txMemoIncorrect";u.txTypeNotFound="txTypeNotFound";u.txNoMessage="txNoMessage";u.txNotFound="txNotFound";u.txReceiptNotFound="txReceiptNotFound";u.txParsingError="txParsingError";u.txLogsParsingError="txLogsParsingError";u.blockNotFound="blockNotFound";u.balanceNotFound="balanceNotFound";u.configError="configError";u.synthSwapDisallowed="synthSwapDisallowed";u.providerQuoteTimeout="providerQuoteTimeout";u.noQuoteResponse="noQuoteResponse";u.noPoolAssetsFound="noPoolAssetsFound";u.noThorchainPools="noThorchainPools";u.noMayachainPools="noMayachainPools";u.noThorchainNetworkInfo="noThorchainNetworkInfo";u.invalidAffiliateFee="invalidAffiliateFee";u.invalidBuyAssetAddress="invalidBuyAssetAddress";u.invalidSellAssetAddress="invalidSellAssetAddress";u.invalidSourceAddress="invalidSourceAddress";u.invalidDestinationAddress="invalidDestinationAddress";u.sourceAddressIsSmartContract="sourceAddressIsSmartContract";u.destinationAddressIsSmartContract="destinationAddressIsSmartContract";u.invalidChainId="invalidChainId";u.unsupportedChainId="unsupportedChainId";u.unsupportedEVMChainId="unsupportedEVMChainId";u.unsupportedMethod="unsupportedMethod";u.unsupportedProvider="unsupportedProvider";u.invalidParamsForMethod="invalidParamsForMethod";u.unsupportedAdapter="unsupportedAdapter";u.noWhitelistTokens="noWhitelistTokens";u.failedFetchGasPrice="failedFetchGasPrice";u.failedToCreateDepositChannel="failedToCreateDepositChannel";u.noProviderDetailsFound="noProviderDetailsFound";u.noTokenListsFound="noTokenListsFound";u.tokenNotFound="tokenNotFound";u.tokenPriceNotFound="tokenPriceNotFound";u.tokenPriceFailedToUpdate="tokenPriceFailedToUpdate";u.swapAmountTooSmall="swapAmountTooSmall";u.legsArrayIsEmpty="legsArrayIsEmpty";u.failedToFetchQuoteForLeg="failedToFetchQuoteForLeg";u.noBlockHeaderFound="noBlockHeaderFound";u.failedToSimulateSwap="failedToSimulateSwap";u.addressScreeningFailed="addressScreeningFailed";u.noLiquidtyProvidersFound="noLiquidtyProvidersFound";u.insufficientLiquidity="insufficientLiquidity";u.noInboundDataFound="noInbounDataFound";u.noInboundAddressesFound="noInboundAddressesFound";u.noInboundAddressFoundForChain="noInboundAddressFoundForChain";u.noLastBlocksFound="noLastBlocksFound";u.noVersionFound="noVersionFound";u.noConstantsFound="noConstantsFound";u.noMimirsFound="noMimirsFound";u.noRoutesFound="noRoutesFound";u.quoteNotFound="quoteNotFound";u.ledgerSignFailed="ledgerSignFailed";u.ledgerWrongPayload="ledgerWrongPayload";u.ledgerFetchSwapFailed="ledgerFetchSwapFailed";u.failedToFetchTx="failedToFetchTx";u.failedBuildTransactionDetails="failedBuildTransactionDetails";u.noLegsForRoute="noLegsForRoute";u.noRouterAddressFound="noRouterAddressFound";u.noAggregatorAddressFound="noAggregatorAddressFound";u.noContractInstanceFound="noContractInstanceFound";u.noContractAddressFound="noContractAddressFound";u.invalidAffiliate="invalidAffiliate";u.thornameAffiliate="thornameAffiliate";u.providerNotfound="No provider found";u.noRecordFound="No Record found";u.slippageTooLow="Slippage too low";u.tradingHalted="tradingHalted";u.noWrappedGasAsset="noWrappedGasAsset";u.aggregatorAddressNotFound="aggregatorAddressNotFound";u.routerAddressNotFound="routerAddressNotFound";u.dummyAddressNotFound="dummyAddressNotFound";u.trackerError="trackerError";u.thorchainPoolUnavailable="thorchainPoolUnavailable";u.noOhlcvDataFound="noOhlcvDataFound";u.noTradingPairs="noTradingPairs";u.noLendingAvailability="noLendingAvailability";u.lendingRepayTooSmall="lendingRepayTooSmall";u.missingState="missingState";u.ledgerSwapNotFound="ledgerSwapNotFound";u.ledgerSwapNotReadyForTracking="ledgerSwapNotReadyForTracking";u.errorEstimatingGas="errorEstimatingGas";u.apiKeyInvalid="apiKeyInvalid";u.apiKeyFailedToUpdate="apiKeyFailedToUpdate";u.apiKeyExpired="apiKeyExpired";u.unauthorized="unauthorized";u.failedToCreateMemo="failedToCreateMemo";u.radixIncorrectInstructions="radixIncorrectInstructions";u.radixTxMissedParam="radixTxMissedParam";u.radixTxMissedAccount="radixTxMissedAccount";u.radixManifestParseError="radixManifestParseError";u.radixManifestBuildError="radixManifestBuildError";u.invalidAddressForChain="invalidAddressForChain";u.riskyAddress="riskyAddress";u.noRoutesToProcess="noRoutesToProcess";u.sellAssetAmountTooSmall="sellAssetAmountTooSmall";u.missingPrivateKey="missingPrivateKey";u.noMemoPriceProtection="noMemoPriceProtection"})(RN||={});var xN;((T)=>{T.highSlippage="highSlippage";T.highPriceImpact="highPriceImpact"})(xN||={});var J;((E)=>{E.CHAINFLIP="CHAINFLIP";E.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";E.JUPITER="JUPITER";E.MAYACHAIN="MAYACHAIN";E.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";E.ONEINCH="ONEINCH";E.PANCAKESWAP="PANCAKESWAP";E.SUSHISWAP_V2="SUSHISWAP_V2";E.THORCHAIN="THORCHAIN";E.THORCHAIN_STREAMING="THORCHAIN_STREAMING";E.TRADERJOE_V2="TRADERJOE_V2";E.UNISWAP_V2="UNISWAP_V2";E.UNISWAP_V3="UNISWAP_V3";E.NEAR="NEAR";E.GARDEN="GARDEN";E.OKX="OKX";E.HARBOR="HARBOR";E.FLASHNET="FLASHNET";E.MAYAN="MAYAN"})(J||={});var QN;(($)=>{$.LIQUIDITY="liquidity";$.NETWORK="network";$.INBOUND="inbound";$.OUTBOUND="outbound";$.AFFILIATE="affiliate";$.TAX="tax";$.PRIORITY="priority";$.SERVICE="service"})(QN||={});var TT;((H)=>{H.Average="average";H.Fast="fast";H.Fastest="fastest"})(TT||={});var HT;((T)=>{T.Approve="approve";T.CheckOnly="checkOnly"})(HT||={});var PT;((D)=>{D.NAME_REGISTER="~";D.BOND="BOND";D.DEPOSIT="+";D.LEAVE="LEAVE";D.UNBOND="UNBOND";D.WITHDRAW="-";D.RUNEPOOL_DEPOSIT="POOL+";D.RUNEPOOL_WITHDRAW="POOL-";D.CLAIM_TCY="tcy";D.STAKE_TCY="tcy+";D.UNSTAKE_TCY="tcy-"})(PT||={});var wN;((Y)=>{Y.BITGET="BITGET";Y.BRAVE="BRAVE";Y.COINBASE_MOBILE="COINBASE_MOBILE";Y.COINBASE_WEB="COINBASE_WEB";Y.COSMOSTATION="COSMOSTATION";Y.CTRL="CTRL";Y.EIP6963="EIP6963";Y.EXODUS="EXODUS";Y.KEEPKEY="KEEPKEY";Y.KEEPKEY_BEX="KEEPKEY_BEX";Y.KEPLR="KEPLR";Y.KEYSTORE="KEYSTORE";Y.LEAP="LEAP";Y.LEDGER="LEDGER";Y.METAMASK="METAMASK";Y.OKX="OKX";Y.OKX_MOBILE="OKX_MOBILE";Y.ONEKEY="ONEKEY";Y.PASSKEYS="PASSKEYS";Y.PASSKEY_WALLET="PASSKEY_WALLET";Y.PETRA="PETRA";Y.PHANTOM="PHANTOM";Y.POLKADOT_JS="POLKADOT_JS";Y.RADIX_WALLET="RADIX_WALLET";Y.TALISMAN="TALISMAN";Y.TREZOR="TREZOR";Y.TRONLINK="TRONLINK";Y.TRUSTWALLET_WEB="TRUSTWALLET_WEB";Y.VULTISIG="VULTISIG";Y.WALLETCONNECT="WALLETCONNECT";Y.WALLET_SELECTOR="WALLET_SELECTOR";Y.XAMAN="XAMAN"})(wN||={});var LT;((H)=>{H[H.NoError=36864]="NoError";H[H.LockedDevice=21781]="LockedDevice";H[H.TC_NotFound=65535]="TC_NotFound"})(LT||={});var nT=lN.reduce((N,A)=>{if(!N.THOR_STAGENET)N[MN.Maya]=rN.rpcUrls,N[MN.THORChain]=iN.rpcUrls;return N[A]=RT(A).rpcUrls,N},{}),BT={[cN.THORChain]:uT.nodeUrl,[cN.Maya]:FT.nodeUrl,[MN.THORChain]:iN.nodeUrl,[MN.Maya]:rN.nodeUrl},sN={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:lN,endpoints:{},envs:{apiUrl:"https://api.swapkit.dev",devApiUrl:"https://dev-api.swapkit.dev",isDev:!1,isStagenet:!1},feeMultipliers:void 0,integrations:{radix:{applicationName:"Swapkit Playground",applicationVersion:"0.0.1",dAppDefinitionAddress:"account_rdx128r289p58222hcvev7frs6kue76pl7pdcnw8725aw658v0zggkh9ws",network:{dashboardBase:"https://dashboard.radixdlt.com",networkId:1,networkName:"mainnet"}}},localMode:{enabled:!1,quoteUrl:"http://localhost:3000",swapUrl:"http://localhost:3001"},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:nT,thornodeUrls:BT,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(wN),widgetId:"",widgetKey:""},Z=IT((N)=>({...sN,setApiKey:(A,T)=>N((H)=>({apiKeys:{...H.apiKeys,[A]:T}})),setConfig:(A)=>N((T)=>({apiKeys:{...T.apiKeys,...A?.apiKeys},chains:T.chains.concat(A?.chains||[]),endpoints:{...T.endpoints,...A?.endpoints},envs:{...T.envs,...A?.envs},feeMultipliers:A?.feeMultipliers||T.feeMultipliers,integrations:{...T.integrations,...A?.integrations},localMode:{...T.localMode,...A?.localMode},rpcUrls:{...T.rpcUrls,...A?.rpcUrls},thornodeUrls:{...T.thornodeUrls,...A?.thornodeUrls},v3SwapFlow:{...T.v3SwapFlow,...A?.v3SwapFlow},wallets:T.wallets.concat(A?.wallets||[]),widgetId:A?.widgetId||T.widgetId,widgetKey:A?.widgetKey||T.widgetKey})),setEndpoint:(A,T)=>N((H)=>({endpoints:{...H.endpoints,[A]:T}})),setEnv:(A,T)=>N((H)=>({envs:{...H.envs,[A]:T}})),setFeeMultipliers:(A)=>N(()=>({feeMultipliers:A})),setIntegrationConfig:(A,T)=>N((H)=>({integrations:{...H.integrations,[A]:T}})),setRequestOptions:(A)=>N((T)=>({requestOptions:{retry:{...T.requestOptions.retry,...A.retry},timeoutMs:A.timeoutMs||T.requestOptions.timeoutMs}})),setRpcUrl:(A,T)=>N((H)=>({rpcUrls:{...H.rpcUrls,[A]:T}})),setThornodeUrl:(A,T)=>N((H)=>({thornodeUrls:{...H.thornodeUrls,[A]:T}})),setWidgetId:(A)=>N({widgetId:A}),setWidgetKey:(A)=>N({widgetKey:A})})),X={get:(N)=>Z.getState()[N],getState:Z.getState,reinitialize:()=>Z.setState(sN),set:(N)=>Z.getState().setConfig(N),setApiKey:(N,A)=>Z.getState().setApiKey(N,A),setEndpoint:(N,A)=>Z.getState().setEndpoint(N,A),setEnv:(N,A)=>Z.getState().setEnv(N,A),setFeeMultipliers:(N)=>Z.getState().setFeeMultipliers(N),setIntegrationConfig:(N,A)=>Z.getState().setIntegrationConfig(N,A),setRequestOptions:(N)=>Z.getState().setRequestOptions(N),setRpcUrl:(N,A)=>Z.getState().setRpcUrl(N,A),setThornodeUrl:(N,A)=>Z.getState().setThornodeUrl(N,A),setWidgetId:(N)=>Z.getState().setWidgetId(N),setWidgetKey:(N)=>Z.getState().setWidgetKey(N)};var OT={core_estimated_max_spendable_chain_not_supported:10001,core_extend_error:10002,core_inbound_data_not_found:10003,core_approve_asset_address_or_from_not_found:10004,core_plugin_not_found:10005,core_plugin_swap_not_found:10006,core_approve_asset_target_invalid:10007,core_explorer_unsupported_chain:10008,core_verify_message_not_supported:10009,core_chain_halted:10010,core_wallet_connection_not_found:10101,core_wallet_ctrl_not_installed:10102,core_wallet_evmwallet_not_installed:10103,core_wallet_walletconnect_not_installed:10104,core_wallet_keystore_not_installed:10105,core_wallet_ledger_not_installed:10106,core_wallet_trezor_not_installed:10107,core_wallet_keplr_not_installed:10108,core_wallet_okx_not_installed:10109,core_wallet_keepkey_not_installed:10110,core_wallet_talisman_not_installed:10111,core_wallet_not_keypair_wallet:10112,core_wallet_sign_message_not_supported:10113,core_wallet_connection_failed:10114,core_wallet_create_not_supported:10115,core_wallet_sign_typed_data_not_supported:10116,core_swap_invalid_params:10201,core_swap_route_not_complete:10202,core_swap_asset_not_recognized:10203,core_swap_contract_not_found:10204,core_swap_route_transaction_not_found:10205,core_swap_contract_not_supported:10206,core_swap_transaction_error:10207,core_swap_quote_mode_not_supported:10208,core_transaction_deposit_error:10301,core_transaction_create_liquidity_base_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_base_address:10306,core_transaction_add_liquidity_base_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_invalid_sender_address:10313,core_transaction_deposit_server_error:10314,core_transaction_user_rejected:10315,core_transaction_failed:10316,core_transaction_invalid_recipient_address:10317,wallet_connection_rejected_by_user:20001,wallet_missing_api_key:20002,wallet_chain_not_supported:20003,wallet_missing_params:20004,wallet_provider_not_found:20005,wallet_failed_to_add_or_switch_network:20006,wallet_ledger_connection_error:20101,wallet_ledger_connection_claimed:20102,wallet_ledger_get_address_error:20103,wallet_ledger_device_not_found:20104,wallet_ledger_device_locked:20105,wallet_ledger_transport_error:20106,wallet_ledger_public_key_error:20107,wallet_ledger_derivation_path_error:20108,wallet_ledger_signing_error:20109,wallet_ledger_app_not_open:20110,wallet_ledger_invalid_response:20111,wallet_ledger_method_not_supported:20112,wallet_ledger_invalid_params:20113,wallet_ledger_invalid_signature:20114,wallet_ledger_no_provider:20115,wallet_ledger_pubkey_not_found:20116,wallet_ledger_transport_not_defined:20117,wallet_ledger_webusb_not_supported:20118,wallet_ledger_chain_not_supported:20119,wallet_ledger_invalid_asset:20120,wallet_ledger_invalid_account:20121,wallet_ledger_address_not_found:20122,wallet_ledger_failed_to_get_address:20123,wallet_ledger_webhid_not_supported:20124,wallet_phantom_not_found:20201,wallet_ctrl_not_found:20301,wallet_ctrl_send_transaction_no_address:20302,wallet_ctrl_contract_address_not_provided:20303,wallet_ctrl_asset_not_defined:20304,wallet_walletconnect_project_id_not_specified:20401,wallet_walletconnect_connection_not_established:20402,wallet_walletconnect_namespace_not_supported:20403,wallet_walletconnect_chain_not_supported:20404,wallet_walletconnect_invalid_method:20405,wallet_walletconnect_method_not_supported:20406,wallet_trezor_failed_to_sign_transaction:20501,wallet_trezor_derivation_path_not_supported:20502,wallet_trezor_failed_to_get_address:20503,wallet_trezor_transport_error:20504,wallet_trezor_method_not_supported:20505,wallet_trezor_failed_to_get_public_key:20506,wallet_talisman_not_enabled:20601,wallet_talisman_not_found:20602,wallet_polkadot_not_found:20701,wallet_radix_not_found:20801,wallet_radix_transaction_failed:20802,wallet_radix_invalid_manifest:20803,wallet_radix_method_not_supported:20804,wallet_radix_no_account:20805,wallet_keepkey_not_found:20901,wallet_keepkey_asset_not_defined:20902,wallet_keepkey_contract_address_not_provided:20903,wallet_keepkey_send_transaction_no_address:20904,wallet_keepkey_derivation_path_error:20905,wallet_keepkey_signing_error:20906,wallet_keepkey_transport_error:20907,wallet_keepkey_unsupported_chain:20908,wallet_keepkey_invalid_response:20909,wallet_keepkey_chain_not_supported:20910,wallet_keepkey_signer_not_found:20911,wallet_keepkey_no_accounts:20912,wallet_keepkey_method_not_supported:20913,wallet_keepkey_invalid_params:20914,wallet_keepkey_config_not_found:20915,wallet_keepkey_no_provider:20916,wallet_keepkey_account_not_found:20917,wallet_keepkey_failed_to_get_public_key:20918,wallet_bitkeep_not_found:21001,wallet_bitkeep_failed_to_switch_network:21002,wallet_bitkeep_no_accounts:21003,wallet_passkeys_sign_transaction_error:21101,wallet_passkeys_not_found:21102,wallet_passkeys_no_address:21103,wallet_passkeys_request_canceled:21104,wallet_passkeys_signature_canceled:21105,wallet_passkeys_failed_to_switch_network:21106,wallet_passkeys_chain_not_supported:21107,wallet_passkeys_instance_missing:21108,wallet_onekey_not_found:21201,wallet_onekey_sign_transaction_error:21202,wallet_okx_not_found:21301,wallet_okx_chain_not_supported:21302,wallet_okx_failed_to_switch_network:21303,wallet_okx_no_accounts:21304,wallet_keplr_not_found:21401,wallet_keplr_chain_not_supported:21402,wallet_keplr_signer_not_found:21403,wallet_keplr_no_accounts:21404,wallet_cosmostation_not_found:21501,wallet_cosmostation_chain_not_supported:21502,wallet_cosmostation_evm_provider_not_found:21503,wallet_cosmostation_keplr_provider_not_found:21504,wallet_cosmostation_no_accounts:21505,wallet_cosmostation_no_evm_accounts:21506,wallet_cosmostation_no_evm_address:21507,wallet_cosmostation_signer_not_found:21508,wallet_passkey_not_supported:21601,wallet_passkey_connection_failed:21602,wallet_coinbase_not_found:21701,wallet_coinbase_chain_not_supported:21702,wallet_coinbase_method_not_supported:21703,wallet_coinbase_no_accounts:21704,wallet_evm_extensions_failed_to_switch_network:21801,wallet_evm_extensions_no_provider:21802,wallet_evm_extensions_not_found:21803,wallet_keystore_invalid_password:21901,wallet_keystore_unsupported_version:21902,wallet_near_extensions_failed_to_switch_network:22001,wallet_near_extensions_no_provider:22002,wallet_near_extensions_not_found:22003,wallet_near_method_not_supported:22004,wallet_petra_not_found:22201,wallet_vultisig_not_found:22101,wallet_vultisig_contract_address_not_provided:22102,wallet_vultisig_asset_not_defined:22103,wallet_vultisig_send_transaction_no_address:22104,wallet_xaman_not_configured:23001,wallet_xaman_not_connected:23002,wallet_xaman_auth_failed:23003,wallet_xaman_connection_failed:23004,wallet_xaman_transaction_failed:23005,wallet_xaman_monitoring_failed:23006,wallet_tronlink_request_accounts_failed:24001,wallet_tronlink_locked:24002,chainflip_channel_error:30001,chainflip_unknown_asset:30002,chainflip_broker_invalid_params:30101,chainflip_broker_recipient_error:30102,chainflip_broker_register:30103,chainflip_broker_tx_error:30104,chainflip_broker_withdraw:30105,chainflip_broker_fund_only_flip_supported:30106,chainflip_broker_fund_invalid_address:30107,thorchain_chain_halted:40001,thorchain_trading_halted:40002,thorchain_asset_is_not_tcy:40003,thorchain_swapin_router_required:40101,thorchain_swapin_vault_required:40102,thorchain_swapin_memo_required:40103,thorchain_swapin_token_required:40104,thorchain_preferred_asset_payout_required:40105,toolbox_cosmos_account_not_found:50101,toolbox_cosmos_invalid_fee:50102,toolbox_cosmos_invalid_params:50103,toolbox_cosmos_no_signer:50104,toolbox_cosmos_not_supported:50105,toolbox_cosmos_signer_not_defined:50106,toolbox_cosmos_validate_address_prefix_not_found:50107,toolbox_cosmos_verify_signature_no_pubkey:50108,toolbox_evm_error_estimating_gas_limit:50201,toolbox_evm_error_sending_transaction:50202,toolbox_evm_gas_estimation_error:50203,toolbox_evm_invalid_gas_asset_address:50204,toolbox_evm_invalid_params:50205,toolbox_evm_invalid_transaction:50206,toolbox_evm_no_abi_fragment:50207,toolbox_evm_no_contract_address:50208,toolbox_evm_no_fee_data:50209,toolbox_evm_no_from_address:50210,toolbox_evm_no_gas_price:50211,toolbox_evm_no_signer_address:50212,toolbox_evm_no_signer:50213,toolbox_evm_no_to_address:50214,toolbox_evm_not_supported:50215,toolbox_evm_provider_not_eip1193_compatible:50216,toolbox_evm_invalid_eip7702_authorization:50217,toolbox_utxo_api_error:50301,toolbox_utxo_broadcast_failed:50302,toolbox_utxo_insufficient_balance:50303,toolbox_utxo_invalid_address:50304,toolbox_utxo_invalid_params:50305,toolbox_utxo_invalid_transaction:50306,toolbox_utxo_no_signer:50307,toolbox_utxo_not_supported:50308,toolbox_utxo_tx_not_found:50309,toolbox_utxo_rbf_not_supported:50310,toolbox_utxo_tx_not_replaceable:50311,toolbox_utxo_tx_already_confirmed:50312,toolbox_utxo_rbf_fee_too_low:50313,toolbox_utxo_rbf_insufficient_change:50314,toolbox_solana_no_signer:50401,toolbox_substrate_not_supported:50501,toolbox_substrate_transfer_error:50502,toolbox_radix_method_not_supported:50601,toolbox_ripple_get_balance_error:50701,toolbox_ripple_rpc_not_configured:50702,toolbox_ripple_signer_not_found:50703,toolbox_ripple_asset_not_supported:50704,toolbox_ripple_broadcast_error:50705,toolbox_ripple_get_trust_lines_error:50706,toolbox_ripple_invalid_trust_line_limit:50707,toolbox_tron_no_signer:50801,toolbox_tron_invalid_token_identifier:50802,toolbox_tron_token_transfer_failed:50803,toolbox_tron_transaction_creation_failed:50804,toolbox_tron_trongrid_api_error:50805,toolbox_tron_approve_failed:50806,toolbox_tron_invalid_token_contract:50807,toolbox_tron_allowance_check_failed:50808,toolbox_tron_invalid_transaction_integrity:50809,toolbox_tron_broadcast_failed:50810,toolbox_hypercore_no_signer:51001,toolbox_cardano_sign_transaction_failed:50901,toolbox_near_no_signer:90601,toolbox_near_invalid_address:90602,toolbox_near_invalid_amount:90603,toolbox_near_transfer_failed:90604,toolbox_near_access_key_error:90605,toolbox_near_no_rpc_url:90606,toolbox_near_empty_batch:90607,toolbox_near_balance_failed:90608,toolbox_near_invalid_name:90609,toolbox_near_missing_contract_address:90610,toolbox_near_no_account:90611,toolbox_near_invalid_gas_params:90612,toolbox_near_no_public_key_found:90613,toolbox_near_sign_transaction_failed:90614,toolbox_sui_address_required:90701,toolbox_sui_keypair_required:90702,toolbox_sui_balance_error:90703,toolbox_sui_transaction_creation_error:90704,toolbox_sui_signing_error:90705,toolbox_sui_broadcast_error:90706,toolbox_sui_no_signer:90707,toolbox_sui_no_sender:90708,toolbox_sui_missing_coin_type:90709,toolbox_sui_no_coins_found:90710,toolbox_sui_insufficient_balance:90711,toolbox_starknet_no_signer:90801,toolbox_starknet_invalid_address:90802,toolbox_starknet_fee_estimation_failed:90803,toolbox_starknet_account_not_deployed:90804,toolbox_starknet_transaction_failed:90805,toolbox_ton_no_signer:90901,toolbox_ton_invalid_address:90902,toolbox_ton_missing_jetton_address:90903,toolbox_ton_jetton_transfer_failed:90904,toolbox_ton_transaction_failed:90905,toolbox_aptos_address_required:91001,toolbox_aptos_keypair_required:91002,toolbox_aptos_balance_error:91003,toolbox_aptos_transaction_creation_error:91004,toolbox_aptos_signing_error:91005,toolbox_aptos_broadcast_error:91006,toolbox_aptos_no_signer:91007,toolbox_aptos_no_sender:91008,toolbox_aptos_missing_asset_type:91009,toolbox_aptos_insufficient_balance:91010,toolbox_stellar_no_signer:91101,toolbox_stellar_broadcast_error:91102,toolbox_stellar_invalid_address:91103,toolbox_stellar_account_not_found:91104,toolbox_stellar_transaction_failed:91105,toolbox_stellar_balance_error:91106,toolbox_not_supported:59901,toolbox_fee_estimation_failed:59902,plugin_near_invalid_name:41001,plugin_near_no_connection:41002,plugin_near_name_unavailable:41003,plugin_near_registration_failed:41004,plugin_near_transfer_failed:41005,plugin_garden_missing_data:42001,plugin_swapkit_swap_invalid_data:43001,plugin_swapkit_invalid_transaction:43002,api_v2_invalid_response:60001,api_v2_server_error:60002,api_v2_invalid_method_key_hash:60003,helpers_invalid_number_different_decimals:70001,helpers_invalid_number_of_years:70002,helpers_invalid_identifier:70003,helpers_invalid_asset_url:70004,helpers_invalid_asset_identifier:70005,helpers_invalid_memo_type:70006,helpers_failed_to_switch_network:70007,helpers_not_found_provider:70008,helpers_chain_not_supported:70009,helpers_invalid_params:70010,helpers_invalid_response:70011,helpers_chain_no_public_or_set_rpc_url:70012,helpers_chain_rpc_connection_failed:70013,mcp_wallet_not_configured:90001,not_implemented:99999};function zN(N){return JSON.stringify(N,(A,T)=>typeof T==="bigint"?T.toString():T)}class g extends Error{static ErrorCode=OT;errorKey;info;constructor(N,A){let T=typeof N==="string",H=T?N:N.errorKey,P=T?void 0:N.info,F=`${H}${P?`: ${zN(P)}`:""}`;super(F);if(Object.setPrototypeOf(this,g.prototype),this.name="SwapKitError",this.errorKey=H,this.info=P,this.cause=A,A){let I=A instanceof Error?`${A.message}${A.cause?` (${A.cause})`:""}`:zN(A);console.error(`SwapKitError [${H}]: ${I}`)}else if(P)console.error(`SwapKitError [${H}]: ${zN(P)}`)}}var $T=(N)=>new Promise((A)=>setTimeout(A,N)),GT=(N,{baseDelay:A,backoffMultiplier:T,maxDelay:H})=>Math.min(A*T**N,H);function MT(N,A){if(N instanceof Error&&N.name==="AbortError")return!0;if(N instanceof TypeError)return!0;if(A===429)return!0;if(A&&A>=500&&A<600)return!0;return!1}var _T=async(N,A)=>{let T=await fetch(N,A),H;try{H=await T.json()}catch{if(!T.ok)throw new g({errorKey:"helpers_invalid_response",info:{status:T.status,statusText:T.statusText}},{status:T.status,statusText:T.statusText});return{}}if(!T.ok){let F={data:H?.data,error:H?.error,message:H?.message,status:T.status};throw new g({errorKey:H?.error||"helpers_invalid_response",info:F},F)}let P=H?.routes?.length||H?.result||H?.data&&!H?.error;if(H?.error&&!P){let F={data:H.data,error:H.error,message:H.message,status:T.status};throw new g({errorKey:H.error,info:F},F)}if(H?.providerErrors?.length||H?.error&&P)console.warn("[SwapKit] Partial errors in response:",H.providerErrors||H.error);return H};function _N(N,A={}){return async function(H,P={}){let{searchParams:F,json:I,body:O,headers:$,dynamicHeader:S,retry:x,timeoutMs:D,abortController:v,onError:U,onSuccess:k,responseHandler:Q,...w}={...A,...P},HN=X.get("requestOptions"),d={...HN.retry,...x},E=!!I||H.endsWith(".json"),$N=DT(H,F),fN=S?await S():{},PN=gT(E,{...$,...fN}),c=E?JSON.stringify(I):O,bN;for(let GN=0;GN<=d.maxRetries;GN++){let CN=v||new AbortController,hN=setTimeout(()=>CN.abort(),D||HN.timeoutMs);try{let m=await _T($N,{...w,body:c,headers:PN,method:N,signal:CN.signal});return clearTimeout(hN),k?.(m)||Q?.(m)||m}catch(m){clearTimeout(hN),bN=m;let iA=m?.cause?.status;if(GN>=d.maxRetries||!MT(m,iA))return U?U(m):Promise.reject(m);await $T(GT(GN,d))}}return U?U(bN):Promise.reject(bN)}}function gT(N,A){return{...A,...N&&{"Content-Type":"application/json"}}}function DT(N,A){let T=new URL(N);if(A)T.search=new URLSearchParams(A).toString();return T.toString()}var M={extend:(N)=>({extend:(A)=>M.extend({...N,...A}),get:_N("GET",N),post:_N("POST",N)}),get:_N("GET"),post:_N("POST")};import{Chain as z,CosmosChains as YT,EVMChains as ST,StagenetChains as UT,UTXOChains as XT}from"@swapkit/types";import{match as AA}from"ts-pattern";import{Chain as JN}from"@swapkit/types";function rP(N){if(N<0)throw new g({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:N}});return 10+N}function iP(N){if(N<0)throw new g({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:N}});return Math.round((10+N*1.0512)*10000000000)/10000000000}function sP(N,A){try{return N()}catch(T){if(A)throw new g(A,T);return}}function eP(N){switch(N){case JN.THORChain:return`${N}.RUNE`;case JN.Cosmos:return`${N}.ATOM`;case JN.BinanceSmartChain:return`${N}`;default:return`${N}.${N}`}}var eN=new Set;function l({condition:N,id:A,warning:T}){if(N){if(eN.has(A))return;console.warn(T),eN.add(A)}}function tT(N){return AA(N).with(...ST,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...XT,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...YT,...UT,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(z.Polkadot,z.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(z.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(z.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(z.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(z.Aptos,z.Tron,z.Radix,z.Stellar,()=>"").with(z.Hype,()=>({type:"meta"})).with(z.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(z.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(z.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new g("helpers_chain_not_supported",{chain:N})})}function aN(N){return AA(N).with(z.Aptos,()=>"/-/healthy").with(z.Hype,()=>"/info").with(z.Radix,()=>"/status/network-configuration").with(z.Stellar,()=>"").with(z.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function NA(N,A){try{let T=A.startsWith("wss")?A.replace("wss","https"):A;if(N===z.Stellar)return(await fetch(`${T}${aN(N)}`,{cache:"no-store",method:"GET",signal:AbortSignal.timeout(3000)})).ok;return(await fetch(`${T}${aN(N)}`,{body:JSON.stringify(tT(N)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var ZN=new Map,ET=120000;function bT(N){let[A=""]=X.get("rpcUrls")[N];if(!A)throw l({condition:!0,id:"helpers_chain_no_public_or_set_rpc_url",warning:`No public or set RPC URL found for chain. Please ensure you configured rpcUrls for ${N}.`}),new g("helpers_chain_no_public_or_set_rpc_url",{chain:N});let T=ZN.get(N);if(T&&Date.now()-T.timestamp<ET)return T.url;return ZN.set(N,{timestamp:Date.now(),url:A}),A}async function r(N){let A=bT(N),[,...T]=X.get("rpcUrls")[N];if(await NA(N,A))return A;for(let P of T)if(await NA(N,P))return ZN.set(N,{timestamp:Date.now(),url:P}),P;throw new g("helpers_chain_rpc_connection_failed",{chain:N,fallbackUrls:T,primaryRpcUrl:A})}function LL(N){l({condition:!0,id:"initializeRPCUrlsWithFallback",warning:"initializeRPCUrlsWithFallback is deprecated. Use static { rpcUrls, fallbackRpcUrls } SwapKit init config or dynamic SKConfig.setRpcUrl/setFallbackRpcUrl to configure RPC endpoints."})}var BL=[`${n.Maya}.MAYA`,`${n.Maya}.CACAO`,`${n.Ethereum}.THOR`,`${n.Ethereum}.vTHOR`,`${n.Kujira}.USK`,`${n.Ethereum}.FLIP`,`${n.Radix}.XRD`],PA=[n.Arbitrum,n.Aurora,n.Base,n.Ethereum,n.Optimism];async function wT(N){let{baseDecimal:A}=o(n.Radix);try{let T=await r(n.Radix),{manager:H}=await M.post(`${T}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:N}),headers:{Accept:"*/*","Content-Type":"application/json"}});return H?.divisibility?.value?.divisibility}catch(T){let H=T instanceof Error?T.message:String(T);return console.warn(`Failed to fetch Radix asset decimals for ${N}: ${H}`),A}}async function zT(N){try{let A=await r(n.Radix);return(await M.post(`${A}/state/entity/details`,{body:JSON.stringify({addresses:[N],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((P)=>P.key==="symbol")?.value.typed.value||void 0}catch(A){let T=A instanceof Error?A.message:String(A);return console.warn(`Failed to fetch Radix asset symbol for ${N}: ${T}`),""}}async function LA({chain:N,address:A,methodHex:T,id:H}){let P=await r(N);return M.post(P,{body:JSON.stringify({id:H,jsonrpc:"2.0",method:"eth_call",params:[{data:T,to:A.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}async function JT(N){if(!N||N==="0x")return"UNKNOWN";try{let{AbiCoder:A}=await import("ethers");return A.defaultAbiCoder().decode(["string"],N)[0].trim()}catch(A){return console.warn(`Failed to decode ABI string from ${N}: ${A}`),"UNKNOWN"}}function ZT(N,A){if(!N||N==="0x")return A;try{return Number(N)}catch(T){return console.warn(`Failed to decode ABI uint8 from ${N}: ${T}`),A}}async function WT({chain:N,address:A}){let{baseDecimal:T}=o(N),H=A.toLowerCase();if(A===""||!H.startsWith("0x"))return T;let P=await LA({address:A,chain:N,id:2,methodHex:"0x313ce567"}).catch((I)=>{return console.warn(`Could not fetch decimals for ${A} on ${N}: ${I.message}`),{result:""}});return ZT(P.result,T)}async function jT({chain:N,address:A}){let T=A.toLowerCase();if(T===""||!T.startsWith("0x"))return;let H=await LA({address:A,chain:N,id:1,methodHex:"0x95d89b41"}).catch((F)=>{return console.warn(`Could not fetch symbol for ${A} on ${N}: ${F.message}`),{result:""}});return await JT(H.result)}async function TA({rpcUrl:N,contractAddress:A,functionSelector:T}){return(await M.post(`${N}/wallet/triggerconstantcontract`,{body:JSON.stringify({contract_address:A,function_selector:T,owner_address:A,parameter:"",visible:!0}),headers:{accept:"application/json","content-type":"application/json"}}).catch(()=>{return}))?.constant_result?.[0]}function HA(N){let A=N.match(/.{2}/g)?.map((T)=>Number.parseInt(T,16))??[];return new TextDecoder().decode(new Uint8Array(A))}function VT(N){return FN(N).with(void 0,()=>{return}).when((A)=>A.length>=128,(A)=>{let T=Number.parseInt(A.slice(64,128),16);return HA(A.slice(128,128+T*2))}).when((A)=>A.length===64,(A)=>{let T=A.replace(/0+$/,"");if(T.length>0&&T.length%2===0)return HA(T);return}).otherwise(()=>{return})}function RA({chain:N,address:A}){let{baseDecimal:T}=o(N),H={decimals:T,ticker:void 0};return FN(N).with(...xT,async()=>{try{let{isAddress:P,getAddress:F}=await import("ethers");if(!P(F(A.replace(/^0X/,"0x"))))return H;let[I,O]=await Promise.all([jT({address:A,chain:N}),WT({address:A,chain:N})]);return{decimals:O,ticker:I}}catch(P){return console.warn(`Failed to fetch token info for ${A} on ${N}: ${P?.code} ${P?.message}`),H}}).with(n.Solana,async()=>{if(!A)return H;try{let P=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${A}`);if(P.ok){let F=await P.json(),I=Array.isArray(F)?F[0]:F;if(I)return{decimals:I.decimals??T,ticker:I.symbol||void 0}}}catch(P){console.warn(`Failed to fetch Solana token info for ${A}: ${P?.code} ${P?.message}`)}return H}).with(n.Tron,async()=>{if(!A)return H;try{let P=await r(n.Tron),[F,I]=await Promise.all([TA({contractAddress:A,functionSelector:"symbol()",rpcUrl:P}),TA({contractAddress:A,functionSelector:"decimals()",rpcUrl:P})]),O=VT(F);return{decimals:F!==void 0&&I?Number(BigInt(`0x${I}`)):T,ticker:O}}catch(P){let F=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Tron token info for ${A}: ${F}`),H}}).with(n.Near,async()=>{if(!A)return H;try{let{JsonRpcProvider:P}=await import("@near-js/providers"),F=await r(n.Near),O=await new P({url:F}).query({account_id:A,args_base64:Buffer.from("{}").toString("base64"),finality:"final",method_name:"ft_metadata",request_type:"call_function"}),$=JSON.parse(Buffer.from(O.result).toString());return{decimals:$?.decimals||T,ticker:$?.symbol}}catch(P){let F=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Near token info for ${A}: ${F}`),H}}).with(n.Radix,async()=>{if(!A)return H;try{let[P,F]=await Promise.all([zT(A),wT(A)]);return{decimals:F,ticker:P}}catch(P){let F=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Radix token info for ${A}: ${F}`),H}}).otherwise(async()=>H)}function FA({chain:N,symbol:A}){return FN(N).with(...PA,()=>A==="ETH").with(n.Avalanche,()=>A==="AVAX").with(n.Berachain,()=>A==="BERA").with(n.Hyperevm,()=>A==="HYPE").with(n.Hype,()=>A==="HYPE").with(n.Spark,()=>A==="BTC").with(n.BinanceSmartChain,()=>A==="BNB").with(n.Gnosis,()=>A==="xDAI"||A==="XDAI").with(n.Monad,()=>A==="MON").with(n.XLayer,()=>A==="OKB").with(n.Maya,()=>A==="CACAO").with(n.Cosmos,()=>A==="ATOM").with(n.THORChain,()=>A==="RUNE").with(n.Tron,()=>A==="TRX").with(n.Ripple,()=>A==="XRP").with(n.Radix,()=>`${N}.${A}`===gN(N).identifier).otherwise(()=>A===N)}var gN=(N)=>{let{baseDecimal:A}=o(N);return FN(N.toUpperCase()).with(...PA,(H)=>({decimal:A,identifier:`${H}.ETH`})).with(n.THORChain,(H)=>({decimal:A,identifier:`${H}.RUNE`})).with(n.Cosmos,(H)=>({decimal:A,identifier:`${H}.ATOM`})).with(n.Maya,(H)=>({decimal:10,identifier:`${H}.CACAO`})).with(n.BinanceSmartChain,(H)=>({decimal:A,identifier:`${H}.BNB`})).with(n.Monad,(H)=>({decimal:A,identifier:`${H}.MON`})).with(n.Avalanche,(H)=>({decimal:A,identifier:`${H}.AVAX`})).with(n.Gnosis,(H)=>({decimal:A,identifier:`${H}.xDAI`})).with(n.XLayer,(H)=>({decimal:A,identifier:`${H}.OKB`})).with(n.Berachain,(H)=>({decimal:A,identifier:`${H}.BERA`})).with(n.Hyperevm,(H)=>({decimal:A,identifier:`${H}.HYPE`})).with(n.Hype,(H)=>({decimal:A,identifier:`${H}.HYPE`})).with(n.Spark,(H)=>({decimal:A,identifier:`${H}.BTC`})).with(n.Tron,(H)=>({decimal:A,identifier:`${H}.TRX`})).with(n.Solana,n.Chainflip,n.Kujira,n.Ripple,n.Polkadot,n.Near,...QT,(H)=>({decimal:A,identifier:`${H}.${H}`})).with(n.Radix,"XRD.XRD",()=>({decimal:A,identifier:"XRD.XRD"})).with(n.Polygon,"POL.POL",()=>({decimal:A,identifier:"POL.POL"})).with("KUJI.USK",(H)=>({decimal:6,identifier:H})).with("ETH.FLIP",()=>({decimal:o(n.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:o(n.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:o(n.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(H)=>({decimal:10,identifier:H})).with("MAYA.MAYA",(H)=>({decimal:4,identifier:H})).otherwise(()=>({decimal:A,identifier:N}))};function WN({chain:N,symbol:A}){if(A.includes("/"))return"Synth";if(A.includes("~"))return"Trade";return FN(N).with(n.Radix,()=>A===n.Radix||`${N}.${A}`===gN(N).identifier).with(n.Arbitrum,n.Optimism,n.Base,n.Aurora,()=>A===n.Ethereum).with(n.Cosmos,()=>A==="ATOM").with(n.BinanceSmartChain,()=>A==="BNB").with(n.Maya,()=>A==="CACAO").with(n.Monad,()=>A==="MON").with(n.THORChain,()=>A==="RUNE").with(n.Tron,()=>A==="TRX").with(n.Hyperevm,()=>A==="HYPE").with(n.Hype,()=>A==="HYPE").with(n.Spark,()=>A==="BTC").with(n.XLayer,()=>A==="OKB").otherwise(()=>A===N)?"Native":N}var f=(N)=>{let[A,...T]=N.split("."),H=N.includes("/"),P=T.join("."),F=P?.split("-"),I=F?.length?F.length===1?F[0]:F.slice(0,-1).join("-"):void 0;return{chain:A,symbol:P,synth:H,ticker:I}};function uN(N,A){let H=A===n.Near?N.indexOf("-"):N.lastIndexOf("-");if(H===-1)return{address:void 0,ticker:N};return{address:N.slice(H+1),ticker:N.slice(0,H)}}function OL(N){return`https://storage.googleapis.com/token-list-swapkit-dev/images/${N.toLowerCase()}.png`}async function $L(N){let{loadTokenLists:A}=await import("./tokens.js"),T=await A(),H=Object.values(T).flatMap((F)=>F.tokens);if("identifier"in N)return H.find((F)=>F.identifier===N.identifier)?.identifier;let P=N.contract.toLowerCase();for(let F of H){let{chain:I,symbol:O}=f(F.identifier);if(I!==N.chain)continue;let{address:$}=uN(O,I);if($?.toLowerCase()===P)return F.identifier}return}var uA=["TERRA",...X.get("chains")];function IA(N=""){let A=N.toUpperCase(),[T]=A.split(".");if(uA.includes(T))return!0;let[H]=A.split("/");if(uA.includes(H))return!0;throw new g({errorKey:"helpers_invalid_identifier",info:{identifier:N,message:`Invalid identifier: ${N}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}function gL(N){if(N.length>30)return!1;let A=/^[a-zA-Z0-9+_-]+$/g;return!!N.match(A)}import{match as DN}from"ts-pattern";var i=8,vT=10;function h({value:N,bigIntDecimal:A=i,decimal:T=i}){if(T===0)return N.toString();let H=N<0n,P=N.toString().substring(H?1:0),F=T-(P.length-1);if(F>0)P="0".repeat(F)+P;let I=P.length-T,O=P.slice(-T);if(Number.parseInt(O[A]||"0",10)>=5){let S=Number.parseInt(O[A-1]||"0",10);O=`${O.substring(0,A-1)}${S+1}`}else O=O.substring(0,A);return`${H?"-":""}${P.slice(0,I)}.${O}`.replace(/\.?0*$/,"")}class y{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(N,A){return new y({decimal:A,value:h({bigIntDecimal:A,decimal:A,value:N})})}static shiftDecimals({value:N,from:A,to:T}){return y.fromBigInt(N.getBaseValue("bigint")*C(T)/C(A),T)}constructor(N){let A=jN(N),T=typeof N==="object";this.decimal=T?N.decimal:void 0,this.decimalMultiplier=T&&"decimalMultiplier"in N?N.decimalMultiplier:C(Math.max(nA(YN(A)),this.decimal||0)),this.#P(A)}set(N){return new this.constructor({decimal:this.decimal,identifier:this.toString?.({includeSynthProtocol:!0}),value:N})}add(...N){return this.#A("add",...N)}sub(...N){return this.#A("sub",...N)}mul(...N){return this.#A("mul",...N)}div(...N){return this.#A("div",...N)}gt(N){return this.#N("gt",N)}gte(N){return this.#N("gte",N)}lt(N){return this.#N("lt",N)}lte(N){return this.#N("lte",N)}eqValue(N){return this.#N("eqValue",N)}getValue(N,A){let T=IN(this.decimalMultiplier),H=A!==void 0?A:this.decimal,P=H!==void 0?H:T;if(H!==void 0&&H<T){if(this.formatBigIntToSafeValue(this.bigIntValue,H)==="0"&&this.bigIntValue!==0n)P=T}let F=this.formatBigIntToSafeValue(this.bigIntValue,P);return DN(N).with("number",()=>Number(F)).with("string",()=>F).with("bigint",()=>{return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}).otherwise(()=>F)}getBaseValue(N,A){let T=this.decimalMultiplier/C(A||this.decimal||i),H=kT(this.bigIntValue,T);return DN(N).with("number",()=>Number(H)).with("string",()=>H.toString()).otherwise(()=>H)}getBigIntValue(N,A){if(!A&&typeof N==="object")return N.bigIntValue;let T=jN(N),H=YN(T);if(H==="0"||H==="undefined")return 0n;return this.#H(H,A)}toSignificant(N=6){let A=this.getValue("string"),[T="",H=""]=A.split("."),P=Number.parseInt(T,10)>0;if((P?T.length+H.length:H.length)<=N)return A;if(T.length>=N)return T.slice(0,N).padEnd(T.length,"0");if(P)return`${T}.${H.slice(0,N-T.length)}`;let I=Number.parseInt(H,10).toString(),O=I.slice(0,N),$=H.length-I.length;return`0.${O.padStart($+O.length,"0")}`}toFixed(N=6){let A=this.getValue("string"),T=A.startsWith("-"),[H="0",P=""]=(T?A.slice(1):A).split("."),F=H==="0"&&Number.parseInt(P.slice(0,N),10)===0,I=T&&!F?"-":"";if(N===0){if(H==="0"&&!P)return"0";return P&&Number.parseInt(P[0]||"0",10)>=5?`${I}${BigInt(H)+1n}.0`:`${I}${H}.0`}if(!P)return`${I}${H}.${"0".repeat(N)}`;let O=P[N];if(!(O&&Number.parseInt(O,10)>=5))return`${I}${H}.${P.slice(0,N).padEnd(N,"0")}`;let S=BigInt(P.slice(0,N).padEnd(N,"0"))+1n,x=10n**BigInt(N);if(S>=x)return`${I}${BigInt(H)+1n}.${"0".repeat(N)}`;return`${I}${H}.${S.toString().padStart(N,"0")}`}toAbbreviation(N=2){let A=this.getValue("string"),T=Number(A),H=["","K","M","B","T","Q","Qi","S"],P=Math.floor(Math.log10(Math.abs(T))/3);if(P===0||!H[P])return A;return`${(T/10**(P*3)).toFixed(N)}${H[P]}`}toCurrency(N="$",{currencyPosition:A="start",decimal:T=2,decimalSeparator:H=".",thousandSeparator:P=",",trimTrailingZeros:F=!0}={}){let I=this.toFixed(T),O=A==="end",[$="0",S=""]=I.split("."),x=$.replace(/\B(?=(\d{3})+(?!\d))/g,P),D=S&&Number.parseInt(S,10)>0,v=D?`${x}${H}${S}`:x,k=v.length<100&&F&&D?v.replace(/\.?0*$/,""):v;return O?`${k}${N}`:`${N}${k}`}formatBigIntToSafeValue(N,A){let T=A||this.decimal||i,H=Math.max(T,IN(this.decimalMultiplier));return h({bigIntDecimal:T,decimal:H,value:N})}#A(N,...A){let T=this.#T(this,...A),H=IN(this.decimalMultiplier),F=Math.max(T,H)+vT,I=C(F),O=A.reduce((S,x)=>{let D=this.getBigIntValue(x,F);return DN(N).with("add",()=>S+D).with("sub",()=>S-D).with("mul",()=>S*D/I).with("div",()=>{if(D===0n)throw RangeError("Division by zero");return S*I/D}).otherwise(()=>S)},this.bigIntValue*I/this.decimalMultiplier),$=h({bigIntDecimal:F,decimal:F,value:O});return new this.constructor({decimal:this.decimal,decimalMultiplier:C(F),identifier:this.toString(),value:$})}#N(N,...A){let T=this.#T(this,...A),H=this.getBigIntValue(A[0]||"0",T),P=this.getBigIntValue(this,T);return DN(N).with("gt",()=>P>H).with("gte",()=>P>=H).with("lt",()=>P<H).with("lte",()=>P<=H).with("eqValue",()=>P===H).otherwise(()=>!1)}#P(N){let A=YN(N)||"0";this.bigIntValue=this.#H(A)}#T(...N){let A=N.map((T)=>{return typeof T==="object"?T.decimal||IN(T.decimalMultiplier):nA(YN(T))}).filter(Boolean);return Math.max(...A,i)}#H(N,A){let T=A?C(A):this.decimalMultiplier,H=IN(T),[P="",F=""]=N.split(".");return BigInt(`${P}${F.padEnd(H,"0")}`)}}var qT=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function YN(N){let T=`${typeof N==="number"?qT.format(N):jN(N)}`.replaceAll(",",".").split(".");return T.length>1?`${T.slice(0,-1).join("")}.${T.at(-1)}`:T[0]||"0"}function nA(N){let A=N.split(".")[1]?.length||0;return Math.max(A,i)}function jN(N){return typeof N==="object"?"getValue"in N?N.getValue("string"):N.value:N}function kT(N,A){if(A===0n)throw Error("Cannot divide by zero");let T=A/2n;return N>=0n&&A>=0n||N<0n&&A<0n?(N+T)/A:(N-T)/A}function C(N){return 10n**BigInt(N)}function IN(N){return Math.log10(Number.parseFloat(N.toString()))}var p=[b.Hype,b.Near,b.Ripple,b.Solana,b.Sui,b.Ton,b.Tron],qN=[b.THORChain,b.Maya],s=new Map,SN=new Map,e=new Map,yT=3600000;function pT(N){let A=e.get(N);if(A?.timestamp&&Date.now()-A.timestamp>yT){e.delete(N);return}return A}function oT(N,A){if(e.size>1000){let T=e.keys().next().value;if(T)e.delete(T)}e.set(N,{...A,timestamp:Date.now()})}class W extends y{address;chain;isGasAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:N,decimal:A,tax:T,chain:H,symbol:P,identifier:F}){super(typeof N==="object"?N:{decimal:A,value:N});let I=OA(F||`${H}.${P}`);this.type=WN(I),this.tax=T,this.chain=I.chain,this.ticker=I.ticker,this.symbol=I.symbol,this.address=I.address,this.isSynthetic=I.isSynthetic,this.isTradeAsset=I.isTradeAsset,this.isGasAsset=I.isGasAsset,this.chainId=nN(I.chain).chainId}toString({includeSynthProtocol:N}={}){return(this.isSynthetic||this.isTradeAsset)&&!N?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){if(this.isSynthetic)return`${this.chain}.${this.symbol.replace(/\//g,".")}`;if(this.isTradeAsset)return`${this.chain}.${this.symbol.replace(/~/g,"..")}`;let N=this.symbol.replace(/\./g,"__");return`${this.chain}.${N}`}getIconUrl(){return s.get(this.toString())?.logoURI}eqAsset({chain:N,symbol:A}){return this.chain===N&&this.symbol===A}eq(N){return this.eqAsset(N)&&this.eqValue(N)}static fromUrl(N,A=0){let T=N.indexOf(".");if(T===-1)throw new g({errorKey:"helpers_invalid_asset_url",info:{urlAsset:N}});let H=N.slice(0,T),P=N.slice(T+1),F=vN({chain:H,rest:P}).when(({rest:I})=>I.includes(".."),({chain:I,rest:O})=>`${I}.${O.replace(/\.\./g,"~")}`).when(({chain:I,rest:O})=>qN.includes(I)&&O.includes("."),({chain:I,rest:O})=>`${I}.${O.replace(/\./g,"/")}`).otherwise(({chain:I,rest:O})=>`${I}.${O.replace(/__/g,".")}`);return W.from({asset:F,value:A})}static from({value:N=0,fromBaseDecimal:A,asyncTokenLookup:T,...H}){let P=N instanceof y?N.getValue("string"):N,F="address"in H&&"chain"in H,I=dT(H);if(I===null&&T&&F){let{chain:PN,address:c}=H;return CT({address:c,chain:PN,fromBaseDecimal:A,parsedValue:P})}let O=F&&!I?`${H.chain}.UNKNOWN-${H.address}`:I,{identifier:$,decimal:S}=gN(O),{chain:x,isSynthetic:D,isTradeAsset:v,address:U}=OA($),{baseDecimal:k}=nN(x),Q=s.get(p.includes(x)?$:$.toUpperCase());if(!Q&&T&&!D&&!v)return(async()=>{let{ticker:PN}=f($),c=await $A({address:U,chain:x,ticker:PN});return VN({decimal:c.decimals,identifier:c.identifier,value:A?a(BigInt(P),A):P})})();let w=Q?.decimal||S;l({condition:!w&&!T,id:`assetValue_static_decimal_not_found_${x}`,warning:`Couldn't find static decimal for one or more tokens on ${x} (Using default ${k} decimal as fallback).
2
- This can result in incorrect calculations and mess with amount sent on transactions.
3
- You can load static assets by installing @swapkit/tokens package and calling AssetValue.loadStaticAssets()
4
- or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`});let{decimal:HN,identifier:d,tax:E}=Q||{decimal:w||k,identifier:$},$N=A?a(BigInt(P),A):a(P,HN);return D||v?fT(d,$N):VN({decimal:HN,identifier:d,tax:E,value:$N})}static async loadStaticAssets(N){let{loadTokenLists:A}=await import("@swapkit/tokens"),T=await A(N);for(let{tokens:H}of Object.values(T))for(let P of H){let{identifier:F}=P,{chain:I,symbol:O}=f(F),{address:$}=uN(O,I),{baseDecimal:S}=nN(I),x=p.includes(I)?F:F.toUpperCase(),D="decimals"in P&&P.decimals!==void 0?P.decimals:S,v="logoURI"in P&&P.logoURI?P.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${F.toLowerCase()}.png`,U={decimal:D,identifier:F,logoURI:v,tax:"tax"in P?P.tax:void 0};if(s.set(x,U),$){let k=p.includes(I)?`${I}:${$}`:`${I}:${$.toUpperCase()}`;SN.set(k,F)}}return!0}static setStaticAssets(N){s.clear(),SN.clear();for(let[A,T]of N.entries()){let{identifier:H}=T,{chain:P,symbol:F}=f(H),{address:I}=uN(F,P),{baseDecimal:O}=nN(P),$=T.chain??P,S=T.address??I,x=p.includes($)?H:H.toUpperCase(),D=T.decimals??T.decimal??O,v=T.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${H.toLowerCase()}.png`,U={decimal:D,identifier:x,logoURI:v,tax:T.tax};if(s.set(x,U),S){let k=p.includes($)?`${$}:${S}`:`${$}:${S.toUpperCase()}`;SN.set(k,H)}}return!0}static get staticAssets(){return s}}function zL(N){let A=W.from({chain:N});return vN(N).with(b.Bitcoin,b.Litecoin,b.BitcoinCash,b.Dash,()=>A.set(0.00010001)).with(b.Dogecoin,()=>A.set(1.00000001)).with(b.Avalanche,b.Ethereum,b.Arbitrum,b.BinanceSmartChain,()=>A.set(0.00000001)).with(b.THORChain,b.Maya,()=>A.set(0)).with(b.Cosmos,b.Kujira,()=>A.set(0.000001)).otherwise(()=>A.set(0.00000001))}async function $A({chain:N,address:A,ticker:T}){let P=p.includes(N)?`${N}:${A||T}`:`${N}:${A||T}`.toUpperCase(),F=pT(P);if(F)return F;if(!A){let{baseDecimal:$}=nN(N);return{decimals:$,identifier:`${N}.${T||"UNKNOWN"}`}}let I=await RA({address:A,chain:N}),O=`${N}.${I.ticker||T||"UNKNOWN"}-${A}`;return l({condition:!!(!I.ticker&&T),id:`async_token_lookup_failed_${N}_${A}`,warning:`Could not fetch token metadata for ${N}:${A} from chain. Using user-provided ticker (${T}) with baseDecimal (${I.decimals}).`}),I.ticker&&oT(P,{decimals:I.decimals,identifier:O}),{decimals:I.decimals,identifier:O}}function VN({identifier:N,decimal:A,value:T,tax:H}){return IA(N),new W({decimal:A,identifier:N,tax:H,value:a(T,A)})}function fT(N,A=0){let T=N.includes(".")?N.split(".")?.[0]?.toUpperCase():void 0,H=T?qN.includes(T):!1,P=N.slice(0,14).includes("~")?"~":"/",[F,I]=H?N.split(".").slice(1).join().split(P):N.split(P);if(!(F&&I))throw new g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});return new W({decimal:8,identifier:`${T||b.THORChain}.${F}${P}${I}`,value:a(A,8)})}async function CT({address:N,chain:A,fromBaseDecimal:T,parsedValue:H}){let{decimals:P,identifier:F}=await $A({address:N,chain:A}),I=T?a(BigInt(H),T):H;return VN({decimal:P,identifier:F,value:I})}function a(N,A){return typeof N==="bigint"?h({bigIntDecimal:A,decimal:A,value:N}):N}function hT(N){let A=vN(N).when((T)=>("chain"in T)&&T.chain!==void 0,({chain:T})=>T).otherwise((T)=>{let H=f(T.asset);return H.synth?b.THORChain:H.chain});if(!KT.includes(A.toUpperCase())){let T="asset"in N?N.asset:A;throw new g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:T,message:`Unsupported chain "${A}" - use the AssetValue constructor directly`}})}}function dT(N){if(hT(N),"chain"in N){let{chain:P,address:F}=N;if(F){let I=p.includes(P)?`${P}:${F}`:`${P}:${F.toUpperCase()}`,O=SN.get(I);if(O)return O;return null}return P}let{chain:A,symbol:T}=f(N.asset);return WN({chain:A,symbol:T})==="Native"?A:N.asset}function cT(N,A,T){let H=N.split("."),P=H[0]?.toUpperCase(),F=qN.includes(P),I=T?"~":"/",[O,$=""]=F?H.slice(1).join(".").split(I):N.split(I);if(!(O&&$))throw new g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});let{ticker:S,address:x}=GA({chain:O,symbol:$}),D=`${O}${I}${$}`;return{address:x,chain:P,isGasAsset:!1,isSynthetic:A,isTradeAsset:T,symbol:D,ticker:S}}function lT(N){let A=N.indexOf("."),T=(A===-1?N:N.slice(0,A)).toUpperCase(),H=A===-1?N:N.slice(A+1),{address:P,ticker:F}=GA({chain:T,symbol:H}),I;try{I=P&&mT.includes(T)&&BA(P)?BA(P):P}catch{I=P}let O=I?`${F}-${I}`:H;return{address:I,chain:T,isGasAsset:FA({chain:T,symbol:H}),isSynthetic:!1,isTradeAsset:!1,symbol:O,ticker:F}}function OA(N){let A=N.slice(0,14),T=A.includes("/"),H=A.includes("~");if(T||H)return cT(N,T,H);return lT(N)}function GA({symbol:N,chain:A}){let{ticker:T,address:H}=uN(N,A);return{address:H&&!p.includes(A)?H.toLowerCase():H,ticker:T}}class UN extends y{eq(N){return this.eqValue(N)}static fromBigInt(N,A){return new UN({decimal:A,value:h({bigIntDecimal:A,decimal:A,value:N})})}}function MA(N=!0){return N?"https://midgard.thorchain.network":"https://midgard.mayachain.info"}function iT(N=!0){let A=MA(N);return N?`${A}/v2/thorname`:`${A}/v2/mayaname`}function sT(N){return function(T){let H=T?`?status=${T}`:"";return M.get(`${N}/v2/pools${H}`)}}function eT(N){return function(T){return M.get(`${N}/v2/pool/${T}`)}}function aT(N){return function(T,H){let P=H?`?period=${H}`:"";return M.get(`${N}/v2/pool/${T}/stats${P}`)}}function NH(N){return function(T,H){let P=new URLSearchParams;if(H?.interval)P.append("interval",H.interval);if(H?.count)P.append("count",H.count.toString());if(H?.from)P.append("from",H.from.toString());if(H?.to)P.append("to",H.to.toString());let F=P.toString()?`?${P.toString()}`:"";return M.get(`${N}/v2/history/depths/${T}${F}`)}}function AH(N){return function(){return M.get(`${N}/v2/network`)}}function TH(N){return function(){return M.get(`${N}/v2/health`)}}function HH(N){return function(){return M.get(`${N}/v2/nodes`)}}function PH(N){return function(T){return M.get(`${N}/v2/node/${T}`)}}function LH(N){return function(){return M.get(`${N}/v2/mimir/votes`)}}function RH(N){return function(){return M.get(`${N}/v2/mimir`)}}function FH(N){return function(){return M.get(`${N}/v2/constants`)}}function uH(N){return function(){return M.get(`${N}/v2/stats`)}}function IH(N){return function(T){let H=new URLSearchParams;if(T?.interval)H.append("interval",T.interval);if(T?.count)H.append("count",T.count.toString());if(T?.from)H.append("from",T.from.toString());if(T?.to)H.append("to",T.to.toString());let P=H.toString()?`?${H.toString()}`:"";return M.get(`${N}/v2/history/earnings${P}`)}}function nH(N){return function(T,H){let P=new URLSearchParams;if(H?.interval)P.append("interval",H.interval);if(H?.count)P.append("count",H.count.toString());if(H?.from)P.append("from",H.from.toString());if(H?.to)P.append("to",H.to.toString());let F=P.toString()?`?${P.toString()}`:"",I=T?`/swaps/${T}`:"/swaps";return M.get(`${N}/v2/history${I}${F}`)}}function BH(N){return function(T){let H=new URLSearchParams;if(T?.interval)H.append("interval",T.interval);if(T?.count)H.append("count",T.count.toString());if(T?.from)H.append("from",T.from.toString());if(T?.to)H.append("to",T.to.toString());let P=H.toString()?`?${H.toString()}`:"";return M.get(`${N}/v2/history/tvl${P}`)}}function OH(N){if(!N)return"";let A=new URLSearchParams,T=(H,P)=>{if(P!==void 0)A.append(H,typeof P==="number"?P.toString():P)};return T("address",N.address),T("txid",N.txid),T("asset",N.asset),T("type",N.type),T("affiliate",N.affiliate),T("limit",N.limit),T("offset",N.offset),A.toString()?`?${A.toString()}`:""}function $H(N){return function(T){let H=OH(T);return M.get(`${N}/v2/actions${H}`)}}function GH(N){return function(T){return M.get(`${N}/v2/member/${T}`)}}function MH(N){return function(T){let H=T?`/${T}`:"";return M.get(`${N}/v2/members${H}`)}}function _H(N){return function(T,H){let P=H?`&asset=${H}`:"";return M.get(`${N}/v2/saver/${T}${P?`?${P.substring(1)}`:""}`)}}function gH(N){return function(T){return M.get(`${N}/v2/savers/${T}`)}}function DH(N){return function(T,H){let P=new URLSearchParams;if(H?.interval)P.append("interval",H.interval);if(H?.count)P.append("count",H.count.toString());if(H?.from)P.append("from",H.from.toString());if(H?.to)P.append("to",H.to.toString());let F=P.toString()?`?${P.toString()}`:"",I=T?`/savers/${T}`:"/savers";return M.get(`${N}/v2/history${I}${F}`)}}function YH(N){return function(T){return M.get(`${N}/v2/balance/${T}`)}}function SH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return;throw P};return await M.get(`${N}/lookup/${T}`,{onError:H,retry:{maxRetries:1}})}}function UH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return[];throw P};return await M.get(`${N}/rlookup/${T}`,{onError:H,retry:{maxRetries:1}})}}function XH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return[];throw P};return await M.get(`${N}/owner/${T}`,{onError:H,retry:{maxRetries:1}})}}function NN({asset:N,value:A}){return W.from({asset:N,fromBaseDecimal:rT(XN.THORChain).baseDecimal,value:A})}function tH({liquidityPositionGetter:N,isThorchain:A}){return async function(H){let P=await N(H),F=A?"rune":"cacao";return P.pools.map((I)=>({[`${F}Pending`]:NN({asset:"THOR.RUNE",value:I.runePending}),[`${F}RegisteredAddress`]:I.runeAddress,[`${F}Withdrawn`]:NN({asset:"THOR.RUNE",value:I.runeWithdrawn}),[F]:NN({asset:"THOR.RUNE",value:I.runeAdded}),asset:NN({asset:I.pool,value:I.assetAdded}),assetPending:NN({asset:I.pool,value:I.assetPending}),assetRegisteredAddress:I.assetAddress,assetWithdrawn:NN({asset:I.pool,value:I.assetWithdrawn}),dateFirstAdded:I.dateFirstAdded,dateLastAdded:I.dateLastAdded,poolShare:new UN(I.liquidityUnits).div(I.pool)}))}}function _A(N){let A=N===XN.THORChain,T=MA(A),H=iT(A),P=GH(T);return{getActions:$H(T),getBalance:YH(T),getConstants:FH(T),getEarningsHistory:IH(T),getHealth:TH(T),getLiquidityPosition:tH({isThorchain:A,liquidityPositionGetter:P}),getLiquidityPositionRaw:P,getMembers:MH(T),getMimir:RH(T),getMimirVotes:LH(T),getNameDetails:SH(H),getNamesByAddress:UH(H),getNamesByOwner:XH(H),getNetworkInfo:AH(T),getNode:PH(T),getNodes:HH(T),getPool:eT(T),getPoolDepthHistory:NH(T),getPoolStats:aT(T),getPools:sT(T),getSaverDetails:_H(T),getSavers:gH(T),getSaversHistory:DH(T),getStats:uH(T),getSwapHistory:nH(T),getTVLHistory:BH(T)}}var gA=_A(XN.THORChain),DA=_A(XN.Maya);var pN={};dN(pN,{getTrackerDetails:()=>iH,getTokenListProviders:()=>AP,getTokenList:()=>TP,getTokenApproval:()=>NP,getSwapTo:()=>BP,getSwapQuote:()=>sH,getRouteWithTx:()=>eH,getPrice:()=>HP,getNearDepositChannel:()=>RP,getGasRate:()=>PP,getChainflipDepositChannel:()=>LP,getChainBalance:()=>aH,SKRequestClient:()=>V});import{EVMChains as yN}from"@swapkit/types";import{match as rH,P as ON}from"ts-pattern";async function YA(N,A,T,H){let P=`${A}:${T}:${H}`,F=new TextEncoder,I=await crypto.subtle.importKey("raw",F.encode(N),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),O=await crypto.subtle.sign("HMAC",I,F.encode(P));return Array.from(new Uint8Array(O)).map(($)=>$.toString(16).padStart(2,"0")).join("")}import{Chain as tN,ChainId as BN}from"@swapkit/types";import{array as t,boolean as K,coerce as tA,number as _,object as G,optional as B,string as R,union as kN,unknown as EA,z as L}from"zod";var bA;((H)=>{H.CHEAPEST="CHEAPEST";H.FASTEST="FASTEST";H.RECOMMENDED="RECOMMENDED"})(bA||={});var EN;((F)=>{F.PSBT="PSBT";F.EVM="EVM";F.COSMOS="COSMOS";F.RADIX="RADIX";F.NEAR="NEAR"})(EN||={});var xA;((w)=>{w.approve="approve";w.claim="claim";w.deposit="deposit";w.donate="donate";w.lending="lending";w.lp_action="lp_action";w.native_contract_call="native_contract_call";w.native_send="native_send";w.stake="stake";w.streaming_swap="streaming_swap";w.swap="swap";w.thorname_action="thorname_action";w.token_contract_call="token_contract_call";w.token_transfer="token_transfer";w.unknown="unknown";w.unstake="unstake"})(xA||={});var QA;((U)=>{U.swap="swap";U.aggregation="aggregation";U.addLiquidity="addLiquidity";U.withdrawLiquidity="withdrawLiquidity";U.addSavers="addSavers";U.withdrawSavers="withdrawSavers";U.borrow="borrow";U.repay="repay";U.name="name";U.donate="donate";U.claim="claim";U.stake="stake";U.unstake="unstake"})(QA||={});var wA;((O)=>{O.unknown="unknown";O.not_started="not_started";O.pending="pending";O.swapping="swapping";O.completed="completed";O.refunded="refunded";O.failed="failed"})(wA||={});var zA;((Q)=>{Q.not_started="not_started";Q.starting="starting";Q.broadcasted="broadcasted";Q.mempool="mempool";Q.inbound="inbound";Q.outbound="outbound";Q.swapping="swapping";Q.completed="completed";Q.refunded="refunded";Q.partially_refunded="partially_refunded";Q.dropped="dropped";Q.reverted="reverted";Q.replaced="replaced";Q.retries_exceeded="retries_exceeded";Q.parsing_error="parsing_error"})(zA||={});var oL=G({address:B(R()),chain:L.enum(tN).optional(),chainId:L.enum(BN),coingeckoId:B(R()),decimals:tA.number(),extensions:B(L.looseObject({})),identifier:R(),logoURI:B(R()),name:B(R()),shortCode:B(R()),symbol:B(R()),ticker:R()}),fL=L.object({block:L.optional(L.number().describe("Block number. Required for Polkadot chain. e.g. `123456`")),chainId:L.optional(L.string().describe("ChainId for the hash. e.g. `thorchain-1`")),depositChannelId:L.optional(L.string().describe("Deposit channel ID, required for Chainflip if tx was broadcasted without wallet connection")),hash:L.optional(L.string().describe("Hash for the first transaction broadcasted by the end user. e.g. `88D1819378ECD09E5284C54937CDC1E99B52F253C007617A02DD1200710CE677`"))}).refine((N)=>N.hash&&N.chainId||N.depositChannelId,{message:"Either `hash` and `chainId` or `depositChannelId` must be provided"}),CL=L.object({forceUpdate:L.string().toLowerCase().transform((N)=>N==="true").pipe(L.boolean()).optional()}),hL=G({error:R(),message:R()}),AN=G({address:B(R()),chain:L.enum(tN),decimal:B(_()),isGasAsset:K(),isSynthetic:K(),symbol:R(),tax:B(G({buy:_(),sell:_()})),ticker:R()}),JA=G({id:R(),market_cap:_(),name:R(),price_change_24h_usd:_(),price_change_percentage_24h_usd:_(),sparkline_in_7d:t(_()),timestamp:R(),total_volume:_()}).partial(),dL=G({cg:B(JA),identifier:R(),price_usd:_(),provider:R(),timestamp:_()}),ZA=t(G({cg:B(JA),identifier:R(),price_usd:_(),provider:R(),timestamp:_()}).partial()),cL=G({affiliate:B(R().describe("Affiliate thorname")),affiliateFee:B(_().describe("Affiliate fee in basis points").refine((N)=>N===Math.floor(N)&&N>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:B(K().describe("Allow smart contract as recipient")),allowSmartContractSender:B(K().describe("Allow smart contract as sender")),buyAsset:R().describe("Asset to buy"),cfBoost:B(K().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:B(R().describe("Address to send asset to")),disableSecurityChecks:B(K().describe("Disable security checks")),includeTx:B(K().describe("Set to true to include an transaction object (EVM only)")),providers:B(t(R().describe("List of providers to use").refine((N)=>J[N]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:B(R().describe("Referrer address (referral program)")),sellAmount:R().describe("Amount of asset to sell").refine((N)=>+N>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:R().describe("Asset to sell"),slippage:B(_().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:B(R().describe("Address to send asset from"))}).refine((N)=>N.sellAsset!==N.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),lL=G({metadata:K(),tokens:t(G({identifier:R()}))}),WA=G({destinationAddress:R()}),EH=WA.extend({affiliateFees:t(G({brokerAddress:R(),feeBps:_()})).optional(),brokerCommissionBps:_().optional(),buyAsset:G({asset:R(),chain:R()}),channelMetadata:G({cfParameters:R().optional(),gasBudget:R().optional(),message:R().optional()}).optional(),dcaParameters:G({chunkInterval:_().optional(),numberOfChunks:_().optional()}).optional(),maxBoostFeeBps:_().optional(),refundParameters:G({minPrice:R().optional(),refundAddress:R().optional(),retryDuration:_().optional()}).optional(),sellAsset:G({asset:R(),chain:R()})}),jA=G({channelId:R(),depositAddress:R()}),SA=WA.extend({affiliateFees:G({feeBps:_(),nearId:R()}).optional(),buyAsset:R(),sellAmount:R(),sellAsset:R(),slippage:tA.number(),sourceAddress:R()}),UA=G({amountIn:R(),amountInFormatted:R(),amountInUsd:R(),amountOut:R(),amountOutFormatted:R(),amountOutUsd:R(),deadline:R().optional(),minAmountIn:R(),minAmountOut:R(),timeEstimate:_().optional(),timeWhenInactive:R().optional()}),rL=UA.extend({depositAddress:R(),quote:UA,signature:R(),timestamp:R(),tx:EA()}),VA=G({buyAsset:R(),buyAssetAmount:R(),buyAssetAmountMaxSlippage:R(),deadline:R().optional(),depositAddress:R(),depositAmount:R(),depositAsset:R(),tx:EA()}),bH=G({evmCalldata:L.optional(L.string()),intentHash:L.optional(L.string()),logs:L.optional(L.unknown()),manifest:L.optional(L.unknown()),memo:L.optional(L.string()),spender:L.optional(L.string()),thorname:L.optional(L.string())}),xH=G({currentStage:R(),inboundConfirmation:_(),inboundObservation:_(),outboundDelay:_(),outboundObservation:_(),streamingSwap:_()}),QH=G({count:B(_()),interval:B(_()),quantity:B(_()),subSwapsMap:B(t(_()))}),wH=L.object({currentLegIndex:L.optional(L.number()),estimatedTimeToComplete:L.number(),estimates:L.optional(xH),providerDetails:L.optional(L.object({streamingDetails:L.optional(QH)}))}),zH=G({affiliate:B(AN),liquidity:B(AN),network:B(AN),protocol:B(AN),tax:B(AN)}),JH=G({affiliate:R(),bps:R(),isReferrer:K()}),ZH=G({affiliate:B(R()),affiliateFees:B(t(JH)),broadcastedAt:B(_()),explorerUrl:B(R()),fees:B(zH),images:B(G({chain:B(R()),from:B(R()),provider:B(R()),to:B(R())})),provider:B(L.enum(J)),providerAction:L.optional(L.enum(QA)),quoteId:B(R()),wallet:B(R())}),TN=L.object({block:L.number(),chainId:L.enum(BN),finalAddress:L.optional(L.string()),finalAsset:L.optional(AN),finalisedAt:L.number(),fromAddress:L.string(),fromAmount:L.string(),fromAsset:L.string(),hash:L.string(),meta:L.optional(ZH),payload:L.optional(bH),status:L.enum(wA),toAddress:L.string(),toAmount:L.string(),toAsset:L.string(),trackingStatus:L.optional(L.enum(zA)),transient:L.optional(wH),type:L.enum(xA)}),vA=TN.extend({legs:L.array(TN)}),iL=TN.extend({legs:t(TN)}),sL=TN.extend({legs:t(TN)}),KN=t(G({amount:R(),asset:R(),chain:R(),protocol:L.enum(J),type:L.enum(QN)})),mN=L.object({inbound:L.optional(L.number().describe("Time to receive inbound asset in seconds")),outbound:L.optional(L.number().describe("Time to receive outbound asset in seconds")),swap:L.optional(L.number().describe("Time to swap assets in seconds")),total:L.number().describe("Total time in seconds")}),qA=G({data:R().describe("Data to send"),from:R().describe("Address of the sender"),to:R().describe("Address of the recipient"),value:R().describe("Value to send")}),kA=L.object({raw_data:L.object({contract:L.any(),data:L.string().optional(),expiration:L.number(),fee_limit:L.number().optional(),ref_block_bytes:L.string(),ref_block_hash:L.string(),timestamp:L.number()}).passthrough(),raw_data_hex:L.string(),txID:L.string(),visible:L.boolean()}),WH=t(kN([R(),_(),t(R()),G({from:R(),value:R()}).describe("Parameters to pass to the contract method")])),eL=G({approvalSpender:B(R().describe("Address of the spender to approve")),approvalToken:B(R().describe("Address of the token to approve spending of")),contractAddress:R().describe("Address of the contract to interact with"),contractMethod:R().describe("Name of the method to call"),contractParamNames:t(R().describe("Names of the parameters to pass to the contract method")),contractParams:WH}),jH=G({typeUrl:R("/types.MsgDeposit"),value:G({coins:t(G({amount:R(),asset:G({chain:R(),symbol:R(),synth:K(),ticker:R()})})),memo:R(),signer:R()})}),VH=G({typeUrl:R("/types.MsgSend"),value:G({amount:t(G({amount:R(),denom:R()})),fromAddress:R(),toAddress:R()})}),vH=G({typeUrl:R(),value:VH.shape.value.or(jH.shape.value)}),qH=G({amount:t(G({amount:R(),denom:R()})),gas:R()}),KA=G({accountNumber:_(),chainId:L.enum(BN),fee:qH,memo:R(),msgs:t(vH),sequence:_()}),kH=L.array(L.object({calldata:L.array(L.string()),contractAddress:L.string(),entrypoint:L.string()})),mA=L.array(L.object({address:L.string().describe("Destination address in friendly format"),amount:L.string().describe("Amount in nanotons"),payload:L.string().optional().describe("Base64 BOC of body cell"),stateInit:L.string().optional().describe("Base64 BOC of state init")})),KH=G({affiliate:R().describe("Affiliate address").optional(),affiliateFee:_().describe("Affiliate fee").optional(),buyAsset:R().describe("Asset to buy"),destinationAddress:R().describe("Destination address"),estimatedTime:mN.optional(),provider:L.enum(J),sellAsset:R().describe("Asset to sell"),slipPercentage:_().describe("Slippage as a percentage"),sourceAddress:R().describe("Source address")}),aL=KH.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),mH=G({asset:R().describe("Asset name"),image:R().describe("Asset image"),price:_().describe("Price in USD")}),yH=EH,yA=G({assets:B(t(mH)),maxStreamingQuantity:_().optional(),referrer:R().optional(),streamingInterval:_().optional(),tags:t(L.enum(bA))}),pA=yA.extend({affiliate:B(R()),affiliateFee:B(R()),approvalAddress:B(R().describe("Approval address for swap")),chainflip:yH.optional(),garden:SA.optional(),near:SA.optional(),priceImpact:B(_().describe("Price impact")),referrer:B(R()),txType:B(L.enum(EN))}),oA=t(G({code:L.enum(xN),display:R(),tooltip:R().optional()})),pH=G({buyAmount:R().describe("Buy amount"),buyAmountMaxSlippage:R().describe("Buy amount max slippage"),buyAsset:R().describe("Asset to buy"),fees:B(KN),provider:L.enum(J),sellAmount:R().describe("Sell amount"),sellAsset:R().describe("Asset to sell")}),oH=G({buyAsset:R().describe("Asset to buy"),destinationAddress:B(R().describe("Destination address")),estimatedTime:B(mN),expectedBuyAmount:R().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:R().describe("Expected Buy amount max slippage"),expiration:B(R().describe("Expiration")),fees:KN,inboundAddress:B(R().describe("Inbound address")),legs:t(pH),memo:B(R().describe("Memo")),meta:pA,providers:t(L.enum(J)),routeId:R().describe("Route ID"),sellAmount:R().describe("Sell amount"),sellAsset:R().describe("Asset to sell"),sourceAddress:B(R().describe("Source address")),targetAddress:B(R().describe("Target address")),totalSlippageBps:_().describe("Total slippage in bps"),tx:B(kN([qA,KA,kA,kH,mA,R()])),txType:B(L.enum(EN)),warnings:oA}),fA=G({error:B(R().describe("Error message")),providerErrors:B(t(G({errorCode:B(L.enum(RN)),message:B(R()),provider:L.enum(J).optional()}))),quoteId:R().describe("Quote ID"),routes:t(oH)}),CA=L.object({chainId:L.enum(BN),createdAt:L.date(),id:L.number(),unit:L.string(),value:L.string()}),fH=L.array(CA),hA=L.union([CA,fH]),NR=t(G({chain:L.enum(tN),decimal:_(),identifier:R(),symbol:R(),ticker:R(),value:R()})),AR=L.union([L.object({amount:L.string(),spender:L.string(),tokenIdentifier:L.string(),userWalletAddress:L.string()}),L.object({amount:L.string(),chainId:L.enum(BN),spender:L.string(),tokenContractAddress:L.string(),userWalletAddress:L.string()}),L.object({routeId:L.string()})]),TR=L.object({approvalTransaction:L.optional(L.object({data:L.string(),from:L.string(),gasLimit:L.optional(L.string()),gasPrice:L.optional(L.string()),to:L.string(),value:L.string()})),approvedAmount:L.string(),isApproved:L.boolean()}),CH=L.object({data:L.string().describe("Encoded approval call data"),from:L.string().describe("User wallet address"),gasLimit:L.string().optional().describe("Estimated gas limit"),gasPrice:L.string().optional().describe("Current gas price"),to:L.string().describe("Token contract address"),value:L.string().describe("ETH value (always '0' for approvals)")}),XA=L.object({buyAmount:L.string().describe("Buy amount").optional(),buyAmountMaxSlippage:L.string().describe("Buy amount max slippage").optional(),buyAsset:L.string().describe("Asset to buy"),expectedBuyAmount:L.string().describe("Expected Buy amount").optional(),expectedBuyAmountMaxSlippage:L.string().describe("Expected Buy amount max slippage").optional(),fees:KN,provider:L.enum(J),sellAmount:L.string().describe("Sell amount"),sellAsset:L.string().describe("Asset to sell")}),dA=XA.extend({estimatedTime:L.optional(mN),expiration:L.optional(L.string().describe("Expiration")),legs:L.array(XA),providers:L.array(L.enum(J)),routeId:L.string().describe("Route ID"),totalSlippageBps:L.number().describe("Total slippage in bps"),warnings:oA}).omit({provider:!0}),hH=L.object({method:L.string(),payload:L.optional(L.unknown()),url:L.string()}),dH=dA.extend({meta:yA,nextActions:L.optional(L.array(hH))}),HR=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(L.object({errorCode:L.optional(L.enum(RN)),message:L.optional(L.string()),provider:L.enum(J).optional()}))),quoteId:L.string().describe("Quote ID"),routes:L.array(dH)}),PR=L.object({providers:L.array(L.enum(J)).optional().describe("Optional list of providers to query for trading pairs"),sellAsset:L.string().describe("Asset identifier to sell (e.g., 'BTC.BTC' or 'ETH.ETH')")}),cH=L.object({chain:L.enum(tN).describe("Chain the asset is on"),identifier:L.string().describe("Asset identifier (e.g., 'ETH.USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')"),providers:L.array(L.enum(J)).describe("Providers that support this trading pair"),symbol:L.string().describe("Asset symbol"),ticker:L.string().describe("Asset ticker")}),LR=L.object({buyAssets:L.array(cH).describe("List of assets that can be swapped to"),sellAsset:L.string().describe("The input sell asset identifier")}),cA=dA.extend({destinationAddress:L.string().describe("Destination address"),inboundAddress:L.optional(L.string().describe("Inbound address")),memo:L.optional(L.string().describe("Memo to include in the transaction")),meta:pA,sourceAddress:L.string().describe("Source address"),targetAddress:L.optional(L.string().describe("Target address")),tx:B(kN([qA,KA,kA,mA,R()])),txType:L.optional(L.enum(EN))}),lH=L.object({data:L.optional(L.record(L.string(),L.string().optional())),errorCode:L.enum(RN),message:L.string().optional(),provider:L.enum(J).optional()}),RR=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(lH)),quoteId:L.string().describe("Quote ID"),routes:L.array(cA)}),lA=cA.extend({approvalTx:CH.optional().describe("Optional approval transaction if ERC-20 approval is required before swap"),swapId:L.string().describe("The unique swap ID for tracking")});var V=M.extend({dynamicHeader:async()=>{let N=X.get("widgetId"),A=X.get("widgetKey");if(N&&A&&typeof window<"u"){let H=Math.floor(Date.now()/1000),P=window.location.origin,F=await YA(A,N,P,H);return{Origin:P,"X-Signature":F,"X-Timestamp":H.toString(),"x-widget-id":N}}let{swapKit:T}=X.get("apiKeys");return T?{"x-api-key":T}:{}}});async function iH(N){let A=await V.post(j("/track"),{json:N});try{let T=vA.safeParse(A);if(!T.success)throw new g("api_v2_invalid_response",T.error);return T.data}catch(T){return A}}async function sH(N){let{getQuote:A}=X.get("endpoints");if(A)return A(N);let H=X.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",P=await V.post(j(H),{json:N});if(P.error)throw new g("api_v2_server_error",{message:P.error});try{let F=fA.safeParse(P);if(!F.success)throw new g("api_v2_invalid_response",F.error);return F.data}catch{return P}}async function eH(N){let{getRouteWithTx:A}=X.get("endpoints");if(A)return A(N);let H=X.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",P=await V.post(j(H),{json:N});try{let F=lA.safeParse(P);if(!F.success)throw new g("api_v2_invalid_response",F.error);return F.data}catch(F){return console.error(new g("api_v2_invalid_response",F)),P}}async function aH({chain:N,address:A,scamFilter:T=!0}){let{getBalance:H}=X.get("endpoints");if(H)return H({address:A,chain:N});let P=j(`/balance?chain=${N}&address=${A}`),F=await V.get(P),I=Array.isArray(F)?F:[];return T?nP(I):I}function NP(N){let A=rH(N).with({routeId:ON.string,spender:ON.string},({routeId:T,spender:H})=>j(`/approve?routeId=${T}&sourceAddress=${H}`)).with({assetValue:ON.instanceOf(W),spender:ON.string,userWallet:ON.string},({spender:T,userWallet:H,assetValue:P})=>j(`/approve?tokenIdentifier=${P.toString()}&userWalletAddress=${H}&spender=${T}&amount=${P.getValue("string")}`)).exhaustive();return V.get(A)}function AP(){let N=j("/providers");return V.get(N)}function TP(N){let A=j(`/tokens?provider=${N}`);return V.get(A)}async function HP(N){let A=j("/price"),T=await V.post(A,{json:N});try{let H=ZA.safeParse(T);if(!H.success)throw new g("api_v2_invalid_response",H.error);return H.data}catch(H){throw new g("api_v2_invalid_response",H)}}async function PP(){let N=j("/gas"),A=await V.get(N);try{let T=hA.safeParse(A);if(!T.success)throw new g("api_v2_invalid_response",T.error);return Array.isArray(T)?T:[T]}catch(T){throw new g("api_v2_invalid_response",T)}}async function LP(N){let{destinationAddress:A}=N;if(!A)throw new g("chainflip_broker_invalid_params");let T=X.get("integrations").chainflip?.brokerUrl||j("/chainflip/broker/channel"),H=await V.post(T,{json:N});try{let P=jA.safeParse(H);if(!P.success)throw new g("api_v2_invalid_response",P.error);return P.data}catch(P){throw new g("api_v2_invalid_response",P)}}async function RP(N){let{destinationAddress:A}=N;if(!A)throw new g("chainflip_broker_invalid_params");let T=j("/near/channel"),H=await V.post(T,{json:N});try{let P=VA.safeParse(H);if(!P.success)throw new g("api_v2_invalid_response",P.error);return P.data}catch(P){throw new g("api_v2_invalid_response",P)}}function j(N){let{isDev:A,apiUrl:T,devApiUrl:H}=X.get("envs"),{enabled:P,quoteUrl:F,swapUrl:I}=X.get("localMode");if(P&&N){let[$]=N.split("?");if($==="/quote"||$==="/v3/quote")return`${F}${N}`;if($==="/swap"||$==="/v3/swap")return`${I}${N}`}return`${A?H:T}${N}`}function FP(N){try{return W.from({asset:N.identifier})}catch{return}}var uP=new Set(["OP.OP"]),IP=/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/im;function nP(N){return N.filter((A)=>{let T=FP(A);if(!T)return!1;if(uP.has(T.toString().toUpperCase()))return!0;return(!yN.includes(T.chain)||T.isGasAsset||!!T.address)&&!IP.test(T.ticker)})}async function BP(N){let{getSwapTo:A}=X.get("endpoints");if(A)return A(N);let T=new URLSearchParams({sellAsset:N.sellAsset});if(N.providers?.length)for(let I of N.providers)T.append("providers",I);let H=j(`/swapTo?${T.toString()}`),P=await V.get(H);if(!Array.isArray(P))return{buyAssets:[],sellAsset:N.sellAsset};let F=[];for(let I of P)try{let O=W.from({asset:I});F.push({chain:O.chain,identifier:O.toString(),providers:[],symbol:O.symbol,ticker:O.ticker})}catch{}return{buyAssets:F,sellAsset:N.sellAsset}}var oN={};dN(oN,{getThorchainQueue:()=>MP,getTcyStakers:()=>tP,getTcyStaker:()=>XP,getTcyClaimers:()=>bP,getTcyClaimer:()=>EP,getTNSPreferredAsset:()=>YP,getTHORNodeTNSDetails:()=>rA,getRunePoolProviderInfo:()=>UP,getRunePoolInfo:()=>SP,getNodes:()=>_P,getMimirInfo:()=>gP,getLastBlock:()=>GP,getInboundAddresses:()=>DP});import{match as OP}from"ts-pattern";function q(N){let{isStagenet:A}=X.get("envs"),T=X.get("thornodeUrls");return`${OP({isStagenet:A,type:N}).with({type:"mayachain"},({isStagenet:P})=>P?T.MAYA_STAGENET:T.MAYA).otherwise(({isStagenet:P})=>P?T.THOR_STAGENET:T.THOR)}/${N??"thorchain"}`}function $P(N){let A=N==="mayachain"?"mayaname":"thorname";return`${q(N)}/${A}`}function GP(N="thorchain"){return M.get(`${q(N)}/lastblock`)}function MP(N){return M.get(`${q(N)}/queue`)}function _P(N){return M.get(`${q(N)}/nodes`)}function gP(N){return M.get(`${q(N)}/mimir`)}function DP(N){return M.get(`${q(N)}/inbound_addresses`)}async function rA({type:N,name:A}){try{return await M.get(`${$P(N)}/${A}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:A,owner:"",preferred_asset:""}}}async function YP({type:N,tns:A}){let T=await rA({name:A,type:N});if(!T.preferred_asset||T.preferred_asset===".")return;return W.from({asset:T.preferred_asset,asyncTokenLookup:!0})}function SP(N){return M.get(`${q(N)}/runepool`)}function UP({type:N,thorAddress:A}){return M.get(`${q(N)}/rune_provider/${A}`)}function XP({type:N,address:A}){return M.get(`${q(N)}/tcy_staker/${A}`)}function tP(N){return M.get(`${q(N)}/tcy_stakers`)}function EP({type:N,address:A}){return M.get(`${q(N)}/tcy_claimer/${A}`)}function bP(N){return M.get(`${q(N)}/tcy_claimers`)}var UR={...pN,mayachainMidgard:DA,thorchainMidgard:gA,thornode:oN};
5
- export{wP as a,RN as b,xN as c,J as d,QN as e,TT as f,HT as g,PT as h,wN as i,LT as j,Z as k,X as l,g as m,M as n,rP as o,iP as p,sP as q,eP as r,l as s,ZN as t,bT as u,r as v,LL as w,BL as x,RA as y,FA as z,gN as A,WN as B,f as C,uN as D,OL as E,$L as F,IA as G,gL as H,h as I,y as J,W as K,zL as L,UN as M,YA as N,bA as O,EN as P,xA as Q,QA as R,wA as S,zA as T,oL as U,fL as V,CL as W,hL as X,AN as Y,JA as Z,dL as _,ZA as $,cL as aa,lL as ba,WA as ca,EH as da,jA as ea,SA as fa,rL as ga,VA as ha,vA as ia,iL as ja,sL as ka,KN as la,mN as ma,qA as na,kA as oa,WH as pa,eL as qa,KA as ra,kH as sa,mA as ta,KH as ua,aL as va,mH as wa,yH as xa,yA as ya,pA as za,oA as Aa,oH as Ba,fA as Ca,CA as Da,hA as Ea,AR as Fa,TR as Ga,CH as Ha,HR as Ia,PR as Ja,cH as Ka,LR as La,cA as Ma,lH as Na,RR as Oa,lA as Pa,UR as Qa};