@swapkit/helpers 4.12.7 → 4.12.9

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/api/index.js CHANGED
@@ -1 +1 @@
1
- import{$ as m,Aa as N,Ba as O,Ca as P,Da as Q,Ea as R,Fa as S,Ga as T,Ha as U,Ia as V,Ja as W,Ka as X,La as Y,Ma as Z,Na as _,Oa as $,P as a,Pa as aa,Q as b,Qa as ba,R as c,Ra as ca,S as d,T as e,U as f,V as g,W as h,X as i,Y as j,Z as k,_ as l,aa as n,ba as o,ca as p,da as q,ea as r,fa as s,ga as t,ha as u,ia as v,ja as w,ka as x,la as y,ma as z,na as A,oa as B,pa as C,qa as D,ra as E,sa as F,ta as G,ua as H,va as I,wa as J,xa as K,ya as L,za as M}from"../chunk-4wzdfbhr.js";export{c as TxnType,e as TxnStatus,C as TronTransactionSchema,x as TransactionSchema,y as TransactionDTOSchema,f as TrackingStatus,h as TrackingRequestSchema,i as TrackingRequestQuerySchema,w as TrackerResponseSchema,g as TokenSchema,m as TokenDetailsMetadataSchema,H as TONTransactionSchema,Z as SwapToResponseSchema,X as SwapToRequestSchema,Y as SwapToAssetSchema,ba as SwapRouteV2ResponseSchema,ca as SwapKitApi,G as StarknetTransactionSchema,O as RouteQuoteWarningSchema,b as RouteQuoteTxType,$ as RouteQuoteProviderErrorSchema,N as RouteQuoteMetadataV2Schema,M as RouteQuoteMetadataSchema,K as RouteQuoteMetadataAssetSchema,J as RouteLegWithoutAddressesSchema,I as RouteLegSchema,W as QuoteV3ResponseSchema,aa as QuoteV2ResponseSchema,_ as QuoteRouteV2Response,Q as QuoteResponseSchema,P as QuoteResponseRouteItem,o as QuoteRequestSchema,d as ProviderAction,a as PriorityLabel,n as PriceResponseSchema,p as PriceRequestSchema,v as NearSwapResponseSchema,u as NearDepositChannelResultSchema,t as NearDepositChannelParamsSchema,R as GasSchema,S as GasResponseSchema,z as FeesSchema,A as EstimatedTimeSchema,B as EVMTransactionSchema,E as EVMTransactionDetailsSchema,D as EVMTransactionDetailsParamsSchema,s as DepositChannelResponseSchema,q as DepositChannelParamsSchema,F as CosmosTransactionSchema,l as CoinGeckoMetadataSchema,L as ChainflipMetadataSchema,r as BrokerDepositChannelParamsSchema,k as AssetValueSchema,U as ApproveResponseSchema,T as ApproveRequestParams,V as ApprovalTransactionSchema,j as ApiV2ErrorSchema};
1
+ import{$ as m,Aa as N,Ba as O,Ca as P,Da as Q,Ea as R,Fa as S,Ga as T,Ha as U,Ia as V,Ja as W,Ka as X,La as Y,Ma as Z,Na as _,Oa as $,P as a,Pa as aa,Q as b,Qa as ba,R as c,Ra as ca,S as d,T as e,U as f,V as g,W as h,X as i,Y as j,Z as k,_ as l,aa as n,ba as o,ca as p,da as q,ea as r,fa as s,ga as t,ha as u,ia as v,ja as w,ka as x,la as y,ma as z,na as A,oa as B,pa as C,qa as D,ra as E,sa as F,ta as G,ua as H,va as I,wa as J,xa as K,ya as L,za as M}from"../chunk-71e6bysh.js";export{c as TxnType,e as TxnStatus,C as TronTransactionSchema,x as TransactionSchema,y as TransactionDTOSchema,f as TrackingStatus,h as TrackingRequestSchema,i as TrackingRequestQuerySchema,w as TrackerResponseSchema,g as TokenSchema,m as TokenDetailsMetadataSchema,H as TONTransactionSchema,Z as SwapToResponseSchema,X as SwapToRequestSchema,Y as SwapToAssetSchema,ba as SwapRouteV2ResponseSchema,ca as SwapKitApi,G as StarknetTransactionSchema,O as RouteQuoteWarningSchema,b as RouteQuoteTxType,$ as RouteQuoteProviderErrorSchema,N as RouteQuoteMetadataV2Schema,M as RouteQuoteMetadataSchema,K as RouteQuoteMetadataAssetSchema,J as RouteLegWithoutAddressesSchema,I as RouteLegSchema,W as QuoteV3ResponseSchema,aa as QuoteV2ResponseSchema,_ as QuoteRouteV2Response,Q as QuoteResponseSchema,P as QuoteResponseRouteItem,o as QuoteRequestSchema,d as ProviderAction,a as PriorityLabel,n as PriceResponseSchema,p as PriceRequestSchema,v as NearSwapResponseSchema,u as NearDepositChannelResultSchema,t as NearDepositChannelParamsSchema,R as GasSchema,S as GasResponseSchema,z as FeesSchema,A as EstimatedTimeSchema,B as EVMTransactionSchema,E as EVMTransactionDetailsSchema,D as EVMTransactionDetailsParamsSchema,s as DepositChannelResponseSchema,q as DepositChannelParamsSchema,F as CosmosTransactionSchema,l as CoinGeckoMetadataSchema,L as ChainflipMetadataSchema,r as BrokerDepositChannelParamsSchema,k as AssetValueSchema,U as ApproveResponseSchema,T as ApproveRequestParams,V as ApprovalTransactionSchema,j as ApiV2ErrorSchema};
@@ -0,0 +1,4 @@
1
+ var qP={};b(qP,{TxnType:()=>yN,TxnStatus:()=>CN,TronTransactionSchema:()=>aN,TransactionSchema:()=>yH,TransactionDTOSchema:()=>fH,TrackingStatus:()=>dN,TrackingRequestSchema:()=>bH,TrackingRequestQuerySchema:()=>zH,TrackerResponseSchema:()=>sN,TokenSchema:()=>wH,TokenDetailsMetadataSchema:()=>ZH,TONTransactionSchema:()=>AA,SwapToResponseSchema:()=>PP,SwapToRequestSchema:()=>HP,SwapToAssetSchema:()=>rA,SwapRouteV2ResponseSchema:()=>IA,SwapKitApi:()=>WP,StarknetTransactionSchema:()=>oA,RouteQuoteWarningSchema:()=>PA,RouteQuoteTxType:()=>$N,RouteQuoteProviderErrorSchema:()=>lA,RouteQuoteMetadataV2Schema:()=>HA,RouteQuoteMetadataSchema:()=>TA,RouteQuoteMetadataAssetSchema:()=>fA,RouteLegWithoutAddressesSchema:()=>lH,RouteLegSchema:()=>yA,QuoteV3ResponseSchema:()=>TP,QuoteV2ResponseSchema:()=>LP,QuoteRouteV2Response:()=>FA,QuoteResponseSchema:()=>LA,QuoteResponseRouteItem:()=>dA,QuoteRequestSchema:()=>jH,ProviderAction:()=>fN,PriorityLabel:()=>oN,PriceResponseSchema:()=>cN,PriceRequestSchema:()=>vH,NearSwapResponseSchema:()=>iN,NearDepositChannelResultSchema:()=>VH,NearDepositChannelParamsSchema:()=>pN,GasSchema:()=>RA,GasResponseSchema:()=>uA,FeesSchema:()=>bN,EstimatedTimeSchema:()=>zN,EVMTransactionSchema:()=>eN,EVMTransactionDetailsSchema:()=>CH,EVMTransactionDetailsParamsSchema:()=>pA,DepositChannelResponseSchema:()=>lN,DepositChannelParamsSchema:()=>rN,CosmosTransactionSchema:()=>NA,CoinGeckoMetadataSchema:()=>hN,ChainflipMetadataSchema:()=>CA,BrokerDepositChannelParamsSchema:()=>KA,AssetValueSchema:()=>l,ApproveResponseSchema:()=>aH,ApproveRequestParams:()=>eH,ApprovalTransactionSchema:()=>hA,ApiV2ErrorSchema:()=>JH});module.exports=VP(qP);var r=require("@swapkit/types");var iT={};b(iT,{getMinAmountByChain:()=>fT,AssetValue:()=>J});var G=require("@swapkit/types"),qN=require("ethers"),wN=require("ts-pattern");var vT={};b(vT,{parseSymbolForAddress:()=>a,isGasAsset:()=>FN,getTokenLogoURI:()=>ZT,getCommonAssetInfo:()=>IN,getAssetType:()=>EN,findAssetBy:()=>jT,fetchTokenInfo:()=>vN,assetFromString:()=>p,CommonAssetStrings:()=>XT});var I=require("@swapkit/types"),e=require("ts-pattern");var BT={};b(BT,{RequestClient:()=>O});var HT={};b(HT,{swapKitConfigStore:()=>z,SKConfig:()=>M});var V=require("@swapkit/types"),YA=require("zustand/vanilla");var AT={};b(AT,{WarningCodeEnum:()=>DN,WalletOption:()=>UN,V3SwapFlowSupport:()=>NT,ProviderName:()=>w,NetworkDerivationPath:()=>aA,MemoType:()=>tA,LedgerErrorCode:()=>DA,FeeTypeEnum:()=>YN,FeeOption:()=>GA,ErrorCode:()=>s,ApproveMode:()=>_A});var tN=require("@swapkit/types"),aA=tN.AllChains.reduce((A,T)=>{return A[T]=tN.getChainConfig(T).networkDerivationPath,A},{});var s;((R)=>{R.unknownError="unknownError";R.test_error="test_error";R.providerDetailsError="providerDetailsError";R.blockHeaderNotFound="blockHeaderNotFound";R.blockHashNotFoundAtHeight="blockHashNotFoundAtHeight";R.blockHashNotFoundAtHash="blockHashNotFoundAtHash";R.txHashMissing="txHashMissing";R.assetValueMissingInfo="assetValueMissingInfo";R.invalidAsset="invalidAsset";R.blockIsRequired="blockIsRequired";R.currentBlockHeaderNotFound="currentBlockHeaderNotFound";R.failedToRetrieveBalance="failedToRetrieveBalance";R.failedToRetrieveBlock="failedToRetrieveBlock";R.failedToRetrieveFees="failedToRetrieveFees";R.notImplementedBCH="notImplementedBCH";R.notImplementedDoge="notImplementedDoge";R.noPoolsFound="noPoolsFound";R.noVaultsFound="noVaultsFound";R.noTxFound="noTxFound";R.noInputCoinFound="noInputCoinFound";R.noBlockDataFound="noBlockDataFound";R.multipleCosmosMessages="multipleCosmosMessages";R.heightOrHashNotProvided="heightOrHashNotProvided";R.unknownDenom="unknownDenom";R.invalidBlockHeight="invalidBlockHeight";R.timestampExtrinsicNoArgumentsForBlock="timestampExtrinsicNoArgumentsForBlock";R.timestampExtrinsicNoTimestampForBlock="timestampExtrinsicNoTimestampForBlock";R.noTimestampExtrinsicForHash="noTimestampExtrinsicForHash";R.timestampExtrinsicNoArgumentsForHash="timestampExtrinsicNoArgumentsForHash";R.txMemoUndefined="txMemoUndefined";R.txMemoIncorrect="txMemoIncorrect";R.txTypeNotFound="txTypeNotFound";R.txNoMessage="txNoMessage";R.txNotFound="txNotFound";R.txReceiptNotFound="txReceiptNotFound";R.txParsingError="txParsingError";R.txLogsParsingError="txLogsParsingError";R.blockNotFound="blockNotFound";R.balanceNotFound="balanceNotFound";R.configError="configError";R.synthSwapDisallowed="synthSwapDisallowed";R.providerQuoteTimeout="providerQuoteTimeout";R.noQuoteResponse="noQuoteResponse";R.noPoolAssetsFound="noPoolAssetsFound";R.noThorchainPools="noThorchainPools";R.noMayachainPools="noMayachainPools";R.noThorchainNetworkInfo="noThorchainNetworkInfo";R.invalidAffiliateFee="invalidAffiliateFee";R.invalidBuyAssetAddress="invalidBuyAssetAddress";R.invalidSellAssetAddress="invalidSellAssetAddress";R.invalidSourceAddress="invalidSourceAddress";R.invalidDestinationAddress="invalidDestinationAddress";R.sourceAddressIsSmartContract="sourceAddressIsSmartContract";R.destinationAddressIsSmartContract="destinationAddressIsSmartContract";R.invalidChainId="invalidChainId";R.unsupportedChainId="unsupportedChainId";R.unsupportedEVMChainId="unsupportedEVMChainId";R.unsupportedMethod="unsupportedMethod";R.unsupportedProvider="unsupportedProvider";R.invalidParamsForMethod="invalidParamsForMethod";R.unsupportedAdapter="unsupportedAdapter";R.noWhitelistTokens="noWhitelistTokens";R.failedFetchGasPrice="failedFetchGasPrice";R.failedToCreateDepositChannel="failedToCreateDepositChannel";R.noProviderDetailsFound="noProviderDetailsFound";R.noTokenListsFound="noTokenListsFound";R.tokenNotFound="tokenNotFound";R.tokenPriceNotFound="tokenPriceNotFound";R.tokenPriceFailedToUpdate="tokenPriceFailedToUpdate";R.swapAmountTooSmall="swapAmountTooSmall";R.legsArrayIsEmpty="legsArrayIsEmpty";R.failedToFetchQuoteForLeg="failedToFetchQuoteForLeg";R.noBlockHeaderFound="noBlockHeaderFound";R.failedToSimulateSwap="failedToSimulateSwap";R.addressScreeningFailed="addressScreeningFailed";R.noLiquidtyProvidersFound="noLiquidtyProvidersFound";R.insufficientLiquidity="insufficientLiquidity";R.noInboundDataFound="noInbounDataFound";R.noInboundAddressesFound="noInboundAddressesFound";R.noInboundAddressFoundForChain="noInboundAddressFoundForChain";R.noLastBlocksFound="noLastBlocksFound";R.noVersionFound="noVersionFound";R.noConstantsFound="noConstantsFound";R.noMimirsFound="noMimirsFound";R.noRoutesFound="noRoutesFound";R.quoteNotFound="quoteNotFound";R.ledgerSignFailed="ledgerSignFailed";R.ledgerWrongPayload="ledgerWrongPayload";R.ledgerFetchSwapFailed="ledgerFetchSwapFailed";R.failedToFetchTx="failedToFetchTx";R.failedBuildTransactionDetails="failedBuildTransactionDetails";R.noLegsForRoute="noLegsForRoute";R.noRouterAddressFound="noRouterAddressFound";R.noAggregatorAddressFound="noAggregatorAddressFound";R.noContractInstanceFound="noContractInstanceFound";R.noContractAddressFound="noContractAddressFound";R.invalidAffiliate="invalidAffiliate";R.thornameAffiliate="thornameAffiliate";R.providerNotfound="No provider found";R.noRecordFound="No Record found";R.slippageTooLow="Slippage too low";R.tradingHalted="tradingHalted";R.noWrappedGasAsset="noWrappedGasAsset";R.aggregatorAddressNotFound="aggregatorAddressNotFound";R.routerAddressNotFound="routerAddressNotFound";R.dummyAddressNotFound="dummyAddressNotFound";R.trackerError="trackerError";R.thorchainPoolUnavailable="thorchainPoolUnavailable";R.noOhlcvDataFound="noOhlcvDataFound";R.noTradingPairs="noTradingPairs";R.noLendingAvailability="noLendingAvailability";R.lendingRepayTooSmall="lendingRepayTooSmall";R.missingState="missingState";R.ledgerSwapNotFound="ledgerSwapNotFound";R.ledgerSwapNotReadyForTracking="ledgerSwapNotReadyForTracking";R.errorEstimatingGas="errorEstimatingGas";R.apiKeyInvalid="apiKeyInvalid";R.apiKeyFailedToUpdate="apiKeyFailedToUpdate";R.apiKeyExpired="apiKeyExpired";R.unauthorized="unauthorized";R.failedToCreateMemo="failedToCreateMemo";R.radixIncorrectInstructions="radixIncorrectInstructions";R.radixTxMissedParam="radixTxMissedParam";R.radixTxMissedAccount="radixTxMissedAccount";R.radixManifestParseError="radixManifestParseError";R.radixManifestBuildError="radixManifestBuildError";R.invalidAddressForChain="invalidAddressForChain";R.riskyAddress="riskyAddress";R.noRoutesToProcess="noRoutesToProcess";R.sellAssetAmountTooSmall="sellAssetAmountTooSmall";R.missingPrivateKey="missingPrivateKey";R.noMemoPriceProtection="noMemoPriceProtection"})(s||={});var DN;((H)=>{H.highSlippage="highSlippage";H.highPriceImpact="highPriceImpact"})(DN||={});var w;((S)=>{S.CHAINFLIP="CHAINFLIP";S.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";S.JUPITER="JUPITER";S.MAYACHAIN="MAYACHAIN";S.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";S.ONEINCH="ONEINCH";S.PANCAKESWAP="PANCAKESWAP";S.SUSHISWAP_V2="SUSHISWAP_V2";S.THORCHAIN="THORCHAIN";S.THORCHAIN_STREAMING="THORCHAIN_STREAMING";S.TRADERJOE_V2="TRADERJOE_V2";S.UNISWAP_V2="UNISWAP_V2";S.UNISWAP_V3="UNISWAP_V3";S.NEAR="NEAR";S.GARDEN="GARDEN";S.OKX="OKX";S.HARBOR="HARBOR";S.FLASHNET="FLASHNET"})(w||={});var YN;((B)=>{B.LIQUIDITY="liquidity";B.NETWORK="network";B.INBOUND="inbound";B.OUTBOUND="outbound";B.AFFILIATE="affiliate";B.TAX="tax";B.PRIORITY="priority";B.SERVICE="service"})(YN||={});var GA;((P)=>{P.Average="average";P.Fast="fast";P.Fastest="fastest"})(GA||={});var _A;((H)=>{H.Approve="approve";H.CheckOnly="checkOnly"})(_A||={});var tA;((_)=>{_.NAME_REGISTER="~";_.BOND="BOND";_.DEPOSIT="+";_.LEAVE="LEAVE";_.UNBOND="UNBOND";_.WITHDRAW="-";_.RUNEPOOL_DEPOSIT="POOL+";_.RUNEPOOL_WITHDRAW="POOL-";_.CLAIM_TCY="tcy";_.STAKE_TCY="tcy+";_.UNSTAKE_TCY="tcy-"})(tA||={});var $=require("@swapkit/types"),UN;((t)=>{t.BITGET="BITGET";t.BRAVE="BRAVE";t.COINBASE_MOBILE="COINBASE_MOBILE";t.COINBASE_WEB="COINBASE_WEB";t.COSMOSTATION="COSMOSTATION";t.CTRL="CTRL";t.EIP6963="EIP6963";t.EXODUS="EXODUS";t.KEEPKEY="KEEPKEY";t.KEEPKEY_BEX="KEEPKEY_BEX";t.KEPLR="KEPLR";t.KEYSTORE="KEYSTORE";t.LEAP="LEAP";t.LEDGER="LEDGER";t.METAMASK="METAMASK";t.OKX="OKX";t.OKX_MOBILE="OKX_MOBILE";t.ONEKEY="ONEKEY";t.PASSKEYS="PASSKEYS";t.PETRA="PETRA";t.PHANTOM="PHANTOM";t.POLKADOT_JS="POLKADOT_JS";t.RADIX_WALLET="RADIX_WALLET";t.TALISMAN="TALISMAN";t.TREZOR="TREZOR";t.TRONLINK="TRONLINK";t.TRUSTWALLET_WEB="TRUSTWALLET_WEB";t.VULTISIG="VULTISIG";t.WALLETCONNECT="WALLETCONNECT";t.WALLET_SELECTOR="WALLET_SELECTOR";t.XAMAN="XAMAN"})(UN||={});var DA;((P)=>{P[P.NoError=36864]="NoError";P[P.LockedDevice=21781]="LockedDevice";P[P.TC_NotFound=65535]="TC_NotFound"})(DA||={});var x=["BITGET","BRAVE","COINBASE_MOBILE","COINBASE_WEB","COSMOSTATION","CTRL","EIP6963","KEEPKEY","KEEPKEY_BEX","KEYSTORE","LEDGER","METAMASK","OKX","OKX_MOBILE","PASSKEYS","PHANTOM","TALISMAN","TREZOR","TRUSTWALLET_WEB","VULTISIG","WALLETCONNECT"],NT={[$.Chain.Arbitrum]:x,[$.Chain.Aurora]:x,[$.Chain.Avalanche]:x,[$.Chain.Base]:x,[$.Chain.Berachain]:x,[$.Chain.BinanceSmartChain]:x,[$.Chain.Botanix]:x,[$.Chain.Chainflip]:x,[$.Chain.Core]:x,[$.Chain.Corn]:x,[$.Chain.Cronos]:x,[$.Chain.Ethereum]:x,[$.Chain.Gnosis]:x,[$.Chain.Hyperevm]:x,[$.Chain.MegaETH]:x,[$.Chain.Monad]:x,[$.Chain.Optimism]:x,[$.Chain.Polygon]:x,[$.Chain.Sonic]:x,[$.Chain.Unichain]:x,[$.Chain.XLayer]:x,[$.Chain.Bitcoin]:["BITGET","KEYSTORE","OKX","ONEKEY","PASSKEYS","PHANTOM"],[$.Chain.BitcoinCash]:["KEYSTORE"],[$.Chain.Dash]:["KEYSTORE"],[$.Chain.Dogecoin]:["KEYSTORE"],[$.Chain.Litecoin]:["KEYSTORE"],[$.Chain.Zcash]:["KEYSTORE"],[$.Chain.Cosmos]:["COSMOSTATION","CTRL","KEPLR","KEYSTORE","LEAP"],[$.Chain.Kujira]:["COSMOSTATION","CTRL","KEPLR","KEYSTORE","LEAP"],[$.Chain.Maya]:["KEYSTORE"],[$.Chain.Noble]:["COSMOSTATION","CTRL","KEPLR","KEYSTORE","LEAP"],[$.Chain.THORChain]:["COSMOSTATION","KEPLR","KEYSTORE","LEAP"],[$.Chain.Aptos]:["BITGET","KEYSTORE","OKX","PETRA"],[$.Chain.Cardano]:["KEYSTORE"],[$.Chain.HyperCore]:["KEYSTORE"],[$.Chain.Near]:["KEYSTORE","LEDGER"],[$.Chain.Ripple]:["KEYSTORE","LEDGER"],[$.Chain.Solana]:["KEYSTORE","PASSKEYS","PHANTOM"],[$.Chain.Sui]:["KEYSTORE"],[$.Chain.Tron]:["KEYSTORE","LEDGER"],[$.Chain.Stellar]:["KEYSTORE"],[$.Chain.Starknet]:["KEYSTORE"]};var TT=V.AllChains.reduce((A,T)=>{if(!A.THOR_STAGENET)A[V.StagenetChain.Maya]=V.StagenetMAYAConfig.rpcUrls,A[V.StagenetChain.THORChain]=V.StagenetTHORConfig.rpcUrls;return A[T]=V.getChainConfig(T).rpcUrls,A},{}),UA={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:V.AllChains,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"}}},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:TT,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(UN),widgetKey:""},z=YA.createStore((A)=>({...UA,setApiKey:(T,H)=>A((P)=>({apiKeys:{...P.apiKeys,[T]:H}})),setConfig:(T)=>A((H)=>({apiKeys:{...H.apiKeys,...T?.apiKeys},chains:H.chains.concat(T?.chains||[]),endpoints:{...H.endpoints,...T?.endpoints},envs:{...H.envs,...T?.envs},feeMultipliers:T?.feeMultipliers||H.feeMultipliers,integrations:{...H.integrations,...T?.integrations},rpcUrls:{...H.rpcUrls,...T?.rpcUrls},v3SwapFlow:{...H.v3SwapFlow,...T?.v3SwapFlow},wallets:H.wallets.concat(T?.wallets||[]),widgetKey:T?.widgetKey||H.widgetKey})),setEndpoint:(T,H)=>A((P)=>({endpoints:{...P.endpoints,[T]:H}})),setEnv:(T,H)=>A((P)=>({envs:{...P.envs,[T]:H}})),setFeeMultipliers:(T)=>A(()=>({feeMultipliers:T})),setIntegrationConfig:(T,H)=>A((P)=>({integrations:{...P.integrations,[T]:H}})),setRequestOptions:(T)=>A((H)=>({requestOptions:{retry:{...H.requestOptions.retry,...T.retry},timeoutMs:T.timeoutMs||H.requestOptions.timeoutMs}})),setRpcUrl:(T,H)=>A((P)=>({rpcUrls:{...P.rpcUrls,[T]:H}})),setWidgetKey:(T)=>A({widgetKey:T})})),M={get:(A)=>z.getState()[A],getState:z.getState,reinitialize:()=>z.setState(UA),set:(A)=>z.getState().setConfig(A),setApiKey:(A,T)=>z.getState().setApiKey(A,T),setEndpoint:(A,T)=>z.getState().setEndpoint(A,T),setEnv:(A,T)=>z.getState().setEnv(A,T),setFeeMultipliers:(A)=>z.getState().setFeeMultipliers(A),setIntegrationConfig:(A,T)=>z.getState().setIntegrationConfig(A,T),setRequestOptions:(A)=>z.getState().setRequestOptions(A),setRpcUrl:(A,T)=>z.getState().setRpcUrl(A,T),setWidgetKey:(A)=>z.getState().setWidgetKey(A)};var LT={};b(LT,{SwapKitError:()=>g});var PT={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_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_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(A){return JSON.stringify(A,(T,H)=>typeof H==="bigint"?H.toString():H)}class g extends Error{static ErrorCode=PT;errorKey;info;constructor(A,T){let H=typeof A==="string",P=H?A:A.errorKey,L=H?void 0:A.info,u=`${P}${L?`: ${ZN(L)}`:""}`;super(u);if(Object.setPrototypeOf(this,g.prototype),this.name="SwapKitError",this.errorKey=P,this.info=L,this.cause=T,T){let F=T instanceof Error?`${T.message}${T.cause?` (${T.cause})`:""}`:ZN(T);console.error(`SwapKitError [${P}]: ${F}`)}else if(L)console.error(`SwapKitError [${P}]: ${ZN(L)}`)}}var RT=(A)=>new Promise((T)=>setTimeout(T,A)),uT=(A,{baseDelay:T,backoffMultiplier:H,maxDelay:P})=>Math.min(T*H**A,P);function FT(A,T){if(A instanceof Error&&A.name==="AbortError")return!0;if(A instanceof TypeError)return!0;if(T===429)return!0;if(T&&T>=500&&T<600)return!0;return!1}var IT=async(A,T)=>{let H=await fetch(A,T),P;try{P=await H.json()}catch{if(!H.ok)throw new g({errorKey:"helpers_invalid_response",info:{status:H.status,statusText:H.statusText}},{status:H.status,statusText:H.statusText});return{}}if(!H.ok){let u={data:P?.data,error:P?.error,message:P?.message,status:H.status};throw new g({errorKey:P?.error||"helpers_invalid_response",info:u},u)}let L=P?.routes?.length||P?.result||P?.data&&!P?.error;if(P?.error&&!L){let u={data:P.data,error:P.error,message:P.message,status:H.status};throw new g({errorKey:P.error,info:u},u)}if(P?.providerErrors?.length||P?.error&&L)console.warn("[SwapKit] Partial errors in response:",P.providerErrors||P.error);return P};function SN(A,T={}){return async function(P,L={}){let{searchParams:u,json:F,body:n,headers:B,dynamicHeader:D,retry:X,timeoutMs:_,abortController:v,onError:U,onSuccess:q,responseHandler:E,...Q}={...T,...L},RN=M.get("requestOptions"),S={...RN.retry,...X},gN=!!F||P.endsWith(".json"),GN=OT(P,u),BA=D?await D():{},uN=nT(gN,{...B,...BA}),i=gN?JSON.stringify(F):n,JN;for(let _N=0;_N<=S.maxRetries;_N++){let $A=v||new AbortController,gA=setTimeout(()=>$A.abort(),_||RN.timeoutMs);try{let k=await IT(GN,{...Q,body:i,headers:uN,method:A,signal:$A.signal});return clearTimeout(gA),q?.(k)||E?.(k)||k}catch(k){clearTimeout(gA),JN=k;let eA=k?.cause?.status;if(_N>=S.maxRetries||!FT(k,eA))return U?U(k):Promise.reject(k);await RT(uT(_N,S))}}return U?U(JN):Promise.reject(JN)}}function nT(A,T){return{...T,...A&&{"Content-Type":"application/json"}}}function OT(A,T){let H=new URL(A);if(T)H.search=new URLSearchParams(T).toString();return H.toString()}var O={extend:(A)=>({extend:(T)=>O.extend({...A,...T}),get:SN("GET",A),post:SN("POST",A)}),get:SN("GET"),post:SN("POST")};var MT={};b(MT,{initializeRPCUrlsWithFallback:()=>ST,getRPCUrlSync:()=>XA,getRPCUrl:()=>h,_rpcCache:()=>XN});var Y=require("@swapkit/types"),jN=require("ts-pattern");var tT={};b(tT,{wrapWithThrow:()=>GT,warnOnce:()=>d,getTHORNameCost:()=>$T,getMAYANameCost:()=>gT,getChainIdentifier:()=>_T});var MN=require("@swapkit/types");function $T(A){if(A<0)throw new g({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:A}});return 10+A}function gT(A){if(A<0)throw new g({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:A}});return Math.round((10+A*1.0512)*10000000000)/10000000000}function GT(A,T){try{return A()}catch(H){if(T)throw new g(T,H);return}}function _T(A){switch(A){case MN.Chain.THORChain:return`${A}.RUNE`;case MN.Chain.Cosmos:return`${A}.ATOM`;case MN.Chain.BinanceSmartChain:return`${A}`;default:return`${A}.${A}`}}var SA=new Set;function d({condition:A,id:T,warning:H}){if(A){if(SA.has(T))return;console.warn(H),SA.add(T)}}function DT(A){return jN.match(A).with(...Y.EVMChains,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...Y.UTXOChains,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...Y.CosmosChains,...Y.StagenetChains,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(Y.Chain.Polkadot,Y.Chain.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(Y.Chain.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(Y.Chain.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(Y.Chain.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(Y.Chain.Aptos,Y.Chain.Tron,Y.Chain.Radix,Y.Chain.Stellar,()=>"").with(Y.Chain.HyperCore,()=>({type:"meta"})).with(Y.Chain.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(Y.Chain.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(Y.Chain.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new g("helpers_chain_not_supported",{chain:A})})}function YT(A){return jN.match(A).with(Y.Chain.Aptos,()=>"/-/healthy").with(Y.Chain.HyperCore,()=>"/info").with(Y.Chain.Radix,()=>"/status/network-configuration").with(Y.Chain.Stellar,()=>"").with(Y.Chain.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function MA(A,T){try{let H=T.startsWith("wss")?T.replace("wss","https"):T;return(await fetch(`${H}${YT(A)}`,{body:JSON.stringify(DT(A)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var XN=new Map,UT=120000;function XA(A){let[T=""]=M.get("rpcUrls")[A];if(!T)throw d({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 ${A}.`}),new g("helpers_chain_no_public_or_set_rpc_url",{chain:A});let H=XN.get(A);if(H&&Date.now()-H.timestamp<UT)return H.url;return XN.set(A,{timestamp:Date.now(),url:T}),T}async function h(A){let T=XA(A),[,...H]=M.get("rpcUrls")[A];if(await MA(A,T))return T;for(let L of H)if(await MA(A,L))return XN.set(A,{timestamp:Date.now(),url:L}),L;throw new g("helpers_chain_rpc_connection_failed",{chain:A,fallbackUrls:H,primaryRpcUrl:T})}function ST(A){d({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 XT=[`${I.Chain.Maya}.MAYA`,`${I.Chain.Maya}.CACAO`,`${I.Chain.Ethereum}.THOR`,`${I.Chain.Ethereum}.vTHOR`,`${I.Chain.Kujira}.USK`,`${I.Chain.Ethereum}.FLIP`,`${I.Chain.Radix}.XRD`],xA=[I.Chain.Arbitrum,I.Chain.Aurora,I.Chain.Base,I.Chain.Ethereum,I.Chain.Optimism];async function ET(A){let{baseDecimal:T}=I.getChainConfig(I.Chain.Radix);try{let H=await h(I.Chain.Radix),{manager:P}=await O.post(`${H}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:A}),headers:{Accept:"*/*","Content-Type":"application/json"}});return P?.divisibility?.value?.divisibility}catch(H){let P=H instanceof Error?H.message:String(H);return console.warn(`Failed to fetch Radix asset decimals for ${A}: ${P}`),T}}async function QT(A){try{let T=await h(I.Chain.Radix);return(await O.post(`${T}/state/entity/details`,{body:JSON.stringify({addresses:[A],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((L)=>L.key==="symbol")?.value.typed.value||void 0}catch(T){let H=T instanceof Error?T.message:String(T);return console.warn(`Failed to fetch Radix asset symbol for ${A}: ${H}`),""}}async function wA({chain:A,address:T,methodHex:H,id:P}){let L=await h(A);return O.post(L,{body:JSON.stringify({id:P,jsonrpc:"2.0",method:"eth_call",params:[{data:H,to:T.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}async function xT(A){if(!A||A==="0x")return"UNKNOWN";try{let{AbiCoder:T}=await import("ethers");return T.defaultAbiCoder().decode(["string"],A)[0].trim()}catch(T){return console.warn(`Failed to decode ABI string from ${A}: ${T}`),"UNKNOWN"}}function wT(A,T){if(!A||A==="0x")return T;try{return Number(A)}catch(H){return console.warn(`Failed to decode ABI uint8 from ${A}: ${H}`),T}}async function bT({chain:A,address:T}){let{baseDecimal:H}=I.getChainConfig(A),P=T.toLowerCase();if(T===""||!P.startsWith("0x"))return H;let L=await wA({address:T,chain:A,id:2,methodHex:"0x313ce567"}).catch((F)=>{return console.warn(`Could not fetch decimals for ${T} on ${A}: ${F.message}`),{result:""}});return wT(L.result,H)}async function zT({chain:A,address:T}){let H=T.toLowerCase();if(H===""||!H.startsWith("0x"))return;let P=await wA({address:T,chain:A,id:1,methodHex:"0x95d89b41"}).catch((u)=>{return console.warn(`Could not fetch symbol for ${T} on ${A}: ${u.message}`),{result:""}});return await xT(P.result)}async function EA({rpcUrl:A,contractAddress:T,functionSelector:H}){return(await O.post(`${A}/wallet/triggerconstantcontract`,{body:JSON.stringify({contract_address:T,function_selector:H,owner_address:T,parameter:"",visible:!0}),headers:{accept:"application/json","content-type":"application/json"}}).catch(()=>{return}))?.constant_result?.[0]}function QA(A){let T=A.match(/.{2}/g)?.map((H)=>Number.parseInt(H,16))??[];return new TextDecoder().decode(new Uint8Array(T))}function JT(A){return e.match(A).with(void 0,()=>{return}).when((T)=>T.length>=128,(T)=>{let H=Number.parseInt(T.slice(64,128),16);return QA(T.slice(128,128+H*2))}).when((T)=>T.length===64,(T)=>{let H=T.replace(/0+$/,"");if(H.length>0&&H.length%2===0)return QA(H);return}).otherwise(()=>{return})}function vN({chain:A,address:T}){let{baseDecimal:H}=I.getChainConfig(A),P={decimals:H,ticker:void 0};return e.match(A).with(...I.EVMChains,async()=>{try{let{isAddress:L,getAddress:u}=await import("ethers");if(!L(u(T.replace(/^0X/,"0x"))))return P;let[F,n]=await Promise.all([zT({address:T,chain:A}),bT({address:T,chain:A})]);return{decimals:n,ticker:F}}catch(L){return console.warn(`Failed to fetch token info for ${T} on ${A}: ${L?.code} ${L?.message}`),P}}).with(I.Chain.Solana,async()=>{if(!T)return P;try{let L=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${T}`);if(L.ok){let u=await L.json(),F=Array.isArray(u)?u[0]:u;if(F)return{decimals:F.decimals??H,ticker:F.symbol||void 0}}}catch(L){console.warn(`Failed to fetch Solana token info for ${T}: ${L?.code} ${L?.message}`)}return P}).with(I.Chain.Tron,async()=>{if(!T)return P;try{let L=await h(I.Chain.Tron),[u,F]=await Promise.all([EA({contractAddress:T,functionSelector:"symbol()",rpcUrl:L}),EA({contractAddress:T,functionSelector:"decimals()",rpcUrl:L})]),n=JT(u);return{decimals:u!==void 0&&F?Number(BigInt(`0x${F}`)):H,ticker:n}}catch(L){let u=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Tron token info for ${T}: ${u}`),P}}).with(I.Chain.Near,async()=>{if(!T)return P;try{let{JsonRpcProvider:L}=await import("@near-js/providers"),u=await h(I.Chain.Near),n=await new L({url:u}).query({account_id:T,args_base64:Buffer.from("{}").toString("base64"),finality:"final",method_name:"ft_metadata",request_type:"call_function"}),B=JSON.parse(Buffer.from(n.result).toString());return{decimals:B?.decimals||H,ticker:B?.symbol}}catch(L){let u=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Near token info for ${T}: ${u}`),P}}).with(I.Chain.Radix,async()=>{if(!T)return P;try{let[L,u]=await Promise.all([QT(T),ET(T)]);return{decimals:u,ticker:L}}catch(L){let u=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Radix token info for ${T}: ${u}`),P}}).otherwise(async()=>P)}function FN({chain:A,symbol:T}){return e.match(A).with(...xA,()=>T==="ETH").with(I.Chain.Avalanche,()=>T==="AVAX").with(I.Chain.Berachain,()=>T==="BERA").with(I.Chain.Hyperevm,()=>T==="HYPE").with(I.Chain.HyperCore,()=>T==="HYPE").with(I.Chain.BinanceSmartChain,()=>T==="BNB").with(I.Chain.Gnosis,()=>T==="xDAI"||T==="XDAI").with(I.Chain.Monad,()=>T==="MON").with(I.Chain.XLayer,()=>T==="OKB").with(I.Chain.Maya,()=>T==="CACAO").with(I.Chain.Cosmos,()=>T==="ATOM").with(I.Chain.THORChain,()=>T==="RUNE").with(I.Chain.Tron,()=>T==="TRX").with(I.Chain.Ripple,()=>T==="XRP").with(I.Chain.Radix,()=>`${A}.${T}`===IN(A).identifier).otherwise(()=>T===A)}var IN=(A)=>{let{baseDecimal:T}=I.getChainConfig(A);return e.match(A.toUpperCase()).with(...xA,(P)=>({decimal:T,identifier:`${P}.ETH`})).with(I.Chain.THORChain,(P)=>({decimal:T,identifier:`${P}.RUNE`})).with(I.Chain.Cosmos,(P)=>({decimal:T,identifier:`${P}.ATOM`})).with(I.Chain.Maya,(P)=>({decimal:10,identifier:`${P}.CACAO`})).with(I.Chain.BinanceSmartChain,(P)=>({decimal:T,identifier:`${P}.BNB`})).with(I.Chain.Monad,(P)=>({decimal:T,identifier:`${P}.MON`})).with(I.Chain.Avalanche,(P)=>({decimal:T,identifier:`${P}.AVAX`})).with(I.Chain.Gnosis,(P)=>({decimal:T,identifier:`${P}.xDAI`})).with(I.Chain.XLayer,(P)=>({decimal:T,identifier:`${P}.OKB`})).with(I.Chain.Berachain,(P)=>({decimal:T,identifier:`${P}.BERA`})).with(I.Chain.Hyperevm,(P)=>({decimal:T,identifier:`${P}.HYPE`})).with(I.Chain.HyperCore,(P)=>({decimal:T,identifier:`${P}.HYPE`})).with(I.Chain.Tron,(P)=>({decimal:T,identifier:`${P}.TRX`})).with(I.Chain.Solana,I.Chain.Chainflip,I.Chain.Kujira,I.Chain.Ripple,I.Chain.Polkadot,I.Chain.Near,...I.UTXOChains,(P)=>({decimal:T,identifier:`${P}.${P}`})).with(I.Chain.Radix,"XRD.XRD",()=>({decimal:T,identifier:"XRD.XRD"})).with(I.Chain.Polygon,"POL.POL",()=>({decimal:T,identifier:"POL.POL"})).with("KUJI.USK",(P)=>({decimal:6,identifier:P})).with("ETH.FLIP",()=>({decimal:I.getChainConfig(I.Chain.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:I.getChainConfig(I.Chain.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:I.getChainConfig(I.Chain.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(P)=>({decimal:10,identifier:P})).with("MAYA.MAYA",(P)=>({decimal:4,identifier:P})).otherwise(()=>({decimal:T,identifier:A}))};function EN({chain:A,symbol:T}){if(T.includes("/"))return"Synth";if(T.includes("~"))return"Trade";return e.match(A).with(I.Chain.Radix,()=>T===I.Chain.Radix||`${A}.${T}`===IN(A).identifier).with(I.Chain.Arbitrum,I.Chain.Optimism,I.Chain.Base,I.Chain.Aurora,()=>T===I.Chain.Ethereum).with(I.Chain.Cosmos,()=>T==="ATOM").with(I.Chain.BinanceSmartChain,()=>T==="BNB").with(I.Chain.Maya,()=>T==="CACAO").with(I.Chain.Monad,()=>T==="MON").with(I.Chain.THORChain,()=>T==="RUNE").with(I.Chain.Tron,()=>T==="TRX").with(I.Chain.Hyperevm,()=>T==="HYPE").with(I.Chain.HyperCore,()=>T==="HYPE").with(I.Chain.XLayer,()=>T==="OKB").otherwise(()=>T===A)?"Native":A}var p=(A)=>{let[T,...H]=A.split("."),P=A.includes("/"),L=H.join("."),u=L?.split("-"),F=u?.length?u.length===1?u[0]:u.slice(0,-1).join("-"):void 0;return{chain:T,symbol:L,synth:P,ticker:F}};function a(A,T){let P=T===I.Chain.Near?A.indexOf("-"):A.lastIndexOf("-");if(P===-1)return{address:void 0,ticker:A};return{address:A.slice(P+1),ticker:A.slice(0,P)}}function ZT(A){return`https://storage.googleapis.com/token-list-swapkit-dev/images/${A.toLowerCase()}.png`}async function jT(A){let{loadTokenLists:T}=await import("././tokens.cjs"),H=await T(),P=Object.values(H).flatMap((u)=>u.tokens);if("identifier"in A)return P.find((u)=>u.identifier===A.identifier)?.identifier;let L=A.contract.toLowerCase();for(let u of P){let{chain:F,symbol:n}=p(u.identifier);if(F!==A.chain)continue;let{address:B}=a(n,F);if(B?.toLowerCase()===L)return u.identifier}return}var WT={};b(WT,{validateTNS:()=>VT,validateIdentifier:()=>VN});var bA=["TERRA",...M.get("chains")];function VN(A=""){let T=A.toUpperCase(),[H]=T.split(".");if(bA.includes(H))return!0;let[P]=T.split("/");if(bA.includes(P))return!0;throw new g({errorKey:"helpers_invalid_identifier",info:{identifier:A,message:`Invalid identifier: ${A}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}function VT(A){if(A.length>30)return!1;let T=/^[a-zA-Z0-9+_-]+$/g;return!!A.match(T)}var KT={};b(KT,{formatBigIntToSafeValue:()=>o,BigIntArithmetics:()=>K});var ON=require("ts-pattern"),NN=8,qT=10;function o({value:A,bigIntDecimal:T=NN,decimal:H=NN}){if(H===0)return A.toString();let P=A<0n,L=A.toString().substring(P?1:0),u=H-(L.length-1);if(u>0)L="0".repeat(u)+L;let F=L.length-H,n=L.slice(-H);if(Number.parseInt(n[T]||"0",10)>=5){let D=Number.parseInt(n[T-1]||"0",10);n=`${n.substring(0,T-1)}${D+1}`}else n=n.substring(0,T);return`${P?"-":""}${L.slice(0,F)}.${n}`.replace(/\.?0*$/,"")}class K{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(A,T){return new K({decimal:T,value:o({bigIntDecimal:T,decimal:T,value:A})})}static shiftDecimals({value:A,from:T,to:H}){return K.fromBigInt(A.getBaseValue("bigint")*c(H)/c(T),H)}constructor(A){let T=WN(A),H=typeof A==="object";this.decimal=H?A.decimal:void 0,this.decimalMultiplier=H&&"decimalMultiplier"in A?A.decimalMultiplier:c(Math.max(zA(QN(T)),this.decimal||0)),this.#P(T)}set(A){return new this.constructor({decimal:this.decimal,identifier:this.toString?.({includeSynthProtocol:!0}),value:A})}add(...A){return this.#A("add",...A)}sub(...A){return this.#A("sub",...A)}mul(...A){return this.#A("mul",...A)}div(...A){return this.#A("div",...A)}gt(A){return this.#N("gt",A)}gte(A){return this.#N("gte",A)}lt(A){return this.#N("lt",A)}lte(A){return this.#N("lte",A)}eqValue(A){return this.#N("eqValue",A)}getValue(A,T){let H=nN(this.decimalMultiplier),P=T!==void 0?T:this.decimal,L=P!==void 0?P:H;if(P!==void 0&&P<H){if(this.formatBigIntToSafeValue(this.bigIntValue,P)==="0"&&this.bigIntValue!==0n)L=H}let u=this.formatBigIntToSafeValue(this.bigIntValue,L);return ON.match(A).with("number",()=>Number(u)).with("string",()=>u).with("bigint",()=>{return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}).otherwise(()=>u)}getBaseValue(A,T){let H=this.decimalMultiplier/c(T||this.decimal||NN),P=kT(this.bigIntValue,H);return ON.match(A).with("number",()=>Number(P)).with("string",()=>P.toString()).otherwise(()=>P)}getBigIntValue(A,T){if(!T&&typeof A==="object")return A.bigIntValue;let H=WN(A),P=QN(H);if(P==="0"||P==="undefined")return 0n;return this.#H(P,T)}toSignificant(A=6){let T=this.getValue("string"),[H="",P=""]=T.split("."),L=Number.parseInt(H,10)>0;if((L?H.length+P.length:P.length)<=A)return T;if(H.length>=A)return H.slice(0,A).padEnd(H.length,"0");if(L)return`${H}.${P.slice(0,A-H.length)}`;let F=Number.parseInt(P,10).toString(),n=F.slice(0,A),B=P.length-F.length;return`0.${n.padStart(B+n.length,"0")}`}toFixed(A=6){let T=this.getValue("string"),H=T.startsWith("-"),[P="0",L=""]=(H?T.slice(1):T).split("."),u=P==="0"&&Number.parseInt(L.slice(0,A),10)===0,F=H&&!u?"-":"";if(A===0){if(P==="0"&&!L)return"0";return L&&Number.parseInt(L[0]||"0",10)>=5?`${F}${BigInt(P)+1n}.0`:`${F}${P}.0`}if(!L)return`${F}${P}.${"0".repeat(A)}`;let n=L[A];if(!(n&&Number.parseInt(n,10)>=5))return`${F}${P}.${L.slice(0,A).padEnd(A,"0")}`;let D=BigInt(L.slice(0,A).padEnd(A,"0"))+1n,X=10n**BigInt(A);if(D>=X)return`${F}${BigInt(P)+1n}.${"0".repeat(A)}`;return`${F}${P}.${D.toString().padStart(A,"0")}`}toAbbreviation(A=2){let T=this.getValue("string"),H=Number(T),P=["","K","M","B","T","Q","Qi","S"],L=Math.floor(Math.log10(Math.abs(H))/3);if(L===0||!P[L])return T;return`${(H/10**(L*3)).toFixed(A)}${P[L]}`}toCurrency(A="$",{currencyPosition:T="start",decimal:H=2,decimalSeparator:P=".",thousandSeparator:L=",",trimTrailingZeros:u=!0}={}){let F=this.toFixed(H),n=T==="end",[B="0",D=""]=F.split("."),X=B.replace(/\B(?=(\d{3})+(?!\d))/g,L),_=D&&Number.parseInt(D,10)>0,v=_?`${X}${P}${D}`:X,q=v.length<100&&u&&_?v.replace(/\.?0*$/,""):v;return n?`${q}${A}`:`${A}${q}`}formatBigIntToSafeValue(A,T){let H=T||this.decimal||NN,P=Math.max(H,nN(this.decimalMultiplier));return o({bigIntDecimal:H,decimal:P,value:A})}#A(A,...T){let H=this.#T(this,...T),P=nN(this.decimalMultiplier),u=Math.max(H,P)+qT,F=c(u),n=T.reduce((D,X)=>{let _=this.getBigIntValue(X,u);return ON.match(A).with("add",()=>D+_).with("sub",()=>D-_).with("mul",()=>D*_/F).with("div",()=>{if(_===0n)throw RangeError("Division by zero");return D*F/_}).otherwise(()=>D)},this.bigIntValue*F/this.decimalMultiplier),B=o({bigIntDecimal:u,decimal:u,value:n});return new this.constructor({decimal:this.decimal,decimalMultiplier:c(u),identifier:this.toString(),value:B})}#N(A,...T){let H=this.#T(this,...T),P=this.getBigIntValue(T[0]||"0",H),L=this.getBigIntValue(this,H);return ON.match(A).with("gt",()=>L>P).with("gte",()=>L>=P).with("lt",()=>L<P).with("lte",()=>L<=P).with("eqValue",()=>L===P).otherwise(()=>!1)}#P(A){let T=QN(A)||"0";this.bigIntValue=this.#H(T)}#T(...A){let T=A.map((H)=>{return typeof H==="object"?H.decimal||nN(H.decimalMultiplier):zA(QN(H))}).filter(Boolean);return Math.max(...T,NN)}#H(A,T){let H=T?c(T):this.decimalMultiplier,P=nN(H),[L="",u=""]=A.split(".");return BigInt(`${L}${u.padEnd(P,"0")}`)}}var mT=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function QN(A){let H=`${typeof A==="number"?mT.format(A):WN(A)}`.replaceAll(",",".").split(".");return H.length>1?`${H.slice(0,-1).join("")}.${H.at(-1)}`:H[0]||"0"}function zA(A){let T=A.split(".")[1]?.length||0;return Math.max(T,NN)}function WN(A){return typeof A==="object"?"getValue"in A?A.getValue("string"):A.value:A}function kT(A,T){if(T===0n)throw Error("Cannot divide by zero");let H=T/2n;return A>=0n&&T>=0n||A<0n&&T<0n?(A+H)/T:(A-H)/T}function c(A){return 10n**BigInt(A)}function nN(A){return Math.log10(Number.parseFloat(A.toString()))}var y=[G.Chain.HyperCore,G.Chain.Near,G.Chain.Ripple,G.Chain.Solana,G.Chain.Sui,G.Chain.Ton,G.Chain.Tron],kN=[G.Chain.THORChain,G.Chain.Maya],AN=new Map,xN=new Map,TN=new Map,pT=3600000;function oT(A){let T=TN.get(A);if(T?.timestamp&&Date.now()-T.timestamp>pT){TN.delete(A);return}return T}function yT(A,T){if(TN.size>1000){let H=TN.keys().next().value;if(H)TN.delete(H)}TN.set(A,{...T,timestamp:Date.now()})}class J extends K{address;chain;isGasAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:A,decimal:T,tax:H,chain:P,symbol:L,identifier:u}){super(typeof A==="object"?A:{decimal:T,value:A});let F=JA(u||`${P}.${L}`);this.type=EN(F),this.tax=H,this.chain=F.chain,this.ticker=F.ticker,this.symbol=F.symbol,this.address=F.address,this.isSynthetic=F.isSynthetic,this.isTradeAsset=F.isTradeAsset,this.isGasAsset=F.isGasAsset,this.chainId=G.getChainConfig(F.chain).chainId}toString({includeSynthProtocol:A}={}){return(this.isSynthetic||this.isTradeAsset)&&!A?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 A=this.symbol.replace(/\./g,"__");return`${this.chain}.${A}`}getIconUrl(){return AN.get(this.toString())?.logoURI}eqAsset({chain:A,symbol:T}){return this.chain===A&&this.symbol===T}eq(A){return this.eqAsset(A)&&this.eqValue(A)}static fromUrl(A,T=0){let H=A.indexOf(".");if(H===-1)throw new g({errorKey:"helpers_invalid_asset_url",info:{urlAsset:A}});let P=A.slice(0,H),L=A.slice(H+1),u=wN.match({chain:P,rest:L}).when(({rest:F})=>F.includes(".."),({chain:F,rest:n})=>`${F}.${n.replace(/\.\./g,"~")}`).when(({chain:F,rest:n})=>kN.includes(F)&&n.includes("."),({chain:F,rest:n})=>`${F}.${n.replace(/\./g,"/")}`).otherwise(({chain:F,rest:n})=>`${F}.${n.replace(/__/g,".")}`);return J.from({asset:u,value:T})}static from({value:A=0,fromBaseDecimal:T,asyncTokenLookup:H,...P}){let L=A instanceof K?A.getValue("string"):A,u=cT(P),F=!u.startsWith(G.Chain.Sui)&&u.includes(":");if(H&&F){let[uN,i]=u.split(":");return dT({address:i,chain:uN,fromBaseDecimal:T,parsedValue:L})}let n=F?u.split(":").join(".UNKNOWN-"):u,{identifier:B,decimal:D}=IN(n),{chain:X,isSynthetic:_,isTradeAsset:v,address:U}=JA(B),{baseDecimal:q}=G.getChainConfig(X),E=AN.get(y.includes(X)?B:B.toUpperCase());if(!E&&H&&!_&&!v)return(async()=>{let{ticker:uN}=p(B),i=await ZA({address:U,chain:X,ticker:uN});return mN({decimal:i.decimals,identifier:i.identifier,value:T?HN(BigInt(L),T):L})})();let Q=E?.decimal||D;d({condition:!Q&&!H,id:`assetValue_static_decimal_not_found_${X}`,warning:`Couldn't find static decimal for one or more tokens on ${X} (Using default ${q} 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:RN,identifier:S,tax:gN}=E||{decimal:Q||q,identifier:B},GN=T?HN(BigInt(L),T):HN(L,RN);return _||v?CT(S,GN):mN({decimal:RN,identifier:S,tax:gN,value:GN})}static async loadStaticAssets(A){let{loadTokenLists:T}=await import("@swapkit/tokens"),H=await T(A);for(let{tokens:P}of Object.values(H))for(let L of P){let{identifier:u}=L,{chain:F,symbol:n}=p(u),{address:B}=a(n,F),{baseDecimal:D}=G.getChainConfig(F),X=y.includes(F)?u:u.toUpperCase(),_="decimals"in L&&L.decimals!==void 0?L.decimals:D,v="logoURI"in L&&L.logoURI?L.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${u.toLowerCase()}.png`,U={decimal:_,identifier:u,logoURI:v,tax:"tax"in L?L.tax:void 0};if(AN.set(X,U),B){let q=y.includes(F)?`${F}:${B}`:`${F}:${B.toUpperCase()}`;xN.set(q,u)}}return!0}static setStaticAssets(A){AN.clear(),xN.clear();for(let[T,H]of A.entries()){let{identifier:P}=H,{chain:L,symbol:u}=p(P),{address:F}=a(u,L),{baseDecimal:n}=G.getChainConfig(L),B=H.chain??L,D=H.address??F,X=y.includes(B)?P:P.toUpperCase(),_=H.decimals??H.decimal??n,v=H.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${P.toLowerCase()}.png`,U={decimal:_,identifier:X,logoURI:v,tax:H.tax};if(AN.set(X,U),D){let q=y.includes(B)?`${B}:${D}`:`${B}:${D.toUpperCase()}`;xN.set(q,P)}}return!0}static get staticAssets(){return AN}}function fT(A){let T=J.from({chain:A});return wN.match(A).with(G.Chain.Bitcoin,G.Chain.Litecoin,G.Chain.BitcoinCash,G.Chain.Dash,()=>T.set(0.00010001)).with(G.Chain.Dogecoin,()=>T.set(1.00000001)).with(G.Chain.Avalanche,G.Chain.Ethereum,G.Chain.Arbitrum,G.Chain.BinanceSmartChain,()=>T.set(0.00000001)).with(G.Chain.THORChain,G.Chain.Maya,()=>T.set(0)).with(G.Chain.Cosmos,G.Chain.Kujira,()=>T.set(0.000001)).otherwise(()=>T.set(0.00000001))}async function ZA({chain:A,address:T,ticker:H}){let L=y.includes(A)?`${A}:${T||H}`:`${A}:${T||H}`.toUpperCase(),u=oT(L);if(u)return u;if(!T){let{baseDecimal:B}=G.getChainConfig(A);return{decimals:B,identifier:`${A}.${H||"UNKNOWN"}`}}let F=await vN({address:T,chain:A}),n=`${A}.${F.ticker||H||"UNKNOWN"}-${T}`;return d({condition:!!(!F.ticker&&H),id:`async_token_lookup_failed_${A}_${T}`,warning:`Could not fetch token metadata for ${A}:${T} from chain. Using user-provided ticker (${H}) with baseDecimal (${F.decimals}).`}),F.ticker&&yT(L,{decimals:F.decimals,identifier:n}),{decimals:F.decimals,identifier:n}}function mN({identifier:A,decimal:T,value:H,tax:P}){return VN(A),new J({decimal:T,identifier:A,tax:P,value:HN(H,T)})}function CT(A,T=0){let H=A.includes(".")?A.split(".")?.[0]?.toUpperCase():void 0,P=H?kN.includes(H):!1,L=A.slice(0,14).includes("~")?"~":"/",[u,F]=P?A.split(".").slice(1).join().split(L):A.split(L);if(!(u&&F))throw new g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:A}});return new J({decimal:8,identifier:`${H||G.Chain.THORChain}.${u}${L}${F}`,value:HN(T,8)})}async function dT({address:A,chain:T,fromBaseDecimal:H,parsedValue:P}){let{decimals:L,identifier:u}=await ZA({address:A,chain:T}),F=H?HN(BigInt(P),H):P;return mN({decimal:L,identifier:u,value:F})}function HN(A,T){return typeof A==="bigint"?o({bigIntDecimal:T,decimal:T,value:A}):A}function hT(A){let T=wN.match(A).when((H)=>("chain"in H)&&H.chain!==void 0,({chain:H})=>H).otherwise((H)=>{let P=p(H.asset);return P.synth?G.Chain.THORChain:P.chain});if(!G.AllChains.includes(T.toUpperCase())){let H="asset"in A?A.asset:T;throw new g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:H,message:`Unsupported chain "${T}" - use the AssetValue constructor directly`}})}}function cT(A){if(hT(A),"chain"in A){let{chain:L,address:u}=A;if(u){let F=y.includes(L)?`${L}:${u}`:`${L}:${u.toUpperCase()}`,n=xN.get(F);if(n)return n;return F}return L}let{chain:T,symbol:H}=p(A.asset);return EN({chain:T,symbol:H})==="Native"?T:A.asset}function rT(A,T,H){let P=A.split("."),L=P[0]?.toUpperCase(),u=kN.includes(L),F=H?"~":"/",[n,B=""]=u?P.slice(1).join(".").split(F):A.split(F);if(!(n&&B))throw new g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:A}});let{ticker:D,address:X}=jA({chain:n,symbol:B}),_=`${n}${F}${B}`;return{address:X,chain:L,isGasAsset:!1,isSynthetic:T,isTradeAsset:H,symbol:_,ticker:D}}function lT(A){let T=A.indexOf("."),H=(T===-1?A:A.slice(0,T)).toUpperCase(),P=T===-1?A:A.slice(T+1),{address:L,ticker:u}=jA({chain:H,symbol:P}),F;try{F=L&&G.EVMChains.includes(H)&&qN.getAddress(L)?qN.getAddress(L):L}catch{F=L}let n=F?`${u}-${F}`:P;return{address:F,chain:H,isGasAsset:FN({chain:H,symbol:P}),isSynthetic:!1,isTradeAsset:!1,symbol:n,ticker:u}}function JA(A){let T=A.slice(0,14),H=T.includes("/"),P=T.includes("~");if(H||P)return rT(A,H,P);return lT(A)}function jA({symbol:A,chain:T}){let{ticker:H,address:P}=a(A,T);return{address:P&&!y.includes(T)?P.toLowerCase():P,ticker:H}}var sT={};b(sT,{SwapKitNumber:()=>BN});class BN extends K{eq(A){return this.eqValue(A)}static fromBigInt(A,T){return new BN({decimal:T,value:o({bigIntDecimal:T,decimal:T,value:A})})}}function vA(A=!0){return A?"https://midgard.ninerealms.com":"https://midgard.mayachain.info"}function eT(A=!0){let T=vA(A);return A?`${T}/v2/thorname`:`${T}/v2/mayaname`}function aT(A){return function(H){let P=H?`?status=${H}`:"";return O.get(`${A}/v2/pools${P}`)}}function NH(A){return function(H){return O.get(`${A}/v2/pool/${H}`)}}function AH(A){return function(H,P){let L=P?`?period=${P}`:"";return O.get(`${A}/v2/pool/${H}/stats${L}`)}}function TH(A){return function(H,P){let L=new URLSearchParams;if(P?.interval)L.append("interval",P.interval);if(P?.count)L.append("count",P.count.toString());if(P?.from)L.append("from",P.from.toString());if(P?.to)L.append("to",P.to.toString());let u=L.toString()?`?${L.toString()}`:"";return O.get(`${A}/v2/history/depths/${H}${u}`)}}function HH(A){return function(){return O.get(`${A}/v2/network`)}}function PH(A){return function(){return O.get(`${A}/v2/health`)}}function LH(A){return function(){return O.get(`${A}/v2/nodes`)}}function RH(A){return function(H){return O.get(`${A}/v2/node/${H}`)}}function uH(A){return function(){return O.get(`${A}/v2/mimir/votes`)}}function FH(A){return function(){return O.get(`${A}/v2/mimir`)}}function IH(A){return function(){return O.get(`${A}/v2/constants`)}}function nH(A){return function(){return O.get(`${A}/v2/stats`)}}function OH(A){return function(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 L=P.toString()?`?${P.toString()}`:"";return O.get(`${A}/v2/history/earnings${L}`)}}function BH(A){return function(H,P){let L=new URLSearchParams;if(P?.interval)L.append("interval",P.interval);if(P?.count)L.append("count",P.count.toString());if(P?.from)L.append("from",P.from.toString());if(P?.to)L.append("to",P.to.toString());let u=L.toString()?`?${L.toString()}`:"",F=H?`/swaps/${H}`:"/swaps";return O.get(`${A}/v2/history${F}${u}`)}}function $H(A){return function(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 L=P.toString()?`?${P.toString()}`:"";return O.get(`${A}/v2/history/tvl${L}`)}}function gH(A){if(!A)return"";let T=new URLSearchParams,H=(P,L)=>{if(L!==void 0)T.append(P,typeof L==="number"?L.toString():L)};return H("address",A.address),H("txid",A.txid),H("asset",A.asset),H("type",A.type),H("affiliate",A.affiliate),H("limit",A.limit),H("offset",A.offset),T.toString()?`?${T.toString()}`:""}function GH(A){return function(H){let P=gH(H);return O.get(`${A}/v2/actions${P}`)}}function _H(A){return function(H){return O.get(`${A}/v2/member/${H}`)}}function tH(A){return function(H){let P=H?`/${H}`:"";return O.get(`${A}/v2/members${P}`)}}function DH(A){return function(H,P){let L=P?`&asset=${P}`:"";return O.get(`${A}/v2/saver/${H}${L?`?${L.substring(1)}`:""}`)}}function YH(A){return function(H){return O.get(`${A}/v2/savers/${H}`)}}function UH(A){return function(H,P){let L=new URLSearchParams;if(P?.interval)L.append("interval",P.interval);if(P?.count)L.append("count",P.count.toString());if(P?.from)L.append("from",P.from.toString());if(P?.to)L.append("to",P.to.toString());let u=L.toString()?`?${L.toString()}`:"",F=H?`/savers/${H}`:"/savers";return O.get(`${A}/v2/history${F}${u}`)}}function SH(A){return function(H){return O.get(`${A}/v2/balance/${H}`)}}function MH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return;throw L};return await O.get(`${A}/lookup/${H}`,{onError:P,retry:{maxRetries:1}})}}function XH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return[];throw L};return await O.get(`${A}/rlookup/${H}`,{onError:P,retry:{maxRetries:1}})}}function EH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return[];throw L};return await O.get(`${A}/owner/${H}`,{onError:P,retry:{maxRetries:1}})}}function PN({asset:A,value:T}){return J.from({asset:A,fromBaseDecimal:r.getChainConfig(r.Chain.THORChain).baseDecimal,value:T})}function QH({liquidityPositionGetter:A,isThorchain:T}){return async function(P){let L=await A(P),u=T?"rune":"cacao";return L.pools.map((F)=>({[`${u}Pending`]:PN({asset:"THOR.RUNE",value:F.runePending}),[`${u}RegisteredAddress`]:F.runeAddress,[`${u}Withdrawn`]:PN({asset:"THOR.RUNE",value:F.runeWithdrawn}),[u]:PN({asset:"THOR.RUNE",value:F.runeAdded}),asset:PN({asset:F.pool,value:F.assetAdded}),assetPending:PN({asset:F.pool,value:F.assetPending}),assetRegisteredAddress:F.assetAddress,assetWithdrawn:PN({asset:F.pool,value:F.assetWithdrawn}),dateFirstAdded:F.dateFirstAdded,dateLastAdded:F.dateLastAdded,poolShare:new BN(F.liquidityUnits).div(F.pool)}))}}function VA(A){let T=A===r.Chain.THORChain,H=vA(T),P=eT(T),L=_H(H);return{getActions:GH(H),getBalance:SH(H),getConstants:IH(H),getEarningsHistory:OH(H),getHealth:PH(H),getLiquidityPosition:QH({isThorchain:T,liquidityPositionGetter:L}),getLiquidityPositionRaw:L,getMembers:tH(H),getMimir:FH(H),getMimirVotes:uH(H),getNameDetails:MH(P),getNamesByAddress:XH(P),getNamesByOwner:EH(P),getNetworkInfo:HH(H),getNode:RH(H),getNodes:LH(H),getPool:NH(H),getPoolDepthHistory:TH(H),getPoolStats:AH(H),getPools:aT(H),getSaverDetails:DH(H),getSavers:YH(H),getSaversHistory:UH(H),getStats:nH(H),getSwapHistory:BH(H),getTVLHistory:$H(H)}}var WA=VA(r.Chain.THORChain),qA=VA(r.Chain.Maya);var nA={};b(nA,{getTrackerDetails:()=>RP,getTokenListProviders:()=>OP,getTokenList:()=>BP,getTokenApproval:()=>nP,getSwapTo:()=>UP,getSwapQuote:()=>uP,getRouteWithTx:()=>FP,getPrice:()=>$P,getNearDepositChannel:()=>_P,getGasRate:()=>gP,getChainflipDepositChannel:()=>GP,getChainBalance:()=>IP,SKRequestClient:()=>j});var iA=require("@swapkit/types"),f=require("ts-pattern");var xH={};b(xH,{signWidgetRequest:()=>KN});async function KN(A,T,H){let P=`${T}:${H}`,L=new TextEncoder,u=await crypto.subtle.importKey("raw",L.encode(A),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),F=await crypto.subtle.sign("HMAC",u,L.encode(P));return Array.from(new Uint8Array(F)).map((n)=>n.toString(16).padStart(2,"0")).join("")}var m=require("@swapkit/types"),N=require("zod/v4");var oN;((P)=>{P.CHEAPEST="CHEAPEST";P.FASTEST="FASTEST";P.RECOMMENDED="RECOMMENDED"})(oN||={});var $N;((L)=>{L.PSBT="PSBT";L.EVM="EVM";L.COSMOS="COSMOS";L.RADIX="RADIX"})($N||={});var yN;((Q)=>{Q.approve="approve";Q.claim="claim";Q.deposit="deposit";Q.donate="donate";Q.lending="lending";Q.lp_action="lp_action";Q.native_contract_call="native_contract_call";Q.native_send="native_send";Q.stake="stake";Q.streaming_swap="streaming_swap";Q.swap="swap";Q.thorname_action="thorname_action";Q.token_contract_call="token_contract_call";Q.token_transfer="token_transfer";Q.unknown="unknown";Q.unstake="unstake"})(yN||={});var fN;((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"})(fN||={});var CN;((n)=>{n.unknown="unknown";n.not_started="not_started";n.pending="pending";n.swapping="swapping";n.completed="completed";n.refunded="refunded";n.failed="failed"})(CN||={});var dN;((E)=>{E.not_started="not_started";E.starting="starting";E.broadcasted="broadcasted";E.mempool="mempool";E.inbound="inbound";E.outbound="outbound";E.swapping="swapping";E.completed="completed";E.refunded="refunded";E.partially_refunded="partially_refunded";E.dropped="dropped";E.reverted="reverted";E.replaced="replaced";E.retries_exceeded="retries_exceeded";E.parsing_error="parsing_error"})(dN||={});var wH=N.object({address:N.optional(N.string()),chain:N.z.enum(m.Chain).optional(),chainId:N.z.enum(m.ChainId),coingeckoId:N.optional(N.string()),decimals:N.coerce.number(),extensions:N.optional(N.z.looseObject({})),identifier:N.string(),logoURI:N.optional(N.string()),name:N.optional(N.string()),shortCode:N.optional(N.string()),symbol:N.optional(N.string()),ticker:N.string()}),bH=N.z.object({block:N.z.optional(N.z.number().describe("Block number. Required for Polkadot chain. e.g. `123456`")),chainId:N.z.optional(N.z.string().describe("ChainId for the hash. e.g. `thorchain-1`")),depositChannelId:N.z.optional(N.z.string().describe("Deposit channel ID, required for Chainflip if tx was broadcasted without wallet connection")),hash:N.z.optional(N.z.string().describe("Hash for the first transaction broadcasted by the end user. e.g. `88D1819378ECD09E5284C54937CDC1E99B52F253C007617A02DD1200710CE677`"))}).refine((A)=>A.hash&&A.chainId||A.depositChannelId,{message:"Either `hash` and `chainId` or `depositChannelId` must be provided"}),zH=N.z.object({forceUpdate:N.z.string().toLowerCase().transform((A)=>A==="true").pipe(N.z.boolean()).optional()}),JH=N.object({error:N.string(),message:N.string()}),l=N.object({address:N.optional(N.string()),chain:N.z.enum(m.Chain),decimal:N.optional(N.number()),isGasAsset:N.boolean(),isSynthetic:N.boolean(),symbol:N.string(),tax:N.optional(N.object({buy:N.number(),sell:N.number()})),ticker:N.string()}),hN=N.object({id:N.string(),market_cap:N.number(),name:N.string(),price_change_24h_usd:N.number(),price_change_percentage_24h_usd:N.number(),sparkline_in_7d:N.array(N.number()),timestamp:N.string(),total_volume:N.number()}).partial(),ZH=N.object({cg:N.optional(hN),identifier:N.string(),price_usd:N.number(),provider:N.string(),timestamp:N.number()}),cN=N.array(N.object({cg:N.optional(hN),identifier:N.string(),price_usd:N.number(),provider:N.string(),timestamp:N.number()}).partial()),jH=N.object({affiliate:N.optional(N.string().describe("Affiliate thorname")),affiliateFee:N.optional(N.number().describe("Affiliate fee in basis points").refine((A)=>A===Math.floor(A)&&A>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:N.optional(N.boolean().describe("Allow smart contract as recipient")),allowSmartContractSender:N.optional(N.boolean().describe("Allow smart contract as sender")),buyAsset:N.string().describe("Asset to buy"),cfBoost:N.optional(N.boolean().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:N.optional(N.string().describe("Address to send asset to")),disableSecurityChecks:N.optional(N.boolean().describe("Disable security checks")),includeTx:N.optional(N.boolean().describe("Set to true to include an transaction object (EVM only)")),providers:N.optional(N.array(N.string().describe("List of providers to use").refine((A)=>w[A]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:N.optional(N.string().describe("Referrer address (referral program)")),sellAmount:N.string().describe("Amount of asset to sell").refine((A)=>+A>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:N.string().describe("Asset to sell"),slippage:N.optional(N.number().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:N.optional(N.string().describe("Address to send asset from"))}).refine((A)=>A.sellAsset!==A.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),vH=N.object({metadata:N.boolean(),tokens:N.array(N.object({identifier:N.string()}))}),rN=N.object({destinationAddress:N.string()}),KA=rN.extend({affiliateFees:N.array(N.object({brokerAddress:N.string(),feeBps:N.number()})).optional(),brokerCommissionBps:N.number().optional(),buyAsset:N.object({asset:N.string(),chain:N.string()}),channelMetadata:N.object({cfParameters:N.string().optional(),gasBudget:N.string().optional(),message:N.string().optional()}).optional(),dcaParameters:N.object({chunkInterval:N.number().optional(),numberOfChunks:N.number().optional()}).optional(),maxBoostFeeBps:N.number().optional(),refundParameters:N.object({minPrice:N.string().optional(),refundAddress:N.string().optional(),retryDuration:N.number().optional()}).optional(),sellAsset:N.object({asset:N.string(),chain:N.string()})}),lN=N.object({channelId:N.string(),depositAddress:N.string()}),pN=rN.extend({affiliateFees:N.object({feeBps:N.number(),nearId:N.string()}).optional(),buyAsset:N.string(),sellAmount:N.string(),sellAsset:N.string(),slippage:N.coerce.number(),sourceAddress:N.string()}),mA=N.object({amountIn:N.string(),amountInFormatted:N.string(),amountInUsd:N.string(),amountOut:N.string(),amountOutFormatted:N.string(),amountOutUsd:N.string(),deadline:N.string().optional(),minAmountIn:N.string(),minAmountOut:N.string(),timeEstimate:N.number().optional(),timeWhenInactive:N.string().optional()}),VH=mA.extend({depositAddress:N.string(),quote:mA,signature:N.string(),timestamp:N.string(),tx:N.unknown()}),iN=N.object({buyAsset:N.string(),buyAssetAmount:N.string(),buyAssetAmountMaxSlippage:N.string(),deadline:N.string().optional(),depositAddress:N.string(),depositAmount:N.string(),depositAsset:N.string(),tx:N.unknown()}),WH=N.object({evmCalldata:N.z.optional(N.z.string()),intentHash:N.z.optional(N.z.string()),logs:N.z.optional(N.z.unknown()),manifest:N.z.optional(N.z.unknown()),memo:N.z.optional(N.z.string()),spender:N.z.optional(N.z.string()),thorname:N.z.optional(N.z.string())}),qH=N.object({currentStage:N.string(),inboundConfirmation:N.number(),inboundObservation:N.number(),outboundDelay:N.number(),outboundObservation:N.number(),streamingSwap:N.number()}),mH=N.object({count:N.optional(N.number()),interval:N.optional(N.number()),quantity:N.optional(N.number()),subSwapsMap:N.optional(N.array(N.number()))}),kH=N.z.object({currentLegIndex:N.z.optional(N.z.number()),estimatedTimeToComplete:N.z.number(),estimates:N.z.optional(qH),providerDetails:N.z.optional(N.z.object({streamingDetails:N.z.optional(mH)}))}),KH=N.object({affiliate:N.optional(l),liquidity:N.optional(l),network:N.optional(l),protocol:N.optional(l),tax:N.optional(l)}),pH=N.object({affiliate:N.string(),bps:N.string(),isReferrer:N.boolean()}),oH=N.object({affiliate:N.optional(N.string()),affiliateFees:N.optional(N.array(pH)),broadcastedAt:N.optional(N.number()),explorerUrl:N.optional(N.string()),fees:N.optional(KH),images:N.optional(N.object({chain:N.optional(N.string()),from:N.optional(N.string()),provider:N.optional(N.string()),to:N.optional(N.string())})),provider:N.optional(N.z.enum(w)),providerAction:N.z.optional(N.z.enum(fN)),quoteId:N.optional(N.string()),wallet:N.optional(N.string())}),LN=N.z.object({block:N.z.number(),chainId:N.z.enum(m.ChainId),finalAddress:N.z.optional(N.z.string()),finalAsset:N.z.optional(l),finalisedAt:N.z.number(),fromAddress:N.z.string(),fromAmount:N.z.string(),fromAsset:N.z.string(),hash:N.z.string(),meta:N.z.optional(oH),payload:N.z.optional(WH),status:N.z.enum(CN),toAddress:N.z.string(),toAmount:N.z.string(),toAsset:N.z.string(),trackingStatus:N.z.optional(N.z.enum(dN)),transient:N.z.optional(kH),type:N.z.enum(yN)}),sN=LN.extend({legs:N.z.array(LN)}),yH=LN.extend({legs:N.array(LN)}),fH=LN.extend({legs:N.array(LN)}),bN=N.array(N.object({amount:N.string(),asset:N.string(),chain:N.string(),protocol:N.z.enum(w),type:N.z.enum(YN)})),zN=N.z.object({inbound:N.z.optional(N.z.number().describe("Time to receive inbound asset in seconds")),outbound:N.z.optional(N.z.number().describe("Time to receive outbound asset in seconds")),swap:N.z.optional(N.z.number().describe("Time to swap assets in seconds")),total:N.z.number().describe("Total time in seconds")}),eN=N.object({data:N.string().describe("Data to send"),from:N.string().describe("Address of the sender"),to:N.string().describe("Address of the recipient"),value:N.string().describe("Value to send")}),aN=N.z.object({raw_data:N.z.object({contract:N.z.any(),data:N.z.string().optional(),expiration:N.z.number(),fee_limit:N.z.number().optional(),ref_block_bytes:N.z.string(),ref_block_hash:N.z.string(),timestamp:N.z.number()}).passthrough(),raw_data_hex:N.z.string(),txID:N.z.string(),visible:N.z.boolean()}),pA=N.array(N.union([N.string(),N.number(),N.array(N.string()),N.object({from:N.string(),value:N.string()}).describe("Parameters to pass to the contract method")])),CH=N.object({approvalSpender:N.optional(N.string().describe("Address of the spender to approve")),approvalToken:N.optional(N.string().describe("Address of the token to approve spending of")),contractAddress:N.string().describe("Address of the contract to interact with"),contractMethod:N.string().describe("Name of the method to call"),contractParamNames:N.array(N.string().describe("Names of the parameters to pass to the contract method")),contractParams:pA}),dH=N.object({typeUrl:N.string("/types.MsgDeposit"),value:N.object({coins:N.array(N.object({amount:N.string(),asset:N.object({chain:N.string(),symbol:N.string(),synth:N.boolean(),ticker:N.string()})})),memo:N.string(),signer:N.string()})}),hH=N.object({typeUrl:N.string("/types.MsgSend"),value:N.object({amount:N.array(N.object({amount:N.string(),denom:N.string()})),fromAddress:N.string(),toAddress:N.string()})}),cH=N.object({typeUrl:N.string(),value:hH.or(dH)}),rH=N.object({amount:N.array(N.object({amount:N.string(),denom:N.string()})),gas:N.string()}),NA=N.object({accountNumber:N.number(),chainId:N.z.enum(m.ChainId),fee:rH,memo:N.string(),msgs:N.array(cH),sequence:N.number()}),oA=N.z.array(N.z.object({calldata:N.z.array(N.z.string()),contractAddress:N.z.string(),entrypoint:N.z.string()})),AA=N.z.array(N.z.object({address:N.z.string().describe("Destination address in friendly format"),amount:N.z.string().describe("Amount in nanotons"),payload:N.z.string().optional().describe("Base64 BOC of body cell"),stateInit:N.z.string().optional().describe("Base64 BOC of state init")})),yA=N.object({affiliate:N.string().describe("Affiliate address").optional(),affiliateFee:N.number().describe("Affiliate fee").optional(),buyAsset:N.string().describe("Asset to buy"),destinationAddress:N.string().describe("Destination address"),estimatedTime:zN.optional(),provider:N.z.enum(w),sellAsset:N.string().describe("Asset to sell"),slipPercentage:N.number().describe("Slippage as a percentage"),sourceAddress:N.string().describe("Source address")}),lH=yA.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),fA=N.object({asset:N.string().describe("Asset name"),image:N.string().describe("Asset image"),price:N.number().describe("Price in USD")}),CA=KA,TA=N.object({assets:N.optional(N.array(fA)),maxStreamingQuantity:N.number().optional(),referrer:N.string().optional(),streamingInterval:N.number().optional(),tags:N.array(N.z.enum(oN))}),HA=TA.extend({affiliate:N.optional(N.string()),affiliateFee:N.optional(N.string()),approvalAddress:N.optional(N.string().describe("Approval address for swap")),chainflip:CA.optional(),garden:pN.optional(),near:pN.optional(),priceImpact:N.optional(N.number().describe("Price impact")),referrer:N.optional(N.string()),txType:N.optional(N.z.enum($N))}),PA=N.array(N.object({code:N.z.enum(DN),display:N.string(),tooltip:N.string().optional()})),iH=N.object({buyAmount:N.string().describe("Buy amount"),buyAmountMaxSlippage:N.string().describe("Buy amount max slippage"),buyAsset:N.string().describe("Asset to buy"),fees:N.optional(bN),provider:N.z.enum(w),sellAmount:N.string().describe("Sell amount"),sellAsset:N.string().describe("Asset to sell")}),dA=N.object({buyAsset:N.string().describe("Asset to buy"),destinationAddress:N.optional(N.string().describe("Destination address")),estimatedTime:N.optional(zN),expectedBuyAmount:N.string().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:N.string().describe("Expected Buy amount max slippage"),expiration:N.optional(N.string().describe("Expiration")),fees:bN,inboundAddress:N.optional(N.string().describe("Inbound address")),legs:N.array(iH),memo:N.optional(N.string().describe("Memo")),meta:HA,providers:N.array(N.z.enum(w)),routeId:N.string().describe("Route ID"),sellAmount:N.string().describe("Sell amount"),sellAsset:N.string().describe("Asset to sell"),sourceAddress:N.optional(N.string().describe("Source address")),targetAddress:N.optional(N.string().describe("Target address")),totalSlippageBps:N.number().describe("Total slippage in bps"),tx:N.optional(N.union([eN,NA,aN,oA,AA,N.string()])),txType:N.optional(N.z.enum($N)),warnings:PA}),LA=N.object({error:N.optional(N.string().describe("Error message")),providerErrors:N.optional(N.array(N.object({errorCode:N.optional(N.z.enum(s)),message:N.optional(N.string()),provider:N.z.enum(w).optional()}))),quoteId:N.string().describe("Quote ID"),routes:N.array(dA)}),RA=N.z.object({chainId:N.z.enum(m.ChainId),createdAt:N.z.date(),id:N.z.number(),unit:N.z.string(),value:N.z.string()}),sH=N.z.array(RA),uA=N.z.union([RA,sH]),gL=N.array(N.object({chain:N.z.enum(m.Chain),decimal:N.number(),identifier:N.string(),symbol:N.string(),ticker:N.string(),value:N.string()})),eH=N.z.union([N.z.object({amount:N.z.string(),spender:N.z.string(),tokenIdentifier:N.z.string(),userWalletAddress:N.z.string()}),N.z.object({amount:N.z.string(),chainId:N.z.enum(m.ChainId),spender:N.z.string(),tokenContractAddress:N.z.string(),userWalletAddress:N.z.string()}),N.z.object({routeId:N.z.string()})]),aH=N.z.object({approvalTransaction:N.z.optional(N.z.object({data:N.z.string(),from:N.z.string(),gasLimit:N.z.optional(N.z.string()),gasPrice:N.z.optional(N.z.string()),to:N.z.string(),value:N.z.string()})),approvedAmount:N.z.string(),isApproved:N.z.boolean()}),hA=N.z.object({data:N.z.string().describe("Encoded approval call data"),from:N.z.string().describe("User wallet address"),gasLimit:N.z.string().optional().describe("Estimated gas limit"),gasPrice:N.z.string().optional().describe("Current gas price"),to:N.z.string().describe("Token contract address"),value:N.z.string().describe("ETH value (always '0' for approvals)")}),kA=N.z.object({buyAmount:N.z.string().describe("Buy amount"),buyAmountMaxSlippage:N.z.string().describe("Buy amount max slippage"),buyAsset:N.z.string().describe("Asset to buy"),expectedBuyAmount:N.z.string().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:N.z.string().describe("Expected Buy amount max slippage"),fees:bN,provider:N.z.enum(w),sellAmount:N.z.string().describe("Sell amount"),sellAsset:N.z.string().describe("Asset to sell")}),cA=kA.extend({estimatedTime:N.z.optional(zN),expiration:N.z.optional(N.z.string().describe("Expiration")),legs:N.z.array(kA),providers:N.z.array(N.z.enum(w)),routeId:N.z.string().describe("Route ID"),totalSlippageBps:N.z.number().describe("Total slippage in bps"),warnings:PA}).omit({provider:!0}),NP=N.z.object({method:N.z.string(),payload:N.z.optional(N.z.unknown()),url:N.z.string()}),AP=cA.extend({meta:TA,nextActions:N.z.optional(N.z.array(NP))}),TP=N.z.object({error:N.z.optional(N.z.string().describe("Error message")),providerErrors:N.z.optional(N.z.array(N.z.object({errorCode:N.z.optional(N.z.enum(s)),message:N.z.optional(N.z.string()),provider:N.z.enum(w).optional()}))),quoteId:N.z.string().describe("Quote ID"),routes:N.z.array(AP)}),HP=N.z.object({providers:N.z.array(N.z.enum(w)).optional().describe("Optional list of providers to query for trading pairs"),sellAsset:N.z.string().describe("Asset identifier to sell (e.g., 'BTC.BTC' or 'ETH.ETH')")}),rA=N.z.object({chain:N.z.enum(m.Chain).describe("Chain the asset is on"),identifier:N.z.string().describe("Asset identifier (e.g., 'ETH.USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')"),providers:N.z.array(N.z.enum(w)).describe("Providers that support this trading pair"),symbol:N.z.string().describe("Asset symbol"),ticker:N.z.string().describe("Asset ticker")}),PP=N.z.object({buyAssets:N.z.array(rA).describe("List of assets that can be swapped to"),sellAsset:N.z.string().describe("The input sell asset identifier")}),FA=cA.extend({destinationAddress:N.z.string().describe("Destination address"),inboundAddress:N.z.optional(N.z.string().describe("Inbound address")),memo:N.z.optional(N.z.string().describe("Memo to include in the transaction")),meta:HA,sourceAddress:N.z.string().describe("Source address"),targetAddress:N.z.optional(N.z.string().describe("Target address")),tx:N.optional(N.union([eN,NA,aN,AA,N.string()])),txType:N.z.optional(N.z.enum($N))}),lA=N.z.object({data:N.z.optional(N.z.record(N.z.string(),N.z.string().optional())),errorCode:N.z.enum(s),message:N.z.string().optional(),provider:N.z.enum(w).optional()}),LP=N.z.object({error:N.z.optional(N.z.string().describe("Error message")),providerErrors:N.z.optional(N.z.array(lA)),quoteId:N.z.string().describe("Quote ID"),routes:N.z.array(FA)}),IA=FA.extend({approvalTx:hA.optional().describe("Optional approval transaction if ERC-20 approval is required before swap"),swapId:N.z.string().describe("The unique swap ID for tracking")});var j=O.extend({dynamicHeader:async()=>{let A=M.get("widgetKey");if(A&&typeof window<"u"){let H=Math.floor(Date.now()/1000),P=window.location.origin;return{"X-Signature":await KN(A,P,H),"X-Timestamp":H.toString()}}let{swapKit:T}=M.get("apiKeys");return T?{"x-api-key":T}:{}}});async function RP(A){let T=await j.post(Z("/track"),{json:A});try{let H=sN.safeParse(T);if(!H.success)throw new g("api_v2_invalid_response",H.error);return H.data}catch(H){return T}}async function uP(A){let{getQuote:T}=M.get("endpoints");if(T)return T(A);let P=M.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",L=await j.post(Z(P),{json:A});if(L.error)throw new g("api_v2_server_error",{message:L.error});try{let u=LA.safeParse(L);if(!u.success)throw new g("api_v2_invalid_response",u.error);return u.data}catch{return L}}async function FP(A){let{getRouteWithTx:T}=M.get("endpoints");if(T)return T(A);let P=M.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",L=await j.post(Z(P),{json:A});try{let u=IA.safeParse(L);if(!u.success)throw new g("api_v2_invalid_response",u.error);return u.data}catch(u){return console.error(new g("api_v2_invalid_response",u)),L}}async function IP({chain:A,address:T,scamFilter:H=!0}){let{getBalance:P}=M.get("endpoints");if(P)return P({address:T,chain:A});let L=Z(`/balance?chain=${A}&address=${T}`),u=await j.get(L),F=Array.isArray(u)?u:[];return H?YP(F):F}function nP(A){let T=f.match(A).with({routeId:f.P.string,spender:f.P.string},({routeId:H,spender:P})=>Z(`/approve?routeId=${H}&sourceAddress=${P}`)).with({assetValue:f.P.instanceOf(J),spender:f.P.string,userWallet:f.P.string},({spender:H,userWallet:P,assetValue:L})=>Z(`/approve?tokenIdentifier=${L.toString()}&userWalletAddress=${P}&spender=${H}&amount=${L.getValue("string")}`)).exhaustive();return j.get(T)}function OP(){let A=Z("/providers");return j.get(A)}function BP(A){let T=Z(`/tokens?provider=${A}`);return j.get(T)}async function $P(A){let T=Z("/price"),H=await j.post(T,{json:A});try{let P=cN.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 gP(){let A=Z("/gas"),T=await j.get(A);try{let H=uA.safeParse(T);if(!H.success)throw new g("api_v2_invalid_response",H.error);return Array.isArray(H)?H:[H]}catch(H){throw new g("api_v2_invalid_response",H)}}async function GP(A){let{destinationAddress:T}=A;if(!T)throw new g("chainflip_broker_invalid_params");let H=M.get("integrations").chainflip?.brokerUrl||Z("/chainflip/broker/channel"),P=await j.post(H,{json:A});try{let L=lN.safeParse(P);if(!L.success)throw new g("api_v2_invalid_response",L.error);return L.data}catch(L){throw new g("api_v2_invalid_response",L)}}async function _P(A){let{destinationAddress:T}=A;if(!T)throw new g("chainflip_broker_invalid_params");let H=Z("/near/channel"),P=await j.post(H,{json:A});try{let L=iN.safeParse(P);if(!L.success)throw new g("api_v2_invalid_response",L.error);return L.data}catch(L){throw new g("api_v2_invalid_response",L)}}function Z(A){let{isDev:T,apiUrl:H,devApiUrl:P}=M.get("envs");return`${T?P:H}${A}`}function tP(A){let[T,H]=A.split(".");if(!iA.EVMChains.includes(T))return!0;let P=H.split("-"),L=P.length===1?void 0:P[P.length-1];return FN({chain:T,symbol:H})||!!L}var DP=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi");function YP(A){return A.filter((T)=>{return!DP.test(T.identifier)&&tP(T.identifier)})}async function UP(A){let{getSwapTo:T}=M.get("endpoints");if(T)return T(A);let H=new URLSearchParams({sellAsset:A.sellAsset});if(A.providers?.length)for(let F of A.providers)H.append("providers",F);let P=Z(`/swapTo?${H.toString()}`),L=await j.get(P);if(!Array.isArray(L))return{buyAssets:[],sellAsset:A.sellAsset};let u=[];for(let F of L)try{let n=J.from({asset:F});u.push({chain:n.chain,identifier:n.toString(),providers:[],symbol:n.symbol,ticker:n.ticker})}catch{}return{buyAssets:u,sellAsset:A.sellAsset}}var OA={};b(OA,{getThorchainQueue:()=>XP,getTcyStakers:()=>ZP,getTcyStaker:()=>JP,getTcyClaimers:()=>vP,getTcyClaimer:()=>jP,getTNSPreferredAsset:()=>wP,getTHORNodeTNSDetails:()=>sA,getRunePoolProviderInfo:()=>zP,getRunePoolInfo:()=>bP,getNodes:()=>EP,getMimirInfo:()=>QP,getLastBlock:()=>MP,getInboundAddresses:()=>xP});var C=require("@swapkit/types");function W(A){let{isStagenet:T}=M.get("envs");switch(A){case"mayachain":return`${T?C.StagenetMAYAConfig.nodeUrl:C.MAYAConfig.nodeUrl}/mayachain`;default:return`${T?C.StagenetTHORConfig.nodeUrl:C.THORConfig.nodeUrl}/thorchain`}}function SP(A){let T=A==="mayachain"?"mayaname":"thorname";return`${W(A)}/${T}`}function MP(A="thorchain"){return O.get(`${W(A)}/lastblock`)}function XP(A){return O.get(`${W(A)}/queue`)}function EP(A){return O.get(`${W(A)}/nodes`)}function QP(A){return O.get(`${W(A)}/mimir`)}function xP(A){return O.get(`${W(A)}/inbound_addresses`)}async function sA({type:A,name:T}){try{return await O.get(`${SP(A)}/${T}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:T,owner:"",preferred_asset:""}}}async function wP({type:A,tns:T}){let H=await sA({name:T,type:A});if(!H.preferred_asset||H.preferred_asset===".")return;return J.from({asset:H.preferred_asset,asyncTokenLookup:!0})}function bP(A){return O.get(`${W(A)}/runepool`)}function zP({type:A,thorAddress:T}){return O.get(`${W(A)}/rune_provider/${T}`)}function JP({type:A,address:T}){return O.get(`${W(A)}/tcy_staker/${T}`)}function ZP(A){return O.get(`${W(A)}/tcy_stakers`)}function jP({type:A,address:T}){return O.get(`${W(A)}/tcy_claimer/${T}`)}function vP(A){return O.get(`${W(A)}/tcy_claimers`)}var WP={...nA,mayachainMidgard:qA,thorchainMidgard:WA,thornode:OA};
@@ -0,0 +1,5 @@
1
+ var rA=Object.defineProperty;var lA=(N)=>N;function iA(N,A){this[N]=lA.bind(null,A)}var cN=(N,A)=>{for(var T in A)rA(N,T,{get:A[T],enumerable:!0,configurable:!0,set:iA.bind(A,T)})};var RN=((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 EN,getChainConfig as hT}from"@swapkit/types";import{AllChains as WT,Chain as E,EVMChains as qT,getChainConfig as ON}from"@swapkit/types";import{getAddress as FA}from"ethers";import{match as mN}from"ts-pattern";import{Chain as n,EVMChains as XT,getChainConfig as C,UTXOChains as ET}from"@swapkit/types";import{match as FN}from"ts-pattern";import{AllChains as lN,getChainConfig as HT,StagenetChain as rN,StagenetMAYAConfig as PT,StagenetTHORConfig as LT}from"@swapkit/types";import{createStore as RT}from"zustand/vanilla";import{AllChains as sA,getChainConfig as eA}from"@swapkit/types";var bP=sA.reduce((N,A)=>{return N[A]=eA(A).networkDerivationPath,N},{});var uN;((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"})(uN||={});var bN;((T)=>{T.highSlippage="highSlippage";T.highPriceImpact="highPriceImpact"})(bN||={});var j;((X)=>{X.CHAINFLIP="CHAINFLIP";X.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";X.JUPITER="JUPITER";X.MAYACHAIN="MAYACHAIN";X.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";X.ONEINCH="ONEINCH";X.PANCAKESWAP="PANCAKESWAP";X.SUSHISWAP_V2="SUSHISWAP_V2";X.THORCHAIN="THORCHAIN";X.THORCHAIN_STREAMING="THORCHAIN_STREAMING";X.TRADERJOE_V2="TRADERJOE_V2";X.UNISWAP_V2="UNISWAP_V2";X.UNISWAP_V3="UNISWAP_V3";X.NEAR="NEAR";X.GARDEN="GARDEN";X.OKX="OKX";X.HARBOR="HARBOR";X.FLASHNET="FLASHNET"})(j||={});var zN;((G)=>{G.LIQUIDITY="liquidity";G.NETWORK="network";G.INBOUND="inbound";G.OUTBOUND="outbound";G.AFFILIATE="affiliate";G.TAX="tax";G.PRIORITY="priority";G.SERVICE="service"})(zN||={});var aA;((H)=>{H.Average="average";H.Fast="fast";H.Fastest="fastest"})(aA||={});var NT;((T)=>{T.Approve="approve";T.CheckOnly="checkOnly"})(NT||={});var AT;((Y)=>{Y.NAME_REGISTER="~";Y.BOND="BOND";Y.DEPOSIT="+";Y.LEAVE="LEAVE";Y.UNBOND="UNBOND";Y.WITHDRAW="-";Y.RUNEPOOL_DEPOSIT="POOL+";Y.RUNEPOOL_WITHDRAW="POOL-";Y.CLAIM_TCY="tcy";Y.STAKE_TCY="tcy+";Y.UNSTAKE_TCY="tcy-"})(AT||={});import{Chain as t}from"@swapkit/types";var JN;((U)=>{U.BITGET="BITGET";U.BRAVE="BRAVE";U.COINBASE_MOBILE="COINBASE_MOBILE";U.COINBASE_WEB="COINBASE_WEB";U.COSMOSTATION="COSMOSTATION";U.CTRL="CTRL";U.EIP6963="EIP6963";U.EXODUS="EXODUS";U.KEEPKEY="KEEPKEY";U.KEEPKEY_BEX="KEEPKEY_BEX";U.KEPLR="KEPLR";U.KEYSTORE="KEYSTORE";U.LEAP="LEAP";U.LEDGER="LEDGER";U.METAMASK="METAMASK";U.OKX="OKX";U.OKX_MOBILE="OKX_MOBILE";U.ONEKEY="ONEKEY";U.PASSKEYS="PASSKEYS";U.PETRA="PETRA";U.PHANTOM="PHANTOM";U.POLKADOT_JS="POLKADOT_JS";U.RADIX_WALLET="RADIX_WALLET";U.TALISMAN="TALISMAN";U.TREZOR="TREZOR";U.TRONLINK="TRONLINK";U.TRUSTWALLET_WEB="TRUSTWALLET_WEB";U.VULTISIG="VULTISIG";U.WALLETCONNECT="WALLETCONNECT";U.WALLET_SELECTOR="WALLET_SELECTOR";U.XAMAN="XAMAN"})(JN||={});var TT;((H)=>{H[H.NoError=36864]="NoError";H[H.LockedDevice=21781]="LockedDevice";H[H.TC_NotFound=65535]="TC_NotFound"})(TT||={});var J=["BITGET","BRAVE","COINBASE_MOBILE","COINBASE_WEB","COSMOSTATION","CTRL","EIP6963","KEEPKEY","KEEPKEY_BEX","KEYSTORE","LEDGER","METAMASK","OKX","OKX_MOBILE","PASSKEYS","PHANTOM","TALISMAN","TREZOR","TRUSTWALLET_WEB","VULTISIG","WALLETCONNECT"],vP={[t.Arbitrum]:J,[t.Aurora]:J,[t.Avalanche]:J,[t.Base]:J,[t.Berachain]:J,[t.BinanceSmartChain]:J,[t.Botanix]:J,[t.Chainflip]:J,[t.Core]:J,[t.Corn]:J,[t.Cronos]:J,[t.Ethereum]:J,[t.Gnosis]:J,[t.Hyperevm]:J,[t.MegaETH]:J,[t.Monad]:J,[t.Optimism]:J,[t.Polygon]:J,[t.Sonic]:J,[t.Unichain]:J,[t.XLayer]:J,[t.Bitcoin]:["BITGET","KEYSTORE","OKX","ONEKEY","PASSKEYS","PHANTOM"],[t.BitcoinCash]:["KEYSTORE"],[t.Dash]:["KEYSTORE"],[t.Dogecoin]:["KEYSTORE"],[t.Litecoin]:["KEYSTORE"],[t.Zcash]:["KEYSTORE"],[t.Cosmos]:["COSMOSTATION","CTRL","KEPLR","KEYSTORE","LEAP"],[t.Kujira]:["COSMOSTATION","CTRL","KEPLR","KEYSTORE","LEAP"],[t.Maya]:["KEYSTORE"],[t.Noble]:["COSMOSTATION","CTRL","KEPLR","KEYSTORE","LEAP"],[t.THORChain]:["COSMOSTATION","KEPLR","KEYSTORE","LEAP"],[t.Aptos]:["BITGET","KEYSTORE","OKX","PETRA"],[t.Cardano]:["KEYSTORE"],[t.HyperCore]:["KEYSTORE"],[t.Near]:["KEYSTORE","LEDGER"],[t.Ripple]:["KEYSTORE","LEDGER"],[t.Solana]:["KEYSTORE","PASSKEYS","PHANTOM"],[t.Sui]:["KEYSTORE"],[t.Tron]:["KEYSTORE","LEDGER"],[t.Stellar]:["KEYSTORE"],[t.Starknet]:["KEYSTORE"]};var uT=lN.reduce((N,A)=>{if(!N.THOR_STAGENET)N[rN.Maya]=PT.rpcUrls,N[rN.THORChain]=LT.rpcUrls;return N[A]=HT(A).rpcUrls,N},{}),iN={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"}}},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:uT,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(JN),widgetKey:""},q=RT((N)=>({...iN,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},rpcUrls:{...T.rpcUrls,...A?.rpcUrls},v3SwapFlow:{...T.v3SwapFlow,...A?.v3SwapFlow},wallets:T.wallets.concat(A?.wallets||[]),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}})),setWidgetKey:(A)=>N({widgetKey:A})})),x={get:(N)=>q.getState()[N],getState:q.getState,reinitialize:()=>q.setState(iN),set:(N)=>q.getState().setConfig(N),setApiKey:(N,A)=>q.getState().setApiKey(N,A),setEndpoint:(N,A)=>q.getState().setEndpoint(N,A),setEnv:(N,A)=>q.getState().setEnv(N,A),setFeeMultipliers:(N)=>q.getState().setFeeMultipliers(N),setIntegrationConfig:(N,A)=>q.getState().setIntegrationConfig(N,A),setRequestOptions:(N)=>q.getState().setRequestOptions(N),setRpcUrl:(N,A)=>q.getState().setRpcUrl(N,A),setWidgetKey:(N)=>q.getState().setWidgetKey(N)};var FT={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_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_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 D extends Error{static ErrorCode=FT;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,D.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 IT=(N)=>new Promise((A)=>setTimeout(A,N)),nT=(N,{baseDelay:A,backoffMultiplier:T,maxDelay:H})=>Math.min(A*T**N,H);function OT(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 BT=async(N,A)=>{let T=await fetch(N,A),H;try{H=await T.json()}catch{if(!T.ok)throw new D({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 D({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 D({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 tN(N,A={}){return async function(H,P={}){let{searchParams:F,json:I,body:B,headers:G,dynamicHeader:S,retry:w,timeoutMs:Y,abortController:W,onError:M,onSuccess:K,responseHandler:b,...z}={...A,...P},PN=x.get("requestOptions"),X={...PN.retry,...w},gN=!!I||H.endsWith(".json"),GN=gT(H,F),CN=S?await S():{},LN=$T(gN,{...G,...CN}),r=gN?JSON.stringify(I):B,wN;for(let _N=0;_N<=X.maxRetries;_N++){let dN=W||new AbortController,hN=setTimeout(()=>dN.abort(),Y||PN.timeoutMs);try{let o=await BT(GN,{...z,body:r,headers:LN,method:N,signal:dN.signal});return clearTimeout(hN),K?.(o)||b?.(o)||o}catch(o){clearTimeout(hN),wN=o;let cA=o?.cause?.status;if(_N>=X.maxRetries||!OT(o,cA))return M?M(o):Promise.reject(o);await IT(nT(_N,X))}}return M?M(wN):Promise.reject(wN)}}function $T(N,A){return{...A,...N&&{"Content-Type":"application/json"}}}function gT(N,A){let T=new URL(N);if(A)T.search=new URLSearchParams(A).toString();return T.toString()}var g={extend:(N)=>({extend:(A)=>g.extend({...N,...A}),get:tN("GET",N),post:tN("POST",N)}),get:tN("GET"),post:tN("POST")};import{Chain as Z,CosmosChains as GT,EVMChains as _T,StagenetChains as tT,UTXOChains as DT}from"@swapkit/types";import{match as aN}from"ts-pattern";import{Chain as jN}from"@swapkit/types";function sP(N){if(N<0)throw new D({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:N}});return 10+N}function eP(N){if(N<0)throw new D({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:N}});return Math.round((10+N*1.0512)*10000000000)/10000000000}function aP(N,A){try{return N()}catch(T){if(A)throw new D(A,T);return}}function NL(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 sN=new Set;function l({condition:N,id:A,warning:T}){if(N){if(sN.has(A))return;console.warn(T),sN.add(A)}}function YT(N){return aN(N).with(..._T,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...DT,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...GT,...tT,()=>({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.HyperCore,()=>({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 D("helpers_chain_not_supported",{chain:N})})}function UT(N){return aN(N).with(Z.Aptos,()=>"/-/healthy").with(Z.HyperCore,()=>"/info").with(Z.Radix,()=>"/status/network-configuration").with(Z.Stellar,()=>"").with(Z.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function eN(N,A){try{let T=A.startsWith("wss")?A.replace("wss","https"):A;return(await fetch(`${T}${UT(N)}`,{body:JSON.stringify(YT(N)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var vN=new Map,ST=120000;function MT(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 D("helpers_chain_no_public_or_set_rpc_url",{chain:N});let T=vN.get(N);if(T&&Date.now()-T.timestamp<ST)return T.url;return vN.set(N,{timestamp:Date.now(),url:A}),A}async function i(N){let A=MT(N),[,...T]=x.get("rpcUrls")[N];if(await eN(N,A))return A;for(let P of T)if(await eN(N,P))return vN.set(N,{timestamp:Date.now(),url:P}),P;throw new D("helpers_chain_rpc_connection_failed",{chain:N,fallbackUrls:T,primaryRpcUrl:A})}function uL(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 $L=[`${n.Maya}.MAYA`,`${n.Maya}.CACAO`,`${n.Ethereum}.THOR`,`${n.Ethereum}.vTHOR`,`${n.Kujira}.USK`,`${n.Ethereum}.FLIP`,`${n.Radix}.XRD`],TA=[n.Arbitrum,n.Aurora,n.Base,n.Ethereum,n.Optimism];async function QT(N){let{baseDecimal:A}=C(n.Radix);try{let T=await i(n.Radix),{manager:H}=await g.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 xT(N){try{let A=await i(n.Radix);return(await g.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 HA({chain:N,address:A,methodHex:T,id:H}){let P=await i(N);return g.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 wT(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 bT(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 zT({chain:N,address:A}){let{baseDecimal:T}=C(N),H=A.toLowerCase();if(A===""||!H.startsWith("0x"))return T;let P=await HA({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 bT(P.result,T)}async function JT({chain:N,address:A}){let T=A.toLowerCase();if(T===""||!T.startsWith("0x"))return;let H=await HA({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 wT(H.result)}async function NA({rpcUrl:N,contractAddress:A,functionSelector:T}){return(await g.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 AA(N){let A=N.match(/.{2}/g)?.map((T)=>Number.parseInt(T,16))??[];return new TextDecoder().decode(new Uint8Array(A))}function ZT(N){return FN(N).with(void 0,()=>{return}).when((A)=>A.length>=128,(A)=>{let T=Number.parseInt(A.slice(64,128),16);return AA(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 AA(T);return}).otherwise(()=>{return})}function PA({chain:N,address:A}){let{baseDecimal:T}=C(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,B]=await Promise.all([JT({address:A,chain:N}),zT({address:A,chain:N})]);return{decimals:B,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 i(n.Tron),[F,I]=await Promise.all([NA({contractAddress:A,functionSelector:"symbol()",rpcUrl:P}),NA({contractAddress:A,functionSelector:"decimals()",rpcUrl:P})]),B=ZT(F);return{decimals:F!==void 0&&I?Number(BigInt(`0x${I}`)):T,ticker:B}}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 i(n.Near),B=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"}),G=JSON.parse(Buffer.from(B.result).toString());return{decimals:G?.decimals||T,ticker:G?.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([xT(A),QT(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 DN({chain:N,symbol:A}){return FN(N).with(...TA,()=>A==="ETH").with(n.Avalanche,()=>A==="AVAX").with(n.Berachain,()=>A==="BERA").with(n.Hyperevm,()=>A==="HYPE").with(n.HyperCore,()=>A==="HYPE").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}`===YN(N).identifier).otherwise(()=>A===N)}var YN=(N)=>{let{baseDecimal:A}=C(N);return FN(N.toUpperCase()).with(...TA,(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.HyperCore,(H)=>({decimal:A,identifier:`${H}.HYPE`})).with(n.Tron,(H)=>({decimal:A,identifier:`${H}.TRX`})).with(n.Solana,n.Chainflip,n.Kujira,n.Ripple,n.Polkadot,n.Near,...ET,(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:C(n.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:C(n.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:C(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 VN({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}`===YN(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.HyperCore,()=>A==="HYPE").with(n.XLayer,()=>A==="OKB").otherwise(()=>A===N)?"Native":N}var d=(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 IN(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 gL(N){return`https://storage.googleapis.com/token-list-swapkit-dev/images/${N.toLowerCase()}.png`}async function GL(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:B}=d(F.identifier);if(I!==N.chain)continue;let{address:G}=IN(B,I);if(G?.toLowerCase()===P)return F.identifier}return}var LA=["TERRA",...x.get("chains")];function RA(N=""){let A=N.toUpperCase(),[T]=A.split(".");if(LA.includes(T))return!0;let[H]=A.split("/");if(LA.includes(H))return!0;throw new D({errorKey:"helpers_invalid_identifier",info:{identifier:N,message:`Invalid identifier: ${N}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}function YL(N){if(N.length>30)return!1;let A=/^[a-zA-Z0-9+_-]+$/g;return!!N.match(A)}import{match as UN}from"ts-pattern";var s=8,jT=10;function c({value:N,bigIntDecimal:A=s,decimal:T=s}){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,B=P.slice(-T);if(Number.parseInt(B[A]||"0",10)>=5){let S=Number.parseInt(B[A-1]||"0",10);B=`${B.substring(0,A-1)}${S+1}`}else B=B.substring(0,A);return`${H?"-":""}${P.slice(0,I)}.${B}`.replace(/\.?0*$/,"")}class y{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(N,A){return new y({decimal:A,value:c({bigIntDecimal:A,decimal:A,value:N})})}static shiftDecimals({value:N,from:A,to:T}){return y.fromBigInt(N.getBaseValue("bigint")*h(T)/h(A),T)}constructor(N){let A=WN(N),T=typeof N==="object";this.decimal=T?N.decimal:void 0,this.decimalMultiplier=T&&"decimalMultiplier"in N?N.decimalMultiplier:h(Math.max(uA(SN(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=nN(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 UN(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/h(A||this.decimal||s),H=VT(this.bigIntValue,T);return UN(N).with("number",()=>Number(H)).with("string",()=>H.toString()).otherwise(()=>H)}getBigIntValue(N,A){if(!A&&typeof N==="object")return N.bigIntValue;let T=WN(N),H=SN(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(),B=I.slice(0,N),G=H.length-I.length;return`0.${B.padStart(G+B.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 B=P[N];if(!(B&&Number.parseInt(B,10)>=5))return`${I}${H}.${P.slice(0,N).padEnd(N,"0")}`;let S=BigInt(P.slice(0,N).padEnd(N,"0"))+1n,w=10n**BigInt(N);if(S>=w)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),B=A==="end",[G="0",S=""]=I.split("."),w=G.replace(/\B(?=(\d{3})+(?!\d))/g,P),Y=S&&Number.parseInt(S,10)>0,W=Y?`${w}${H}${S}`:w,K=W.length<100&&F&&Y?W.replace(/\.?0*$/,""):W;return B?`${K}${N}`:`${N}${K}`}formatBigIntToSafeValue(N,A){let T=A||this.decimal||s,H=Math.max(T,nN(this.decimalMultiplier));return c({bigIntDecimal:T,decimal:H,value:N})}#A(N,...A){let T=this.#T(this,...A),H=nN(this.decimalMultiplier),F=Math.max(T,H)+jT,I=h(F),B=A.reduce((S,w)=>{let Y=this.getBigIntValue(w,F);return UN(N).with("add",()=>S+Y).with("sub",()=>S-Y).with("mul",()=>S*Y/I).with("div",()=>{if(Y===0n)throw RangeError("Division by zero");return S*I/Y}).otherwise(()=>S)},this.bigIntValue*I/this.decimalMultiplier),G=c({bigIntDecimal:F,decimal:F,value:B});return new this.constructor({decimal:this.decimal,decimalMultiplier:h(F),identifier:this.toString(),value:G})}#N(N,...A){let T=this.#T(this,...A),H=this.getBigIntValue(A[0]||"0",T),P=this.getBigIntValue(this,T);return UN(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=SN(N)||"0";this.bigIntValue=this.#H(A)}#T(...N){let A=N.map((T)=>{return typeof T==="object"?T.decimal||nN(T.decimalMultiplier):uA(SN(T))}).filter(Boolean);return Math.max(...A,s)}#H(N,A){let T=A?h(A):this.decimalMultiplier,H=nN(T),[P="",F=""]=N.split(".");return BigInt(`${P}${F.padEnd(H,"0")}`)}}var vT=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function SN(N){let T=`${typeof N==="number"?vT.format(N):WN(N)}`.replaceAll(",",".").split(".");return T.length>1?`${T.slice(0,-1).join("")}.${T.at(-1)}`:T[0]||"0"}function uA(N){let A=N.split(".")[1]?.length||0;return Math.max(A,s)}function WN(N){return typeof N==="object"?"getValue"in N?N.getValue("string"):N.value:N}function VT(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 h(N){return 10n**BigInt(N)}function nN(N){return Math.log10(Number.parseFloat(N.toString()))}var f=[E.HyperCore,E.Near,E.Ripple,E.Solana,E.Sui,E.Ton,E.Tron],kN=[E.THORChain,E.Maya],e=new Map,MN=new Map,a=new Map,mT=3600000;function kT(N){let A=a.get(N);if(A?.timestamp&&Date.now()-A.timestamp>mT){a.delete(N);return}return A}function KT(N,A){if(a.size>1000){let T=a.keys().next().value;if(T)a.delete(T)}a.set(N,{...A,timestamp:Date.now()})}class m 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=IA(F||`${H}.${P}`);this.type=VN(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=ON(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 e.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 D({errorKey:"helpers_invalid_asset_url",info:{urlAsset:N}});let H=N.slice(0,T),P=N.slice(T+1),F=mN({chain:H,rest:P}).when(({rest:I})=>I.includes(".."),({chain:I,rest:B})=>`${I}.${B.replace(/\.\./g,"~")}`).when(({chain:I,rest:B})=>kN.includes(I)&&B.includes("."),({chain:I,rest:B})=>`${I}.${B.replace(/\./g,"/")}`).otherwise(({chain:I,rest:B})=>`${I}.${B.replace(/__/g,".")}`);return m.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=fT(H),I=!F.startsWith(E.Sui)&&F.includes(":");if(T&&I){let[LN,r]=F.split(":");return oT({address:r,chain:LN,fromBaseDecimal:A,parsedValue:P})}let B=I?F.split(":").join(".UNKNOWN-"):F,{identifier:G,decimal:S}=YN(B),{chain:w,isSynthetic:Y,isTradeAsset:W,address:M}=IA(G),{baseDecimal:K}=ON(w),b=e.get(f.includes(w)?G:G.toUpperCase());if(!b&&T&&!Y&&!W)return(async()=>{let{ticker:LN}=d(G),r=await nA({address:M,chain:w,ticker:LN});return qN({decimal:r.decimals,identifier:r.identifier,value:A?NN(BigInt(P),A):P})})();let z=b?.decimal||S;l({condition:!z&&!T,id:`assetValue_static_decimal_not_found_${w}`,warning:`Couldn't find static decimal for one or more tokens on ${w} (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:PN,identifier:X,tax:gN}=b||{decimal:z||K,identifier:G},GN=A?NN(BigInt(P),A):NN(P,PN);return Y||W?pT(X,GN):qN({decimal:PN,identifier:X,tax:gN,value:GN})}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:B}=d(F),{address:G}=IN(B,I),{baseDecimal:S}=ON(I),w=f.includes(I)?F:F.toUpperCase(),Y="decimals"in P&&P.decimals!==void 0?P.decimals:S,W="logoURI"in P&&P.logoURI?P.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${F.toLowerCase()}.png`,M={decimal:Y,identifier:F,logoURI:W,tax:"tax"in P?P.tax:void 0};if(e.set(w,M),G){let K=f.includes(I)?`${I}:${G}`:`${I}:${G.toUpperCase()}`;MN.set(K,F)}}return!0}static setStaticAssets(N){e.clear(),MN.clear();for(let[A,T]of N.entries()){let{identifier:H}=T,{chain:P,symbol:F}=d(H),{address:I}=IN(F,P),{baseDecimal:B}=ON(P),G=T.chain??P,S=T.address??I,w=f.includes(G)?H:H.toUpperCase(),Y=T.decimals??T.decimal??B,W=T.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${H.toLowerCase()}.png`,M={decimal:Y,identifier:w,logoURI:W,tax:T.tax};if(e.set(w,M),S){let K=f.includes(G)?`${G}:${S}`:`${G}:${S.toUpperCase()}`;MN.set(K,H)}}return!0}static get staticAssets(){return e}}function ZL(N){let A=m.from({chain:N});return mN(N).with(E.Bitcoin,E.Litecoin,E.BitcoinCash,E.Dash,()=>A.set(0.00010001)).with(E.Dogecoin,()=>A.set(1.00000001)).with(E.Avalanche,E.Ethereum,E.Arbitrum,E.BinanceSmartChain,()=>A.set(0.00000001)).with(E.THORChain,E.Maya,()=>A.set(0)).with(E.Cosmos,E.Kujira,()=>A.set(0.000001)).otherwise(()=>A.set(0.00000001))}async function nA({chain:N,address:A,ticker:T}){let P=f.includes(N)?`${N}:${A||T}`:`${N}:${A||T}`.toUpperCase(),F=kT(P);if(F)return F;if(!A){let{baseDecimal:G}=ON(N);return{decimals:G,identifier:`${N}.${T||"UNKNOWN"}`}}let I=await PA({address:A,chain:N}),B=`${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&&KT(P,{decimals:I.decimals,identifier:B}),{decimals:I.decimals,identifier:B}}function qN({identifier:N,decimal:A,value:T,tax:H}){return RA(N),new m({decimal:A,identifier:N,tax:H,value:NN(T,A)})}function pT(N,A=0){let T=N.includes(".")?N.split(".")?.[0]?.toUpperCase():void 0,H=T?kN.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 D({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});return new m({decimal:8,identifier:`${T||E.THORChain}.${F}${P}${I}`,value:NN(A,8)})}async function oT({address:N,chain:A,fromBaseDecimal:T,parsedValue:H}){let{decimals:P,identifier:F}=await nA({address:N,chain:A}),I=T?NN(BigInt(H),T):H;return qN({decimal:P,identifier:F,value:I})}function NN(N,A){return typeof N==="bigint"?c({bigIntDecimal:A,decimal:A,value:N}):N}function yT(N){let A=mN(N).when((T)=>("chain"in T)&&T.chain!==void 0,({chain:T})=>T).otherwise((T)=>{let H=d(T.asset);return H.synth?E.THORChain:H.chain});if(!WT.includes(A.toUpperCase())){let T="asset"in N?N.asset:A;throw new D({errorKey:"helpers_invalid_asset_identifier",info:{identifier:T,message:`Unsupported chain "${A}" - use the AssetValue constructor directly`}})}}function fT(N){if(yT(N),"chain"in N){let{chain:P,address:F}=N;if(F){let I=f.includes(P)?`${P}:${F}`:`${P}:${F.toUpperCase()}`,B=MN.get(I);if(B)return B;return I}return P}let{chain:A,symbol:T}=d(N.asset);return VN({chain:A,symbol:T})==="Native"?A:N.asset}function CT(N,A,T){let H=N.split("."),P=H[0]?.toUpperCase(),F=kN.includes(P),I=T?"~":"/",[B,G=""]=F?H.slice(1).join(".").split(I):N.split(I);if(!(B&&G))throw new D({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});let{ticker:S,address:w}=OA({chain:B,symbol:G}),Y=`${B}${I}${G}`;return{address:w,chain:P,isGasAsset:!1,isSynthetic:A,isTradeAsset:T,symbol:Y,ticker:S}}function dT(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}=OA({chain:T,symbol:H}),I;try{I=P&&qT.includes(T)&&FA(P)?FA(P):P}catch{I=P}let B=I?`${F}-${I}`:H;return{address:I,chain:T,isGasAsset:DN({chain:T,symbol:H}),isSynthetic:!1,isTradeAsset:!1,symbol:B,ticker:F}}function IA(N){let A=N.slice(0,14),T=A.includes("/"),H=A.includes("~");if(T||H)return CT(N,T,H);return dT(N)}function OA({symbol:N,chain:A}){let{ticker:T,address:H}=IN(N,A);return{address:H&&!f.includes(A)?H.toLowerCase():H,ticker:T}}class XN extends y{eq(N){return this.eqValue(N)}static fromBigInt(N,A){return new XN({decimal:A,value:c({bigIntDecimal:A,decimal:A,value:N})})}}function BA(N=!0){return N?"https://midgard.ninerealms.com":"https://midgard.mayachain.info"}function cT(N=!0){let A=BA(N);return N?`${A}/v2/thorname`:`${A}/v2/mayaname`}function rT(N){return function(T){let H=T?`?status=${T}`:"";return g.get(`${N}/v2/pools${H}`)}}function lT(N){return function(T){return g.get(`${N}/v2/pool/${T}`)}}function iT(N){return function(T,H){let P=H?`?period=${H}`:"";return g.get(`${N}/v2/pool/${T}/stats${P}`)}}function sT(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 g.get(`${N}/v2/history/depths/${T}${F}`)}}function eT(N){return function(){return g.get(`${N}/v2/network`)}}function aT(N){return function(){return g.get(`${N}/v2/health`)}}function NH(N){return function(){return g.get(`${N}/v2/nodes`)}}function AH(N){return function(T){return g.get(`${N}/v2/node/${T}`)}}function TH(N){return function(){return g.get(`${N}/v2/mimir/votes`)}}function HH(N){return function(){return g.get(`${N}/v2/mimir`)}}function PH(N){return function(){return g.get(`${N}/v2/constants`)}}function LH(N){return function(){return g.get(`${N}/v2/stats`)}}function RH(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 g.get(`${N}/v2/history/earnings${P}`)}}function uH(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 g.get(`${N}/v2/history${I}${F}`)}}function FH(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 g.get(`${N}/v2/history/tvl${P}`)}}function IH(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 nH(N){return function(T){let H=IH(T);return g.get(`${N}/v2/actions${H}`)}}function OH(N){return function(T){return g.get(`${N}/v2/member/${T}`)}}function BH(N){return function(T){let H=T?`/${T}`:"";return g.get(`${N}/v2/members${H}`)}}function $H(N){return function(T,H){let P=H?`&asset=${H}`:"";return g.get(`${N}/v2/saver/${T}${P?`?${P.substring(1)}`:""}`)}}function gH(N){return function(T){return g.get(`${N}/v2/savers/${T}`)}}function GH(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 g.get(`${N}/v2/history${I}${F}`)}}function _H(N){return function(T){return g.get(`${N}/v2/balance/${T}`)}}function tH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return;throw P};return await g.get(`${N}/lookup/${T}`,{onError:H,retry:{maxRetries:1}})}}function DH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return[];throw P};return await g.get(`${N}/rlookup/${T}`,{onError:H,retry:{maxRetries:1}})}}function YH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return[];throw P};return await g.get(`${N}/owner/${T}`,{onError:H,retry:{maxRetries:1}})}}function AN({asset:N,value:A}){return m.from({asset:N,fromBaseDecimal:hT(EN.THORChain).baseDecimal,value:A})}function UH({liquidityPositionGetter:N,isThorchain:A}){return async function(H){let P=await N(H),F=A?"rune":"cacao";return P.pools.map((I)=>({[`${F}Pending`]:AN({asset:"THOR.RUNE",value:I.runePending}),[`${F}RegisteredAddress`]:I.runeAddress,[`${F}Withdrawn`]:AN({asset:"THOR.RUNE",value:I.runeWithdrawn}),[F]:AN({asset:"THOR.RUNE",value:I.runeAdded}),asset:AN({asset:I.pool,value:I.assetAdded}),assetPending:AN({asset:I.pool,value:I.assetPending}),assetRegisteredAddress:I.assetAddress,assetWithdrawn:AN({asset:I.pool,value:I.assetWithdrawn}),dateFirstAdded:I.dateFirstAdded,dateLastAdded:I.dateLastAdded,poolShare:new XN(I.liquidityUnits).div(I.pool)}))}}function $A(N){let A=N===EN.THORChain,T=BA(A),H=cT(A),P=OH(T);return{getActions:nH(T),getBalance:_H(T),getConstants:PH(T),getEarningsHistory:RH(T),getHealth:aT(T),getLiquidityPosition:UH({isThorchain:A,liquidityPositionGetter:P}),getLiquidityPositionRaw:P,getMembers:BH(T),getMimir:HH(T),getMimirVotes:TH(T),getNameDetails:tH(H),getNamesByAddress:DH(H),getNamesByOwner:YH(H),getNetworkInfo:eT(T),getNode:AH(T),getNodes:NH(T),getPool:lT(T),getPoolDepthHistory:sT(T),getPoolStats:iT(T),getPools:rT(T),getSaverDetails:$H(T),getSavers:gH(T),getSaversHistory:GH(T),getStats:LH(T),getSwapHistory:uH(T),getTVLHistory:FH(T)}}var gA=$A(EN.THORChain),GA=$A(EN.Maya);var yN={};cN(yN,{getTrackerDetails:()=>rH,getTokenListProviders:()=>aH,getTokenList:()=>NP,getTokenApproval:()=>eH,getSwapTo:()=>FP,getSwapQuote:()=>lH,getRouteWithTx:()=>iH,getPrice:()=>AP,getNearDepositChannel:()=>PP,getGasRate:()=>TP,getChainflipDepositChannel:()=>HP,getChainBalance:()=>sH,SKRequestClient:()=>V});import{EVMChains as hH}from"@swapkit/types";import{match as cH,P as $N}from"ts-pattern";async function _A(N,A,T){let H=`${A}:${T}`,P=new TextEncoder,F=await crypto.subtle.importKey("raw",P.encode(N),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),I=await crypto.subtle.sign("HMAC",F,P.encode(H));return Array.from(new Uint8Array(I)).map((B)=>B.toString(16).padStart(2,"0")).join("")}import{Chain as QN,ChainId as BN}from"@swapkit/types";import{array as Q,boolean as p,coerce as UA,number as _,object as $,optional as O,string as R,union as KN,unknown as SA,z as L}from"zod/v4";var MA;((H)=>{H.CHEAPEST="CHEAPEST";H.FASTEST="FASTEST";H.RECOMMENDED="RECOMMENDED"})(MA||={});var xN;((P)=>{P.PSBT="PSBT";P.EVM="EVM";P.COSMOS="COSMOS";P.RADIX="RADIX"})(xN||={});var XA;((z)=>{z.approve="approve";z.claim="claim";z.deposit="deposit";z.donate="donate";z.lending="lending";z.lp_action="lp_action";z.native_contract_call="native_contract_call";z.native_send="native_send";z.stake="stake";z.streaming_swap="streaming_swap";z.swap="swap";z.thorname_action="thorname_action";z.token_contract_call="token_contract_call";z.token_transfer="token_transfer";z.unknown="unknown";z.unstake="unstake"})(XA||={});var EA;((M)=>{M.swap="swap";M.aggregation="aggregation";M.addLiquidity="addLiquidity";M.withdrawLiquidity="withdrawLiquidity";M.addSavers="addSavers";M.withdrawSavers="withdrawSavers";M.borrow="borrow";M.repay="repay";M.name="name";M.donate="donate";M.claim="claim";M.stake="stake";M.unstake="unstake"})(EA||={});var QA;((B)=>{B.unknown="unknown";B.not_started="not_started";B.pending="pending";B.swapping="swapping";B.completed="completed";B.refunded="refunded";B.failed="failed"})(QA||={});var xA;((b)=>{b.not_started="not_started";b.starting="starting";b.broadcasted="broadcasted";b.mempool="mempool";b.inbound="inbound";b.outbound="outbound";b.swapping="swapping";b.completed="completed";b.refunded="refunded";b.partially_refunded="partially_refunded";b.dropped="dropped";b.reverted="reverted";b.replaced="replaced";b.retries_exceeded="retries_exceeded";b.parsing_error="parsing_error"})(xA||={});var CL=$({address:O(R()),chain:L.enum(QN).optional(),chainId:L.enum(BN),coingeckoId:O(R()),decimals:UA.number(),extensions:O(L.looseObject({})),identifier:R(),logoURI:O(R()),name:O(R()),shortCode:O(R()),symbol:O(R()),ticker:R()}),dL=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"}),hL=L.object({forceUpdate:L.string().toLowerCase().transform((N)=>N==="true").pipe(L.boolean()).optional()}),cL=$({error:R(),message:R()}),TN=$({address:O(R()),chain:L.enum(QN),decimal:O(_()),isGasAsset:p(),isSynthetic:p(),symbol:R(),tax:O($({buy:_(),sell:_()})),ticker:R()}),wA=$({id:R(),market_cap:_(),name:R(),price_change_24h_usd:_(),price_change_percentage_24h_usd:_(),sparkline_in_7d:Q(_()),timestamp:R(),total_volume:_()}).partial(),rL=$({cg:O(wA),identifier:R(),price_usd:_(),provider:R(),timestamp:_()}),bA=Q($({cg:O(wA),identifier:R(),price_usd:_(),provider:R(),timestamp:_()}).partial()),lL=$({affiliate:O(R().describe("Affiliate thorname")),affiliateFee:O(_().describe("Affiliate fee in basis points").refine((N)=>N===Math.floor(N)&&N>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:O(p().describe("Allow smart contract as recipient")),allowSmartContractSender:O(p().describe("Allow smart contract as sender")),buyAsset:R().describe("Asset to buy"),cfBoost:O(p().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:O(R().describe("Address to send asset to")),disableSecurityChecks:O(p().describe("Disable security checks")),includeTx:O(p().describe("Set to true to include an transaction object (EVM only)")),providers:O(Q(R().describe("List of providers to use").refine((N)=>j[N]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:O(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:O(_().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:O(R().describe("Address to send asset from"))}).refine((N)=>N.sellAsset!==N.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),iL=$({metadata:p(),tokens:Q($({identifier:R()}))}),zA=$({destinationAddress:R()}),SH=zA.extend({affiliateFees:Q($({brokerAddress:R(),feeBps:_()})).optional(),brokerCommissionBps:_().optional(),buyAsset:$({asset:R(),chain:R()}),channelMetadata:$({cfParameters:R().optional(),gasBudget:R().optional(),message:R().optional()}).optional(),dcaParameters:$({chunkInterval:_().optional(),numberOfChunks:_().optional()}).optional(),maxBoostFeeBps:_().optional(),refundParameters:$({minPrice:R().optional(),refundAddress:R().optional(),retryDuration:_().optional()}).optional(),sellAsset:$({asset:R(),chain:R()})}),JA=$({channelId:R(),depositAddress:R()}),tA=zA.extend({affiliateFees:$({feeBps:_(),nearId:R()}).optional(),buyAsset:R(),sellAmount:R(),sellAsset:R(),slippage:UA.number(),sourceAddress:R()}),DA=$({amountIn:R(),amountInFormatted:R(),amountInUsd:R(),amountOut:R(),amountOutFormatted:R(),amountOutUsd:R(),deadline:R().optional(),minAmountIn:R(),minAmountOut:R(),timeEstimate:_().optional(),timeWhenInactive:R().optional()}),sL=DA.extend({depositAddress:R(),quote:DA,signature:R(),timestamp:R(),tx:SA()}),ZA=$({buyAsset:R(),buyAssetAmount:R(),buyAssetAmountMaxSlippage:R(),deadline:R().optional(),depositAddress:R(),depositAmount:R(),depositAsset:R(),tx:SA()}),MH=$({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=$({currentStage:R(),inboundConfirmation:_(),inboundObservation:_(),outboundDelay:_(),outboundObservation:_(),streamingSwap:_()}),EH=$({count:O(_()),interval:O(_()),quantity:O(_()),subSwapsMap:O(Q(_()))}),QH=L.object({currentLegIndex:L.optional(L.number()),estimatedTimeToComplete:L.number(),estimates:L.optional(XH),providerDetails:L.optional(L.object({streamingDetails:L.optional(EH)}))}),xH=$({affiliate:O(TN),liquidity:O(TN),network:O(TN),protocol:O(TN),tax:O(TN)}),wH=$({affiliate:R(),bps:R(),isReferrer:p()}),bH=$({affiliate:O(R()),affiliateFees:O(Q(wH)),broadcastedAt:O(_()),explorerUrl:O(R()),fees:O(xH),images:O($({chain:O(R()),from:O(R()),provider:O(R()),to:O(R())})),provider:O(L.enum(j)),providerAction:L.optional(L.enum(EA)),quoteId:O(R()),wallet:O(R())}),HN=L.object({block:L.number(),chainId:L.enum(BN),finalAddress:L.optional(L.string()),finalAsset:L.optional(TN),finalisedAt:L.number(),fromAddress:L.string(),fromAmount:L.string(),fromAsset:L.string(),hash:L.string(),meta:L.optional(bH),payload:L.optional(MH),status:L.enum(QA),toAddress:L.string(),toAmount:L.string(),toAsset:L.string(),trackingStatus:L.optional(L.enum(xA)),transient:L.optional(QH),type:L.enum(XA)}),jA=HN.extend({legs:L.array(HN)}),eL=HN.extend({legs:Q(HN)}),aL=HN.extend({legs:Q(HN)}),pN=Q($({amount:R(),asset:R(),chain:R(),protocol:L.enum(j),type:L.enum(zN)})),oN=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")}),vA=$({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")}),VA=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()}),zH=Q(KN([R(),_(),Q(R()),$({from:R(),value:R()}).describe("Parameters to pass to the contract method")])),NR=$({approvalSpender:O(R().describe("Address of the spender to approve")),approvalToken:O(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:Q(R().describe("Names of the parameters to pass to the contract method")),contractParams:zH}),JH=$({typeUrl:R("/types.MsgDeposit"),value:$({coins:Q($({amount:R(),asset:$({chain:R(),symbol:R(),synth:p(),ticker:R()})})),memo:R(),signer:R()})}),ZH=$({typeUrl:R("/types.MsgSend"),value:$({amount:Q($({amount:R(),denom:R()})),fromAddress:R(),toAddress:R()})}),jH=$({typeUrl:R(),value:ZH.or(JH)}),vH=$({amount:Q($({amount:R(),denom:R()})),gas:R()}),WA=$({accountNumber:_(),chainId:L.enum(BN),fee:vH,memo:R(),msgs:Q(jH),sequence:_()}),VH=L.array(L.object({calldata:L.array(L.string()),contractAddress:L.string(),entrypoint:L.string()})),qA=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")})),WH=$({affiliate:R().describe("Affiliate address").optional(),affiliateFee:_().describe("Affiliate fee").optional(),buyAsset:R().describe("Asset to buy"),destinationAddress:R().describe("Destination address"),estimatedTime:oN.optional(),provider:L.enum(j),sellAsset:R().describe("Asset to sell"),slipPercentage:_().describe("Slippage as a percentage"),sourceAddress:R().describe("Source address")}),AR=WH.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),qH=$({asset:R().describe("Asset name"),image:R().describe("Asset image"),price:_().describe("Price in USD")}),mH=SH,mA=$({assets:O(Q(qH)),maxStreamingQuantity:_().optional(),referrer:R().optional(),streamingInterval:_().optional(),tags:Q(L.enum(MA))}),kA=mA.extend({affiliate:O(R()),affiliateFee:O(R()),approvalAddress:O(R().describe("Approval address for swap")),chainflip:mH.optional(),garden:tA.optional(),near:tA.optional(),priceImpact:O(_().describe("Price impact")),referrer:O(R()),txType:O(L.enum(xN))}),KA=Q($({code:L.enum(bN),display:R(),tooltip:R().optional()})),kH=$({buyAmount:R().describe("Buy amount"),buyAmountMaxSlippage:R().describe("Buy amount max slippage"),buyAsset:R().describe("Asset to buy"),fees:O(pN),provider:L.enum(j),sellAmount:R().describe("Sell amount"),sellAsset:R().describe("Asset to sell")}),KH=$({buyAsset:R().describe("Asset to buy"),destinationAddress:O(R().describe("Destination address")),estimatedTime:O(oN),expectedBuyAmount:R().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:R().describe("Expected Buy amount max slippage"),expiration:O(R().describe("Expiration")),fees:pN,inboundAddress:O(R().describe("Inbound address")),legs:Q(kH),memo:O(R().describe("Memo")),meta:kA,providers:Q(L.enum(j)),routeId:R().describe("Route ID"),sellAmount:R().describe("Sell amount"),sellAsset:R().describe("Asset to sell"),sourceAddress:O(R().describe("Source address")),targetAddress:O(R().describe("Target address")),totalSlippageBps:_().describe("Total slippage in bps"),tx:O(KN([vA,WA,VA,VH,qA,R()])),txType:O(L.enum(xN)),warnings:KA}),pA=$({error:O(R().describe("Error message")),providerErrors:O(Q($({errorCode:O(L.enum(uN)),message:O(R()),provider:L.enum(j).optional()}))),quoteId:R().describe("Quote ID"),routes:Q(KH)}),oA=L.object({chainId:L.enum(BN),createdAt:L.date(),id:L.number(),unit:L.string(),value:L.string()}),pH=L.array(oA),yA=L.union([oA,pH]),TR=Q($({chain:L.enum(QN),decimal:_(),identifier:R(),symbol:R(),ticker:R(),value:R()})),HR=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()})]),PR=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()}),oH=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)")}),YA=L.object({buyAmount:L.string().describe("Buy amount"),buyAmountMaxSlippage:L.string().describe("Buy amount max slippage"),buyAsset:L.string().describe("Asset to buy"),expectedBuyAmount:L.string().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:L.string().describe("Expected Buy amount max slippage"),fees:pN,provider:L.enum(j),sellAmount:L.string().describe("Sell amount"),sellAsset:L.string().describe("Asset to sell")}),fA=YA.extend({estimatedTime:L.optional(oN),expiration:L.optional(L.string().describe("Expiration")),legs:L.array(YA),providers:L.array(L.enum(j)),routeId:L.string().describe("Route ID"),totalSlippageBps:L.number().describe("Total slippage in bps"),warnings:KA}).omit({provider:!0}),yH=L.object({method:L.string(),payload:L.optional(L.unknown()),url:L.string()}),fH=fA.extend({meta:mA,nextActions:L.optional(L.array(yH))}),LR=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(L.object({errorCode:L.optional(L.enum(uN)),message:L.optional(L.string()),provider:L.enum(j).optional()}))),quoteId:L.string().describe("Quote ID"),routes:L.array(fH)}),RR=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(QN).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")}),uR=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=fA.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:kA,sourceAddress:L.string().describe("Source address"),targetAddress:L.optional(L.string().describe("Target address")),tx:O(KN([vA,WA,VA,qA,R()])),txType:L.optional(L.enum(xN))}),dH=L.object({data:L.optional(L.record(L.string(),L.string().optional())),errorCode:L.enum(uN),message:L.string().optional(),provider:L.enum(j).optional()}),FR=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(dH)),quoteId:L.string().describe("Quote ID"),routes:L.array(CA)}),dA=CA.extend({approvalTx:oH.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=g.extend({dynamicHeader:async()=>{let N=x.get("widgetKey");if(N&&typeof window<"u"){let T=Math.floor(Date.now()/1000),H=window.location.origin;return{"X-Signature":await _A(N,H,T),"X-Timestamp":T.toString()}}let{swapKit:A}=x.get("apiKeys");return A?{"x-api-key":A}:{}}});async function rH(N){let A=await V.post(v("/track"),{json:N});try{let T=jA.safeParse(A);if(!T.success)throw new D("api_v2_invalid_response",T.error);return T.data}catch(T){return A}}async function lH(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(v(H),{json:N});if(P.error)throw new D("api_v2_server_error",{message:P.error});try{let F=pA.safeParse(P);if(!F.success)throw new D("api_v2_invalid_response",F.error);return F.data}catch{return P}}async function iH(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(v(H),{json:N});try{let F=dA.safeParse(P);if(!F.success)throw new D("api_v2_invalid_response",F.error);return F.data}catch(F){return console.error(new D("api_v2_invalid_response",F)),P}}async function sH({chain:N,address:A,scamFilter:T=!0}){let{getBalance:H}=x.get("endpoints");if(H)return H({address:A,chain:N});let P=v(`/balance?chain=${N}&address=${A}`),F=await V.get(P),I=Array.isArray(F)?F:[];return T?uP(I):I}function eH(N){let A=cH(N).with({routeId:$N.string,spender:$N.string},({routeId:T,spender:H})=>v(`/approve?routeId=${T}&sourceAddress=${H}`)).with({assetValue:$N.instanceOf(m),spender:$N.string,userWallet:$N.string},({spender:T,userWallet:H,assetValue:P})=>v(`/approve?tokenIdentifier=${P.toString()}&userWalletAddress=${H}&spender=${T}&amount=${P.getValue("string")}`)).exhaustive();return V.get(A)}function aH(){let N=v("/providers");return V.get(N)}function NP(N){let A=v(`/tokens?provider=${N}`);return V.get(A)}async function AP(N){let A=v("/price"),T=await V.post(A,{json:N});try{let H=bA.safeParse(T);if(!H.success)throw new D("api_v2_invalid_response",H.error);return H.data}catch(H){throw new D("api_v2_invalid_response",H)}}async function TP(){let N=v("/gas"),A=await V.get(N);try{let T=yA.safeParse(A);if(!T.success)throw new D("api_v2_invalid_response",T.error);return Array.isArray(T)?T:[T]}catch(T){throw new D("api_v2_invalid_response",T)}}async function HP(N){let{destinationAddress:A}=N;if(!A)throw new D("chainflip_broker_invalid_params");let T=x.get("integrations").chainflip?.brokerUrl||v("/chainflip/broker/channel"),H=await V.post(T,{json:N});try{let P=JA.safeParse(H);if(!P.success)throw new D("api_v2_invalid_response",P.error);return P.data}catch(P){throw new D("api_v2_invalid_response",P)}}async function PP(N){let{destinationAddress:A}=N;if(!A)throw new D("chainflip_broker_invalid_params");let T=v("/near/channel"),H=await V.post(T,{json:N});try{let P=ZA.safeParse(H);if(!P.success)throw new D("api_v2_invalid_response",P.error);return P.data}catch(P){throw new D("api_v2_invalid_response",P)}}function v(N){let{isDev:A,apiUrl:T,devApiUrl:H}=x.get("envs");return`${A?H:T}${N}`}function LP(N){let[A,T]=N.split(".");if(!hH.includes(A))return!0;let H=T.split("-"),P=H.length===1?void 0:H[H.length-1];return DN({chain:A,symbol:T})||!!P}var RP=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi");function uP(N){return N.filter((A)=>{return!RP.test(A.identifier)&&LP(A.identifier)})}async function FP(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=v(`/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 B=m.from({asset:I});F.push({chain:B.chain,identifier:B.toString(),providers:[],symbol:B.symbol,ticker:B.ticker})}catch{}return{buyAssets:F,sellAsset:N.sellAsset}}var fN={};cN(fN,{getThorchainQueue:()=>GP,getTcyStakers:()=>XP,getTcyStaker:()=>MP,getTcyClaimers:()=>QP,getTcyClaimer:()=>EP,getTNSPreferredAsset:()=>YP,getTHORNodeTNSDetails:()=>hA,getRunePoolProviderInfo:()=>SP,getRunePoolInfo:()=>UP,getNodes:()=>_P,getMimirInfo:()=>tP,getLastBlock:()=>gP,getInboundAddresses:()=>DP});import{MAYAConfig as IP,StagenetMAYAConfig as nP,StagenetTHORConfig as OP,THORConfig as BP}from"@swapkit/types";function k(N){let{isStagenet:A}=x.get("envs");switch(N){case"mayachain":return`${A?nP.nodeUrl:IP.nodeUrl}/mayachain`;default:return`${A?OP.nodeUrl:BP.nodeUrl}/thorchain`}}function $P(N){let A=N==="mayachain"?"mayaname":"thorname";return`${k(N)}/${A}`}function gP(N="thorchain"){return g.get(`${k(N)}/lastblock`)}function GP(N){return g.get(`${k(N)}/queue`)}function _P(N){return g.get(`${k(N)}/nodes`)}function tP(N){return g.get(`${k(N)}/mimir`)}function DP(N){return g.get(`${k(N)}/inbound_addresses`)}async function hA({type:N,name:A}){try{return await g.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 hA({name:A,type:N});if(!T.preferred_asset||T.preferred_asset===".")return;return m.from({asset:T.preferred_asset,asyncTokenLookup:!0})}function UP(N){return g.get(`${k(N)}/runepool`)}function SP({type:N,thorAddress:A}){return g.get(`${k(N)}/rune_provider/${A}`)}function MP({type:N,address:A}){return g.get(`${k(N)}/tcy_staker/${A}`)}function XP(N){return g.get(`${k(N)}/tcy_stakers`)}function EP({type:N,address:A}){return g.get(`${k(N)}/tcy_claimer/${A}`)}function QP(N){return g.get(`${k(N)}/tcy_claimers`)}var ER={...yN,mayachainMidgard:GA,thorchainMidgard:gA,thornode:fN};
5
+ export{bP as a,uN as b,bN as c,j as d,zN as e,aA as f,NT as g,AT as h,JN as i,TT as j,vP as k,q as l,x as m,D as n,g as o,sP as p,eP as q,aP as r,NL as s,l as t,vN as u,MT as v,i as w,uL as x,$L as y,PA as z,DN as A,YN as B,VN as C,d as D,IN as E,gL as F,GL as G,RA as H,YL as I,c as J,y as K,m as L,ZL as M,XN as N,_A as O,MA as P,xN as Q,XA as R,EA as S,QA as T,xA as U,CL as V,dL as W,hL as X,cL as Y,TN as Z,wA as _,rL as $,bA as aa,lL as ba,iL as ca,zA as da,SH as ea,JA as fa,tA as ga,sL as ha,ZA as ia,jA as ja,eL as ka,aL as la,pN as ma,oN as na,vA as oa,VA as pa,zH as qa,NR as ra,WA as sa,VH as ta,qA as ua,WH as va,AR as wa,qH as xa,mH as ya,mA as za,kA as Aa,KA as Ba,KH as Ca,pA as Da,oA as Ea,yA as Fa,HR as Ga,PR as Ha,oH as Ia,LR as Ja,RR as Ka,CH as La,uR as Ma,CA as Na,dH as Oa,FR as Pa,dA as Qa,ER as Ra};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{$ as WB,A as of,Aa as oB,B as df,Ba as dB,C as sf,Ca as sB,D as lf,Da as lB,E as nf,Ea as nB,F as pf,Fa as pB,G as tf,Ga as iB,H as af,Ha as tB,I as ef,Ia as aB,J as $B,Ja as eB,K as fB,Ka as $R,L as BB,La as fR,M as RB,Ma as BR,N as Q,Na as RR,O as gB,Oa as gR,P as xB,Pa as xR,Q as MB,Qa as MR,R as YB,Ra as YR,S as GB,T as zB,U as JB,V as LB,W as QB,X as XB,Y as ZB,Z as _B,_ as PB,a as Z,aa as jB,b as qf,ba as CB,c as Tf,ca as HB,d as Sf,da as VB,e as Af,ea as FB,f as m,fa as EB,g as Kf,ga as IB,h as t,ha as NB,i as $$,ia as qB,j as Uf,ja as TB,k as S,ka as SB,l as Df,la as AB,m as P,ma as KB,n as W,na as UB,o as Of,oa as DB,p as kf,pa as OB,q as yf,qa as kB,r as bf,ra as yB,s as mf,sa as bB,t as A,ta as mB,u as vf,ua as vB,v as wf,va as wB,w as cf,wa as cB,x as rf,xa as rB,y as hf,ya as hB,z as uf,za as uB}from"./chunk-4wzdfbhr.js";export*from"@swapkit/tokens";export*from"@swapkit/types";var v={average:1,fast:1.5,fastest:2};function I($="average"){let f=P.get("feeMultipliers");if(f&&f[$]!==void 0)return f[$];return v[$]}function w($="average"){let f=I($),B=10n,R=BigInt(Math.round(f*10));return{denominator:B,numerator:R}}function G$($,f="average"){let{numerator:B,denominator:R}=w(f);return $*B/R}function z$($,f="average",B=!1){let R=I(f),g=$*R;return B?Math.floor(g):g}import{Chain as N,EVMChains as c}from"@swapkit/types";function V($,f){if("index"in f)return[...$.slice(0,$.length-1),f.index];if("change"in f){let[B,R,g,,x]=$;return[B,R,g,f.change,x]}if("account"in f){let[B,R,,g,x]=$;return[B,R,f.account,g,x]}return $}function r([$,f,B,R,g],{allHardened:x}={}){let Y=x?"'":"",G=typeof g!=="number";if(typeof R!=="number")return`m/${$}'/${f}'/${B}'`;return`m/${$}'/${f}'/${B}'/${R}${Y}${G?"":`/${g}${Y}`}`}function X$({chain:$,index:f,addressIndex:B=0,type:R}){if(c.includes($)){if(R&&["legacy","account"].includes(R))return[44,60,0,f];if(R==="ledgerLive")return[44,60,f,0,B];return V(Z[$],{index:f})}if($===N.Solana){if(R==="account")return[44,501,0,f];return V(Z[$],{index:f})}let g=$===N.Litecoin?2:0;switch(R){case"nativeSegwitMiddleAccount":return[84,g,f,0,B];case"segwit":return[49,g,0,0,f];case"legacy":return[44,g,0,0,f];default:return V(Z[$],{index:f})}}function Z$($){let[f,B,R]=$.split("/").map((g)=>Number.parseInt(g,10));switch(B){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var _$=Object.keys(Z).reduce(($,f)=>{return $[f]=r(Z[f]),$},{});import{Chain as J,CosmosChains as h,EVMChains as u,getChainConfig as q,SubstrateChains as o,UTXOChains as d}from"@swapkit/types";import{match as T}from"ts-pattern";function C$({chain:$,txHash:f}){let{explorerUrl:B}=q($);return T($).with(...h,J.Solana,()=>`${B}/tx/${f.startsWith("0x")?f.slice(2):f}`).with(...u,...o,()=>`${B}/tx/${f.startsWith("0x")?f:`0x${f}`}`).with(...d,J.Radix,J.Tron,()=>`${B}/transaction/${f.toLowerCase()}`).with(J.Near,()=>`${B}/txns/${f}`).with(J.Ripple,()=>`${B}/transactions/${f}`).with(J.Sui,()=>`${B}/txblock/${f}`).with(J.Cardano,J.HyperCore,J.Ton,()=>`${B}/tx/${f}`).otherwise(()=>"")}function H$({chain:$,address:f}){let{explorerUrl:B}=q($);return T($).with(J.Solana,J.Sui,J.Radix,()=>`${B}/account/${f}`).otherwise(()=>`${B}/address/${f}`)}import{Chain as s,getChainConfig as l}from"@swapkit/types";function n({liquidityUnits:$,poolUnits:f,runeDepth:B}){let R=z($),g=z(f),x=z(B),Y=R.mul(x),G=g.mul(g).mul(2),M=g.mul(R).mul(2),L=R.mul(R),X=g.mul(g).mul(g);return Y.mul(G.sub(M).add(L)).div(X)}function p({liquidityUnits:$,poolUnits:f,assetDepth:B}){let R=z($),g=z(f),x=z(B),Y=R.mul(x),G=g.mul(g).mul(2),M=g.mul(R).mul(2),L=R.mul(R),X=Y.mul(G.sub(M).add(L)),_=g.mul(g).mul(g);return X.div(_)}function I$({percent:$,runeDepth:f,liquidityUnits:B,poolUnits:R}){return n({liquidityUnits:B,poolUnits:R,runeDepth:f}).mul($)}function N$({percent:$,assetDepth:f,liquidityUnits:B,poolUnits:R}){return p({assetDepth:f,liquidityUnits:B,poolUnits:R}).mul($)}function z($){return Q.fromBigInt(BigInt($),l(s.THORChain).baseDecimal)}function i({liquidityUnits:$,poolUnits:f,runeDepth:B,assetDepth:R}){return{assetAmount:z(R).mul($).div(f),runeAmount:z(B).mul($).div(f)}}function q$({liquidityUnits:$,poolUnits:f,runeDepth:B,assetDepth:R,percent:g}){return Object.fromEntries(Object.entries(i({assetDepth:R,liquidityUnits:$,poolUnits:f,runeDepth:B})).map(([x,Y])=>[x,Y.mul(g)]))}function T$({runeDepth:$,poolUnits:f,assetDepth:B,liquidityUnits:R,runeAmount:g,assetAmount:x}){let Y=new Q({decimal:8,value:$}),G=new Q({decimal:8,value:B}),M=new Q({decimal:8,value:f}),L=new Q({decimal:8,value:g}),X=new Q({decimal:8,value:x}),_=L.mul(G),F=X.mul(Y),D=L.mul(X),O=Y.mul(G),k=M.mul(_.add(F.add(D.mul(2)))),y=_.add(F.add(O.mul(2))),E=k.div(y),H=z(R).add(E);if(E.getBaseValue("number")===0)return H.div(M).getBaseValue("number");let b=M.add(H);return H.div(b).getBaseValue("number")}function S$({runeAmount:$,assetAmount:f,runeDepth:B,assetDepth:R}){if($==="0"||f==="0"||B==="0"||R==="0")return 0;let g=z(B),x=z(R),Y=z(f),G=z($),M=Y.mul(g).sub(x.mul(G)),L=x.mul(G).add(g.mul(x));return Math.abs(M.div(L).getBaseValue("number"))}import{Chain as j}from"@swapkit/types";import{match as a}from"ts-pattern";function O$({type:$,address:f}){return`${$}:${f}`}function k$({address:$,unbondAmount:f}){return`${"UNBOND"}:${$}:${f}`}function y$($){return C("POOL+",$)}function b$({chain:$,symbol:f,address:B,...R}){let g=e({chain:$,symbol:f}),x=B?`:${B}:`:":";return C(`${"+"}:${g}${x}`,R)}function m$({chain:$,symbol:f,ticker:B,basisPoints:R,targetAsset:g}){let x=$==="ETH"&&B!=="ETH"?`${B}-${f.slice(-3)}`:f,Y=g?`:${g}`:"";return`${"-"}:${$}.${x}:${R}${Y}`}function v$({basisPoints:$,...f}){return C(`${"POOL-"}:${$}`,f)}function w$({name:$,chain:f,address:B,owner:R}){let g=`${"~"}:${$}:${f}:${B}`,x=R?`:${R}`:"";return`${g}${x}`}function c$({name:$,chain:f,asset:B,payout:R,owner:g}){return`${"~"}:${$}:${f}:${R}:${g}:${B}`}function r$($,{address:f}){return`${$}:${f}`}function h$($,{unstakeBps:f,...B}){let R=f?`:${f}`:"",g=`${$}${R}`;return C(`${g}`,B)}function C($,{affiliateAddress:f,affiliateBasisPoints:B}={}){let R=`${$}${f?`:${f}:${B||0}`:""}`;return R.endsWith(":")?R.slice(0,-1):R}function e({chain:$,symbol:f}){return a($).with(j.Bitcoin,j.Dogecoin,j.Litecoin,()=>$.slice(0,1).toLowerCase()).with(j.BitcoinCash,()=>"c").otherwise(()=>`${$}.${f}`)}import{getChainConfig as K}from"@swapkit/types";function p$(){return typeof window.ethereum<"u"}function i$($){return f$().includes($)}function f$(){let $=window?.ethereum&&!window.ethereum?.isBraveWallet,f=window?.ctrl||window?.ethereum?.__XDEFI,B=window?.vultisig,R=window?.ethereum?.isBraveWallet,g=window?.ethereum?.isTrust||window?.trustwallet,x=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(B)M.push("VULTISIG");if(R)M.push("BRAVE");if(g)M.push("TRUSTWALLET_WEB");if(x)M.push("COINBASE_WEB");if(x$())M.push("OKX_MOBILE");if(Y)M.push("BITGET");if(G)M.push("ONEKEY");return M}async function B$($,f,B){let R=K(f);try{await U({method:"wallet_switchEthereumChain",params:[{chainId:R.chainIdHex}],provider:$})}catch(g){if(!B)throw new W("helpers_failed_to_switch_network",{error:g,reason:"networkParams not provided"});await g$($,B)}}function t$({chains:$,supportedChains:f,walletType:B}){let R=$.filter((x)=>!x||f.includes(x));if(R.length===0)throw new W("wallet_chain_not_supported",{chain:$.join(", "),wallet:B});let g=$.filter((x)=>!f.includes(x));return A({condition:g.length>0,id:`wallet_chain_not_supported_${B}`,warning:`${B} wallet does not support the following chains: ${g.join(", ")}. These chains will be ignored.`}),R}function R$($,f,B){return async(...R)=>{let{chainIdHex:g}=K(B);if((await f.getNetwork()).chainId.toString()===g)return $(...R);try{await B$(f,B)}catch(x){throw new W({errorKey:"helpers_failed_to_switch_network",info:{error:x}})}return $(...R)}}function a$({toolbox:$,chain:f,provider:B=window.ethereum,methodNames:R=[]}){let x=[...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=R$(M,B,f);return{...Y,[G]:L}},{});return{...$,...x}}function g$($,f){return U({method:"wallet_addEthereumChain",params:[f],provider:$})}function e$($){window.ethereum?.on("accountsChanged",()=>$()),window.ctrl?.ethereum.on("accountsChanged",()=>$())}function $f(){let{isTrust:$,isBraveWallet:f,__XDEFI:B,overrideIsMetaMask:R,selectedProvider:g}=window?.ethereum||{};if($)return"TRUSTWALLET_WEB";if(f)return"BRAVE";if(R&&g?.isCoinbaseWallet)return"COINBASE_WEB";if(B)return"CTRL";if(window?.$onekey?.ethereum)return"ONEKEY";return"METAMASK"}function ff(){let $=[];function f(R){if($.map((g)=>g.info.uuid).includes(R.detail.info.uuid))return;$.push(R.detail)}window.addEventListener("eip6963:announceProvider",f),window.dispatchEvent(new Event("eip6963:requestProvider"));function B(){window.removeEventListener("eip6963:announceProvider",f)}return{providers:$,removeEIP6963EventListener:B}}function x$(){let $=navigator.userAgent,f=/iphone|ipad|ipod|ios/i.test($),B=/android|XiaoMi|MiuiBrowser/i.test($),R=f||B,g=/OKApp/i.test($);return R&&g}function U({provider:$,params:f,method:B}){if(!$?.send)throw new W("helpers_not_found_provider");let R=f?Array.isArray(f)?f:[f]:[];return $.send(B,R)}function Bf($,f){if(!P.get("v3SwapFlow")?.enabled)return!1;return S[f]?.includes($)??!1}export{bf as wrapWithThrow,R$ as wrapMethodWithNetworkSwitch,A as warnOnce,ef as validateTNS,af as validateIdentifier,V as updateDerivationPath,B$ as switchEVMWalletNetwork,Df as swapKitConfigStore,Bf as supportsV3SwapFlow,gB as signWidgetRequest,U as providerRequest,a$ as prepareNetworkSwitch,nf as parseSymbolForAddress,x$ as okxMobileEnabled,f$ as listWeb3EVMWallets,p$ as isWeb3Detected,of as isGasAsset,i$ as isDetected,rf as initializeRPCUrlsWithFallback,Z$ as getWalletFormatFor,pf as getTokenLogoURI,kf as getTHORNameCost,q$ as getSymmetricWithdraw,i as getSymmetricPoolShare,wf as getRPCUrlSync,cf as getRPCUrl,RB as getMinAmountByChain,m$ as getMemoForWithdraw,k$ as getMemoForUnbond,h$ as getMemoForTcyStake,r$ as getMemoForTcyClaim,v$ as getMemoForRunePoolWithdraw,y$ as getMemoForRunePoolDeposit,w$ as getMemoForNameRegister,c$ as getMemoForNamePreferredAssetRegister,O$ as getMemoForLeaveAndBond,b$ as getMemoForDeposit,yf as getMAYANameCost,S$ as getLiquiditySlippage,w as getFeeMultiplierAsBigInt,I as getFeeMultiplier,C$ as getExplorerTxUrl,H$ as getExplorerAddressUrl,T$ as getEstimatedPoolShare,$f as getETHDefaultWallet,ff as getEIP6963Wallets,X$ as getDerivationPathFor,df as getCommonAssetInfo,mf as getChainIdentifier,I$ as getAsymmetricRuneWithdrawAmount,n as getAsymmetricRuneShare,N$ as getAsymmetricAssetWithdrawAmount,p as getAsymmetricAssetShare,sf as getAssetType,$B as formatBigIntToSafeValue,tf as findAssetBy,t$ as filterSupportedChains,uf as fetchTokenInfo,r as derivationPathToString,lf as assetFromString,G$ as applyFeeMultiplierToBigInt,z$ as applyFeeMultiplier,g$ as addEVMWalletNetwork,e$ as addAccountsChangedCallback,vf as _rpcCache,Tf as WarningCodeEnum,$$ as WalletOption,S as V3SwapFlowSupport,YB as TxnType,zB as TxnStatus,OB as TronTransactionSchema,SB as TransactionSchema,AB as TransactionDTOSchema,JB as TrackingStatus,QB as TrackingRequestSchema,XB as TrackingRequestQuerySchema,TB as TrackerResponseSchema,LB as TokenSchema,WB as TokenDetailsMetadataSchema,vB as TONTransactionSchema,BR as SwapToResponseSchema,$R as SwapToRequestSchema,fR as SwapToAssetSchema,MR as SwapRouteV2ResponseSchema,Q as SwapKitNumber,W as SwapKitError,YR as SwapKitApi,mB as StarknetTransactionSchema,P as SKConfig,dB as RouteQuoteWarningSchema,MB as RouteQuoteTxType,gR as RouteQuoteProviderErrorSchema,oB as RouteQuoteMetadataV2Schema,uB as RouteQuoteMetadataSchema,rB as RouteQuoteMetadataAssetSchema,cB as RouteLegWithoutAddressesSchema,wB as RouteLegSchema,Of as RequestClient,eB as QuoteV3ResponseSchema,xR as QuoteV2ResponseSchema,RR as QuoteRouteV2Response,lB as QuoteResponseSchema,sB as QuoteResponseRouteItem,CB as QuoteRequestSchema,Sf as ProviderName,GB as ProviderAction,xB as PriorityLabel,jB as PriceResponseSchema,HB as PriceRequestSchema,Z as NetworkDerivationPath,qB as NearSwapResponseSchema,NB as NearDepositChannelResultSchema,IB as NearDepositChannelParamsSchema,t as MemoType,Uf as LedgerErrorCode,nB as GasSchema,pB as GasResponseSchema,KB as FeesSchema,Af as FeeTypeEnum,m as FeeOption,UB as EstimatedTimeSchema,qf as ErrorCode,DB as EVMTransactionSchema,yB as EVMTransactionDetailsSchema,kB as EVMTransactionDetailsParamsSchema,_$ as DerivationPath,EB as DepositChannelResponseSchema,VB as DepositChannelParamsSchema,v as DEFAULT_FEE_MULTIPLIERS,bB as CosmosTransactionSchema,hf as CommonAssetStrings,PB as CoinGeckoMetadataSchema,hB as ChainflipMetadataSchema,FB as BrokerDepositChannelParamsSchema,fB as BigIntArithmetics,_B as AssetValueSchema,BB as AssetValue,tB as ApproveResponseSchema,iB as ApproveRequestParams,Kf as ApproveMode,aB as ApprovalTransactionSchema,ZB as ApiV2ErrorSchema};
1
+ import{$ as WB,A as of,Aa as oB,B as df,Ba as dB,C as sf,Ca as sB,D as lf,Da as lB,E as nf,Ea as nB,F as pf,Fa as pB,G as tf,Ga as iB,H as af,Ha as tB,I as ef,Ia as aB,J as $B,Ja as eB,K as fB,Ka as $R,L as BB,La as fR,M as RB,Ma as BR,N as Q,Na as RR,O as gB,Oa as gR,P as xB,Pa as xR,Q as MB,Qa as MR,R as YB,Ra as YR,S as GB,T as zB,U as JB,V as LB,W as QB,X as XB,Y as ZB,Z as _B,_ as PB,a as Z,aa as jB,b as qf,ba as CB,c as Tf,ca as HB,d as Sf,da as VB,e as Af,ea as FB,f as m,fa as EB,g as Kf,ga as IB,h as t,ha as NB,i as $$,ia as qB,j as Uf,ja as TB,k as S,ka as SB,l as Df,la as AB,m as P,ma as KB,n as W,na as UB,o as Of,oa as DB,p as kf,pa as OB,q as yf,qa as kB,r as bf,ra as yB,s as mf,sa as bB,t as A,ta as mB,u as vf,ua as vB,v as wf,va as wB,w as cf,wa as cB,x as rf,xa as rB,y as hf,ya as hB,z as uf,za as uB}from"./chunk-71e6bysh.js";export*from"@swapkit/tokens";export*from"@swapkit/types";var v={average:1,fast:1.5,fastest:2};function I($="average"){let f=P.get("feeMultipliers");if(f&&f[$]!==void 0)return f[$];return v[$]}function w($="average"){let f=I($),B=10n,R=BigInt(Math.round(f*10));return{denominator:B,numerator:R}}function G$($,f="average"){let{numerator:B,denominator:R}=w(f);return $*B/R}function z$($,f="average",B=!1){let R=I(f),g=$*R;return B?Math.floor(g):g}import{Chain as N,EVMChains as c}from"@swapkit/types";function V($,f){if("index"in f)return[...$.slice(0,$.length-1),f.index];if("change"in f){let[B,R,g,,x]=$;return[B,R,g,f.change,x]}if("account"in f){let[B,R,,g,x]=$;return[B,R,f.account,g,x]}return $}function r([$,f,B,R,g],{allHardened:x}={}){let Y=x?"'":"",G=typeof g!=="number";if(typeof R!=="number")return`m/${$}'/${f}'/${B}'`;return`m/${$}'/${f}'/${B}'/${R}${Y}${G?"":`/${g}${Y}`}`}function X$({chain:$,index:f,addressIndex:B=0,type:R}){if(c.includes($)){if(R&&["legacy","account"].includes(R))return[44,60,0,f];if(R==="ledgerLive")return[44,60,f,0,B];return V(Z[$],{index:f})}if($===N.Solana){if(R==="account")return[44,501,0,f];return V(Z[$],{index:f})}let g=$===N.Litecoin?2:0;switch(R){case"nativeSegwitMiddleAccount":return[84,g,f,0,B];case"segwit":return[49,g,0,0,f];case"legacy":return[44,g,0,0,f];default:return V(Z[$],{index:f})}}function Z$($){let[f,B,R]=$.split("/").map((g)=>Number.parseInt(g,10));switch(B){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var _$=Object.keys(Z).reduce(($,f)=>{return $[f]=r(Z[f]),$},{});import{Chain as J,CosmosChains as h,EVMChains as u,getChainConfig as q,SubstrateChains as o,UTXOChains as d}from"@swapkit/types";import{match as T}from"ts-pattern";function C$({chain:$,txHash:f}){let{explorerUrl:B}=q($);return T($).with(...h,J.Solana,()=>`${B}/tx/${f.startsWith("0x")?f.slice(2):f}`).with(...u,...o,()=>`${B}/tx/${f.startsWith("0x")?f:`0x${f}`}`).with(...d,J.Radix,J.Tron,()=>`${B}/transaction/${f.toLowerCase()}`).with(J.Near,()=>`${B}/txns/${f}`).with(J.Ripple,()=>`${B}/transactions/${f}`).with(J.Sui,()=>`${B}/txblock/${f}`).with(J.Cardano,J.HyperCore,J.Ton,()=>`${B}/tx/${f}`).otherwise(()=>"")}function H$({chain:$,address:f}){let{explorerUrl:B}=q($);return T($).with(J.Solana,J.Sui,J.Radix,()=>`${B}/account/${f}`).otherwise(()=>`${B}/address/${f}`)}import{Chain as s,getChainConfig as l}from"@swapkit/types";function n({liquidityUnits:$,poolUnits:f,runeDepth:B}){let R=z($),g=z(f),x=z(B),Y=R.mul(x),G=g.mul(g).mul(2),M=g.mul(R).mul(2),L=R.mul(R),X=g.mul(g).mul(g);return Y.mul(G.sub(M).add(L)).div(X)}function p({liquidityUnits:$,poolUnits:f,assetDepth:B}){let R=z($),g=z(f),x=z(B),Y=R.mul(x),G=g.mul(g).mul(2),M=g.mul(R).mul(2),L=R.mul(R),X=Y.mul(G.sub(M).add(L)),_=g.mul(g).mul(g);return X.div(_)}function I$({percent:$,runeDepth:f,liquidityUnits:B,poolUnits:R}){return n({liquidityUnits:B,poolUnits:R,runeDepth:f}).mul($)}function N$({percent:$,assetDepth:f,liquidityUnits:B,poolUnits:R}){return p({assetDepth:f,liquidityUnits:B,poolUnits:R}).mul($)}function z($){return Q.fromBigInt(BigInt($),l(s.THORChain).baseDecimal)}function i({liquidityUnits:$,poolUnits:f,runeDepth:B,assetDepth:R}){return{assetAmount:z(R).mul($).div(f),runeAmount:z(B).mul($).div(f)}}function q$({liquidityUnits:$,poolUnits:f,runeDepth:B,assetDepth:R,percent:g}){return Object.fromEntries(Object.entries(i({assetDepth:R,liquidityUnits:$,poolUnits:f,runeDepth:B})).map(([x,Y])=>[x,Y.mul(g)]))}function T$({runeDepth:$,poolUnits:f,assetDepth:B,liquidityUnits:R,runeAmount:g,assetAmount:x}){let Y=new Q({decimal:8,value:$}),G=new Q({decimal:8,value:B}),M=new Q({decimal:8,value:f}),L=new Q({decimal:8,value:g}),X=new Q({decimal:8,value:x}),_=L.mul(G),F=X.mul(Y),D=L.mul(X),O=Y.mul(G),k=M.mul(_.add(F.add(D.mul(2)))),y=_.add(F.add(O.mul(2))),E=k.div(y),H=z(R).add(E);if(E.getBaseValue("number")===0)return H.div(M).getBaseValue("number");let b=M.add(H);return H.div(b).getBaseValue("number")}function S$({runeAmount:$,assetAmount:f,runeDepth:B,assetDepth:R}){if($==="0"||f==="0"||B==="0"||R==="0")return 0;let g=z(B),x=z(R),Y=z(f),G=z($),M=Y.mul(g).sub(x.mul(G)),L=x.mul(G).add(g.mul(x));return Math.abs(M.div(L).getBaseValue("number"))}import{Chain as j}from"@swapkit/types";import{match as a}from"ts-pattern";function O$({type:$,address:f}){return`${$}:${f}`}function k$({address:$,unbondAmount:f}){return`${"UNBOND"}:${$}:${f}`}function y$($){return C("POOL+",$)}function b$({chain:$,symbol:f,address:B,...R}){let g=e({chain:$,symbol:f}),x=B?`:${B}:`:":";return C(`${"+"}:${g}${x}`,R)}function m$({chain:$,symbol:f,ticker:B,basisPoints:R,targetAsset:g}){let x=$==="ETH"&&B!=="ETH"?`${B}-${f.slice(-3)}`:f,Y=g?`:${g}`:"";return`${"-"}:${$}.${x}:${R}${Y}`}function v$({basisPoints:$,...f}){return C(`${"POOL-"}:${$}`,f)}function w$({name:$,chain:f,address:B,owner:R}){let g=`${"~"}:${$}:${f}:${B}`,x=R?`:${R}`:"";return`${g}${x}`}function c$({name:$,chain:f,asset:B,payout:R,owner:g}){return`${"~"}:${$}:${f}:${R}:${g}:${B}`}function r$($,{address:f}){return`${$}:${f}`}function h$($,{unstakeBps:f,...B}){let R=f?`:${f}`:"",g=`${$}${R}`;return C(`${g}`,B)}function C($,{affiliateAddress:f,affiliateBasisPoints:B}={}){let R=`${$}${f?`:${f}:${B||0}`:""}`;return R.endsWith(":")?R.slice(0,-1):R}function e({chain:$,symbol:f}){return a($).with(j.Bitcoin,j.Dogecoin,j.Litecoin,()=>$.slice(0,1).toLowerCase()).with(j.BitcoinCash,()=>"c").otherwise(()=>`${$}.${f}`)}import{getChainConfig as K}from"@swapkit/types";function p$(){return typeof window.ethereum<"u"}function i$($){return f$().includes($)}function f$(){let $=window?.ethereum&&!window.ethereum?.isBraveWallet,f=window?.ctrl||window?.ethereum?.__XDEFI,B=window?.vultisig,R=window?.ethereum?.isBraveWallet,g=window?.ethereum?.isTrust||window?.trustwallet,x=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(B)M.push("VULTISIG");if(R)M.push("BRAVE");if(g)M.push("TRUSTWALLET_WEB");if(x)M.push("COINBASE_WEB");if(x$())M.push("OKX_MOBILE");if(Y)M.push("BITGET");if(G)M.push("ONEKEY");return M}async function B$($,f,B){let R=K(f);try{await U({method:"wallet_switchEthereumChain",params:[{chainId:R.chainIdHex}],provider:$})}catch(g){if(!B)throw new W("helpers_failed_to_switch_network",{error:g,reason:"networkParams not provided"});await g$($,B)}}function t$({chains:$,supportedChains:f,walletType:B}){let R=$.filter((x)=>!x||f.includes(x));if(R.length===0)throw new W("wallet_chain_not_supported",{chain:$.join(", "),wallet:B});let g=$.filter((x)=>!f.includes(x));return A({condition:g.length>0,id:`wallet_chain_not_supported_${B}`,warning:`${B} wallet does not support the following chains: ${g.join(", ")}. These chains will be ignored.`}),R}function R$($,f,B){return async(...R)=>{let{chainIdHex:g}=K(B);if((await f.getNetwork()).chainId.toString()===g)return $(...R);try{await B$(f,B)}catch(x){throw new W({errorKey:"helpers_failed_to_switch_network",info:{error:x}})}return $(...R)}}function a$({toolbox:$,chain:f,provider:B=window.ethereum,methodNames:R=[]}){let x=[...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=R$(M,B,f);return{...Y,[G]:L}},{});return{...$,...x}}function g$($,f){return U({method:"wallet_addEthereumChain",params:[f],provider:$})}function e$($){window.ethereum?.on("accountsChanged",()=>$()),window.ctrl?.ethereum.on("accountsChanged",()=>$())}function $f(){let{isTrust:$,isBraveWallet:f,__XDEFI:B,overrideIsMetaMask:R,selectedProvider:g}=window?.ethereum||{};if($)return"TRUSTWALLET_WEB";if(f)return"BRAVE";if(R&&g?.isCoinbaseWallet)return"COINBASE_WEB";if(B)return"CTRL";if(window?.$onekey?.ethereum)return"ONEKEY";return"METAMASK"}function ff(){let $=[];function f(R){if($.map((g)=>g.info.uuid).includes(R.detail.info.uuid))return;$.push(R.detail)}window.addEventListener("eip6963:announceProvider",f),window.dispatchEvent(new Event("eip6963:requestProvider"));function B(){window.removeEventListener("eip6963:announceProvider",f)}return{providers:$,removeEIP6963EventListener:B}}function x$(){let $=navigator.userAgent,f=/iphone|ipad|ipod|ios/i.test($),B=/android|XiaoMi|MiuiBrowser/i.test($),R=f||B,g=/OKApp/i.test($);return R&&g}function U({provider:$,params:f,method:B}){if(!$?.send)throw new W("helpers_not_found_provider");let R=f?Array.isArray(f)?f:[f]:[];return $.send(B,R)}function Bf($,f){if(!P.get("v3SwapFlow")?.enabled)return!1;return S[f]?.includes($)??!1}export{bf as wrapWithThrow,R$ as wrapMethodWithNetworkSwitch,A as warnOnce,ef as validateTNS,af as validateIdentifier,V as updateDerivationPath,B$ as switchEVMWalletNetwork,Df as swapKitConfigStore,Bf as supportsV3SwapFlow,gB as signWidgetRequest,U as providerRequest,a$ as prepareNetworkSwitch,nf as parseSymbolForAddress,x$ as okxMobileEnabled,f$ as listWeb3EVMWallets,p$ as isWeb3Detected,of as isGasAsset,i$ as isDetected,rf as initializeRPCUrlsWithFallback,Z$ as getWalletFormatFor,pf as getTokenLogoURI,kf as getTHORNameCost,q$ as getSymmetricWithdraw,i as getSymmetricPoolShare,wf as getRPCUrlSync,cf as getRPCUrl,RB as getMinAmountByChain,m$ as getMemoForWithdraw,k$ as getMemoForUnbond,h$ as getMemoForTcyStake,r$ as getMemoForTcyClaim,v$ as getMemoForRunePoolWithdraw,y$ as getMemoForRunePoolDeposit,w$ as getMemoForNameRegister,c$ as getMemoForNamePreferredAssetRegister,O$ as getMemoForLeaveAndBond,b$ as getMemoForDeposit,yf as getMAYANameCost,S$ as getLiquiditySlippage,w as getFeeMultiplierAsBigInt,I as getFeeMultiplier,C$ as getExplorerTxUrl,H$ as getExplorerAddressUrl,T$ as getEstimatedPoolShare,$f as getETHDefaultWallet,ff as getEIP6963Wallets,X$ as getDerivationPathFor,df as getCommonAssetInfo,mf as getChainIdentifier,I$ as getAsymmetricRuneWithdrawAmount,n as getAsymmetricRuneShare,N$ as getAsymmetricAssetWithdrawAmount,p as getAsymmetricAssetShare,sf as getAssetType,$B as formatBigIntToSafeValue,tf as findAssetBy,t$ as filterSupportedChains,uf as fetchTokenInfo,r as derivationPathToString,lf as assetFromString,G$ as applyFeeMultiplierToBigInt,z$ as applyFeeMultiplier,g$ as addEVMWalletNetwork,e$ as addAccountsChangedCallback,vf as _rpcCache,Tf as WarningCodeEnum,$$ as WalletOption,S as V3SwapFlowSupport,YB as TxnType,zB as TxnStatus,OB as TronTransactionSchema,SB as TransactionSchema,AB as TransactionDTOSchema,JB as TrackingStatus,QB as TrackingRequestSchema,XB as TrackingRequestQuerySchema,TB as TrackerResponseSchema,LB as TokenSchema,WB as TokenDetailsMetadataSchema,vB as TONTransactionSchema,BR as SwapToResponseSchema,$R as SwapToRequestSchema,fR as SwapToAssetSchema,MR as SwapRouteV2ResponseSchema,Q as SwapKitNumber,W as SwapKitError,YR as SwapKitApi,mB as StarknetTransactionSchema,P as SKConfig,dB as RouteQuoteWarningSchema,MB as RouteQuoteTxType,gR as RouteQuoteProviderErrorSchema,oB as RouteQuoteMetadataV2Schema,uB as RouteQuoteMetadataSchema,rB as RouteQuoteMetadataAssetSchema,cB as RouteLegWithoutAddressesSchema,wB as RouteLegSchema,Of as RequestClient,eB as QuoteV3ResponseSchema,xR as QuoteV2ResponseSchema,RR as QuoteRouteV2Response,lB as QuoteResponseSchema,sB as QuoteResponseRouteItem,CB as QuoteRequestSchema,Sf as ProviderName,GB as ProviderAction,xB as PriorityLabel,jB as PriceResponseSchema,HB as PriceRequestSchema,Z as NetworkDerivationPath,qB as NearSwapResponseSchema,NB as NearDepositChannelResultSchema,IB as NearDepositChannelParamsSchema,t as MemoType,Uf as LedgerErrorCode,nB as GasSchema,pB as GasResponseSchema,KB as FeesSchema,Af as FeeTypeEnum,m as FeeOption,UB as EstimatedTimeSchema,qf as ErrorCode,DB as EVMTransactionSchema,yB as EVMTransactionDetailsSchema,kB as EVMTransactionDetailsParamsSchema,_$ as DerivationPath,EB as DepositChannelResponseSchema,VB as DepositChannelParamsSchema,v as DEFAULT_FEE_MULTIPLIERS,bB as CosmosTransactionSchema,hf as CommonAssetStrings,PB as CoinGeckoMetadataSchema,hB as ChainflipMetadataSchema,FB as BrokerDepositChannelParamsSchema,fB as BigIntArithmetics,_B as AssetValueSchema,BB as AssetValue,tB as ApproveResponseSchema,iB as ApproveRequestParams,Kf as ApproveMode,aB as ApprovalTransactionSchema,ZB as ApiV2ErrorSchema};
@@ -499,6 +499,10 @@ declare const errorCodes: {
499
499
  readonly helpers_invalid_response: 70011;
500
500
  readonly helpers_chain_no_public_or_set_rpc_url: 70012;
501
501
  readonly helpers_chain_rpc_connection_failed: 70013;
502
+ /**
503
+ * MCP server
504
+ */
505
+ readonly mcp_wallet_not_configured: 90001;
502
506
  /**
503
507
  * Anything else
504
508
  */
@@ -1006,11 +1010,17 @@ export declare class SwapKitError extends Error {
1006
1010
  readonly helpers_invalid_response: 70011;
1007
1011
  readonly helpers_chain_no_public_or_set_rpc_url: 70012;
1008
1012
  readonly helpers_chain_rpc_connection_failed: 70013;
1013
+ /**
1014
+ * MCP server
1015
+ */
1016
+ readonly mcp_wallet_not_configured: 90001;
1009
1017
  /**
1010
1018
  * Anything else
1011
1019
  */
1012
1020
  readonly not_implemented: 99999;
1013
1021
  };
1022
+ readonly errorKey: ErrorKeys;
1023
+ readonly info?: Record<string, any>;
1014
1024
  constructor(errorOrErrorKey: ErrorKeys | {
1015
1025
  errorKey: ErrorKeys;
1016
1026
  info?: Record<string, any>;
@@ -1 +1 @@
1
- {"version":3,"file":"swapKitError.d.ts","sourceRoot":"","sources":["../../../src/modules/swapKitError.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,QAAA,MAAM,UAAU;IACd;;OAEG;;;;;;;;;;;IAWH;;OAEG;;;;;;;;;;;;;;;;;IAiBH;;OAEG;;;;;;;;;IASH;;OAEG;;;;;;;;;;;;;;;;;;IAkBH;;OAEG;;;;;;;IAOH;;OAEG;;;;;;;;;;;;;;;;;;;;;;;;;IAyBH;;OAEG;;IAEH;;OAEG;;;;;IAKH;;OAEG;;;;;;;IAOH;;OAEG;;;;;;;IAOH;;OAEG;;;IAGH;;OAEG;;IAEH;;OAEG;;;;;;IAMH;;OAEG;;;;;;;;;;;;;;;;;;;IAmBH;;OAEG;;;;IAIH;;OAEG;;;;;;;;;IASH;;OAEG;;;IAGH;;OAEG;;;;;IAKH;;OAEG;;;;;IAKH;;OAEG;;;;;;;;;IASH;;OAEG;IAEH;;OAEG;;;;;IAKH;;OAEG;;;;IAIH;;OAEG;;;IAGH;;OAEG;;;;;IAKH;;OAEG;;IAEH;;OAEG;;;;;IAMH;;OAEG;;;;;;;IAOH;;OAEG;;;IAIH;;OAEG;;;IAGH;;OAEG;;;;;;;;IAQH;;OAEG;;;;IAIH;;OAEG;;;;;;IAMH;;OAEG;;;;;;;;;IASH;;OAEG;;;;;;;;;;;;;;;;;;IAkBH;;OAEG;;;;;;;;;;;;;;;IAeH;;OAEG;;IAEH;;OAEG;;;IAGH;;OAEG;;IAEH;;OAEG;;;;;;;;IAQH;;OAEG;;;;;;;;;;;IAWH;;OAEG;;IAEH;;OAEG;;IAEH;;OAEG;;;;;;;;;;;;;;IAcH;;OAEG;;;;;;;;;;;;IAYH;;OAEG;;;;;;IAMH;;OAEG;;;;;;IAMH;;OAEG;;;;;;;;;;;IAWH;;OAEG;;;;;;;IAOH;;OAEG;;;IAGH;;OAEG;;;;;;IAMH;;OAEG;;IAEH;;OAEG;;;IAGH;;OAEG;;;;IAIH;;OAEG;;;;;;;;;;;;;;IAcH;;OAEG;;CAEK,CAAC;AAEX,MAAM,MAAM,SAAS,GAAG,MAAM,OAAO,UAAU,CAAC;AAMhD,qBAAa,YAAa,SAAQ,KAAK;IACrC,MAAM,CAAC,SAAS;QAngBhB;;WAEG;;;;;;;;;;;QAWH;;WAEG;;;;;;;;;;;;;;;;;QAiBH;;WAEG;;;;;;;;;QASH;;WAEG;;;;;;;;;;;;;;;;;;QAkBH;;WAEG;;;;;;;QAOH;;WAEG;;;;;;;;;;;;;;;;;;;;;;;;;QAyBH;;WAEG;;QAEH;;WAEG;;;;;QAKH;;WAEG;;;;;;;QAOH;;WAEG;;;;;;;QAOH;;WAEG;;;QAGH;;WAEG;;QAEH;;WAEG;;;;;;QAMH;;WAEG;;;;;;;;;;;;;;;;;;;QAmBH;;WAEG;;;;QAIH;;WAEG;;;;;;;;;QASH;;WAEG;;;QAGH;;WAEG;;;;;QAKH;;WAEG;;;;;QAKH;;WAEG;;;;;;;;;QASH;;WAEG;QAEH;;WAEG;;;;;QAKH;;WAEG;;;;QAIH;;WAEG;;;QAGH;;WAEG;;;;;QAKH;;WAEG;;QAEH;;WAEG;;;;;QAMH;;WAEG;;;;;;;QAOH;;WAEG;;;QAIH;;WAEG;;;QAGH;;WAEG;;;;;;;;QAQH;;WAEG;;;;QAIH;;WAEG;;;;;;QAMH;;WAEG;;;;;;;;;QASH;;WAEG;;;;;;;;;;;;;;;;;;QAkBH;;WAEG;;;;;;;;;;;;;;;QAeH;;WAEG;;QAEH;;WAEG;;;QAGH;;WAEG;;QAEH;;WAEG;;;;;;;;QAQH;;WAEG;;;;;;;;;;;QAWH;;WAEG;;QAEH;;WAEG;;QAEH;;WAEG;;;;;;;;;;;;;;QAcH;;WAEG;;;;;;;;;;;;QAYH;;WAEG;;;;;;QAMH;;WAEG;;;;;;QAMH;;WAEG;;;;;;;;;;;QAWH;;WAEG;;;;;;;QAOH;;WAEG;;;QAGH;;WAEG;;;;;;QAMH;;WAEG;;QAEH;;WAEG;;;QAGH;;WAEG;;;;QAIH;;WAEG;;;;;;;;;;;;;;QAcH;;WAEG;;MAW2B;gBAG5B,eAAe,EAAE,SAAS,GAAG;QAAE,QAAQ,EAAE,SAAS,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;KAAE,EAChF,iBAAiB,CAAC,EAAE,GAAG;CAuB1B"}
1
+ {"version":3,"file":"swapKitError.d.ts","sourceRoot":"","sources":["../../../src/modules/swapKitError.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,QAAA,MAAM,UAAU;IACd;;OAEG;;;;;;;;;;;IAWH;;OAEG;;;;;;;;;;;;;;;;;IAiBH;;OAEG;;;;;;;;;IASH;;OAEG;;;;;;;;;;;;;;;;;;IAkBH;;OAEG;;;;;;;IAOH;;OAEG;;;;;;;;;;;;;;;;;;;;;;;;;IAyBH;;OAEG;;IAEH;;OAEG;;;;;IAKH;;OAEG;;;;;;;IAOH;;OAEG;;;;;;;IAOH;;OAEG;;;IAGH;;OAEG;;IAEH;;OAEG;;;;;;IAMH;;OAEG;;;;;;;;;;;;;;;;;;;IAmBH;;OAEG;;;;IAIH;;OAEG;;;;;;;;;IASH;;OAEG;;;IAGH;;OAEG;;;;;IAKH;;OAEG;;;;;IAKH;;OAEG;;;;;;;;;IASH;;OAEG;IAEH;;OAEG;;;;;IAKH;;OAEG;;;;IAIH;;OAEG;;;IAGH;;OAEG;;;;;IAKH;;OAEG;;IAEH;;OAEG;;;;;IAMH;;OAEG;;;;;;;IAOH;;OAEG;;;IAIH;;OAEG;;;IAGH;;OAEG;;;;;;;;IAQH;;OAEG;;;;IAIH;;OAEG;;;;;;IAMH;;OAEG;;;;;;;;;IASH;;OAEG;;;;;;;;;;;;;;;;;;IAkBH;;OAEG;;;;;;;;;;;;;;;IAeH;;OAEG;;IAEH;;OAEG;;;IAGH;;OAEG;;IAEH;;OAEG;;;;;;;;IAQH;;OAEG;;;;;;;;;;;IAWH;;OAEG;;IAEH;;OAEG;;IAEH;;OAEG;;;;;;;;;;;;;;IAcH;;OAEG;;;;;;;;;;;;IAYH;;OAEG;;;;;;IAMH;;OAEG;;;;;;IAMH;;OAEG;;;;;;;;;;;IAWH;;OAEG;;;;;;;IAOH;;OAEG;;;IAGH;;OAEG;;;;;;IAMH;;OAEG;;IAEH;;OAEG;;;IAGH;;OAEG;;;;IAIH;;OAEG;;;;;;;;;;;;;;IAcH;;OAEG;;IAEH;;OAEG;;CAEK,CAAC;AAEX,MAAM,MAAM,SAAS,GAAG,MAAM,OAAO,UAAU,CAAC;AAMhD,qBAAa,YAAa,SAAQ,KAAK;IACrC,MAAM,CAAC,SAAS;QAvgBhB;;WAEG;;;;;;;;;;;QAWH;;WAEG;;;;;;;;;;;;;;;;;QAiBH;;WAEG;;;;;;;;;QASH;;WAEG;;;;;;;;;;;;;;;;;;QAkBH;;WAEG;;;;;;;QAOH;;WAEG;;;;;;;;;;;;;;;;;;;;;;;;;QAyBH;;WAEG;;QAEH;;WAEG;;;;;QAKH;;WAEG;;;;;;;QAOH;;WAEG;;;;;;;QAOH;;WAEG;;;QAGH;;WAEG;;QAEH;;WAEG;;;;;;QAMH;;WAEG;;;;;;;;;;;;;;;;;;;QAmBH;;WAEG;;;;QAIH;;WAEG;;;;;;;;;QASH;;WAEG;;;QAGH;;WAEG;;;;;QAKH;;WAEG;;;;;QAKH;;WAEG;;;;;;;;;QASH;;WAEG;QAEH;;WAEG;;;;;QAKH;;WAEG;;;;QAIH;;WAEG;;;QAGH;;WAEG;;;;;QAKH;;WAEG;;QAEH;;WAEG;;;;;QAMH;;WAEG;;;;;;;QAOH;;WAEG;;;QAIH;;WAEG;;;QAGH;;WAEG;;;;;;;;QAQH;;WAEG;;;;QAIH;;WAEG;;;;;;QAMH;;WAEG;;;;;;;;;QASH;;WAEG;;;;;;;;;;;;;;;;;;QAkBH;;WAEG;;;;;;;;;;;;;;;QAeH;;WAEG;;QAEH;;WAEG;;;QAGH;;WAEG;;QAEH;;WAEG;;;;;;;;QAQH;;WAEG;;;;;;;;;;;QAWH;;WAEG;;QAEH;;WAEG;;QAEH;;WAEG;;;;;;;;;;;;;;QAcH;;WAEG;;;;;;;;;;;;QAYH;;WAEG;;;;;;QAMH;;WAEG;;;;;;QAMH;;WAEG;;;;;;;;;;;QAWH;;WAEG;;;;;;;QAOH;;WAEG;;;QAGH;;WAEG;;;;;;QAMH;;WAEG;;QAEH;;WAEG;;;QAGH;;WAEG;;;;QAIH;;WAEG;;;;;;;;;;;;;;QAcH;;WAEG;;QAEH;;WAEG;;MAW2B;IAC9B,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC;IAC7B,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;gBAGlC,eAAe,EAAE,SAAS,GAAG;QAAE,QAAQ,EAAE,SAAS,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;KAAE,EAChF,iBAAiB,CAAC,EAAE,GAAG;CAyB1B"}
@@ -153,7 +153,8 @@ export declare enum ProviderName {
153
153
  NEAR = "NEAR",
154
154
  GARDEN = "GARDEN",
155
155
  OKX = "OKX",
156
- HARBOR = "HARBOR"
156
+ HARBOR = "HARBOR",
157
+ FLASHNET = "FLASHNET"
157
158
  }
158
159
  export declare enum FeeTypeEnum {
159
160
  LIQUIDITY = "liquidity",
@@ -1 +1 @@
1
- {"version":3,"file":"quotes.d.ts","sourceRoot":"","sources":["../../../src/types/quotes.ts"],"names":[],"mappings":"AAAA,oBAAY,SAAS;IACnB,YAAY,iBAAiB;IAC7B,UAAU,eAAe;IACzB,oBAAoB,yBAAyB;IAC7C,mBAAmB,wBAAwB;IAC3C,yBAAyB,8BAA8B;IACvD,uBAAuB,4BAA4B;IACnD,aAAa,kBAAkB;IAC/B,qBAAqB,0BAA0B;IAC/C,YAAY,iBAAiB;IAC7B,eAAe,oBAAoB;IACnC,0BAA0B,+BAA+B;IACzD,uBAAuB,4BAA4B;IACnD,qBAAqB,0BAA0B;IAC/C,oBAAoB,yBAAyB;IAC7C,iBAAiB,sBAAsB;IACvC,kBAAkB,uBAAuB;IACzC,YAAY,iBAAiB;IAC7B,aAAa,kBAAkB;IAC/B,SAAS,cAAc;IACvB,gBAAgB,qBAAqB;IACrC,gBAAgB,qBAAqB;IACrC,sBAAsB,2BAA2B;IACjD,uBAAuB,4BAA4B;IACnD,YAAY,iBAAiB;IAC7B,kBAAkB,uBAAuB;IACzC,qCAAqC,0CAA0C;IAC/E,qCAAqC,0CAA0C;IAC/E,2BAA2B,gCAAgC;IAC3D,oCAAoC,yCAAyC;IAC7E,eAAe,oBAAoB;IACnC,eAAe,oBAAoB;IACnC,cAAc,mBAAmB;IACjC,WAAW,gBAAgB;IAC3B,UAAU,eAAe;IACzB,iBAAiB,sBAAsB;IACvC,cAAc,mBAAmB;IACjC,kBAAkB,uBAAuB;IACzC,aAAa,kBAAkB;IAC/B,eAAe,oBAAoB;IACnC,WAAW,gBAAgB;IAC3B,mBAAmB,wBAAwB;IAC3C,oBAAoB,yBAAyB;IAC7C,eAAe,oBAAoB;IACnC,iBAAiB,sBAAsB;IACvC,gBAAgB,qBAAqB;IACrC,gBAAgB,qBAAqB;IACrC,sBAAsB,2BAA2B;IACjD,mBAAmB,wBAAwB;IAC3C,sBAAsB,2BAA2B;IACjD,uBAAuB,4BAA4B;IACnD,oBAAoB,yBAAyB;IAC7C,yBAAyB,8BAA8B;IACvD,4BAA4B,iCAAiC;IAC7D,iCAAiC,sCAAsC;IACvE,cAAc,mBAAmB;IACjC,kBAAkB,uBAAuB;IACzC,qBAAqB,0BAA0B;IAC/C,iBAAiB,sBAAsB;IACvC,mBAAmB,wBAAwB;IAC3C,sBAAsB,2BAA2B;IACjD,kBAAkB,uBAAuB;IACzC,iBAAiB,sBAAsB;IACvC,mBAAmB,wBAAwB;IAC3C,4BAA4B,iCAAiC;IAC7D,sBAAsB,2BAA2B;IACjD,iBAAiB,sBAAsB;IACvC,aAAa,kBAAkB;IAC/B,kBAAkB,uBAAuB;IACzC,wBAAwB,6BAA6B;IACrD,kBAAkB,uBAAuB;IACzC,gBAAgB,qBAAqB;IACrC,wBAAwB,6BAA6B;IACrD,kBAAkB,uBAAuB;IACzC,oBAAoB,yBAAyB;IAC7C,sBAAsB,2BAA2B;IACjD,wBAAwB,6BAA6B;IACrD,qBAAqB,0BAA0B;IAC/C,kBAAkB,sBAAsB;IACxC,uBAAuB,4BAA4B;IACnD,6BAA6B,kCAAkC;IAC/D,iBAAiB,sBAAsB;IACvC,cAAc,mBAAmB;IACjC,gBAAgB,qBAAqB;IACrC,aAAa,kBAAkB;IAC/B,aAAa,kBAAkB;IAC/B,aAAa,kBAAkB;IAC/B,gBAAgB,qBAAqB;IACrC,kBAAkB,uBAAuB;IACzC,qBAAqB,0BAA0B;IAC/C,eAAe,oBAAoB;IACnC,6BAA6B,kCAAkC;IAC/D,cAAc,mBAAmB;IACjC,oBAAoB,yBAAyB;IAC7C,wBAAwB,6BAA6B;IACrD,uBAAuB,4BAA4B;IACnD,sBAAsB,2BAA2B;IACjD,gBAAgB,qBAAqB;IACrC,iBAAiB,sBAAsB;IACvC,gBAAgB,sBAAsB;IACtC,aAAa,oBAAoB;IACjC,cAAc,qBAAqB;IACnC,aAAa,kBAAkB;IAC/B,iBAAiB,sBAAsB;IACvC,yBAAyB,8BAA8B;IACvD,qBAAqB,0BAA0B;IAC/C,oBAAoB,yBAAyB;IAC7C,YAAY,iBAAiB;IAC7B,wBAAwB,6BAA6B;IACrD,gBAAgB,qBAAqB;IACrC,cAAc,mBAAmB;IACjC,qBAAqB,0BAA0B;IAC/C,oBAAoB,yBAAyB;IAC7C,YAAY,iBAAiB;IAC7B,kBAAkB,uBAAuB;IACzC,6BAA6B,kCAAkC;IAC/D,kBAAkB,uBAAuB;IACzC,aAAa,kBAAkB;IAC/B,oBAAoB,yBAAyB;IAC7C,aAAa,kBAAkB;IAC/B,YAAY,iBAAiB;IAC7B,kBAAkB,uBAAuB;IACzC,0BAA0B,+BAA+B;IACzD,kBAAkB,uBAAuB;IACzC,oBAAoB,yBAAyB;IAC7C,uBAAuB,4BAA4B;IACnD,uBAAuB,4BAA4B;IACnD,sBAAsB,2BAA2B;IACjD,YAAY,iBAAiB;IAC7B,iBAAiB,sBAAsB;IACvC,uBAAuB,4BAA4B;IACnD,iBAAiB,sBAAsB;IACvC,qBAAqB,0BAA0B;CAChD;AAED,oBAAY,eAAe;IACzB,YAAY,iBAAiB;IAC7B,eAAe,oBAAoB;CACpC;AAED,oBAAY,YAAY;IACtB,SAAS,cAAc;IACvB,mBAAmB,wBAAwB;IAC3C,OAAO,YAAY;IACnB,SAAS,cAAc;IACvB,mBAAmB,wBAAwB;IAC3C,OAAO,YAAY;IACnB,WAAW,gBAAgB;IAC3B,YAAY,iBAAiB;IAC7B,SAAS,cAAc;IACvB,mBAAmB,wBAAwB;IAC3C,YAAY,iBAAiB;IAC7B,UAAU,eAAe;IACzB,UAAU,eAAe;IACzB,IAAI,SAAS;IACb,MAAM,WAAW;IACjB,GAAG,QAAQ;IACX,MAAM,WAAW;CAClB;AAED,oBAAY,WAAW;IACrB,SAAS,cAAc;IACvB,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,QAAQ,aAAa;IACrB,SAAS,cAAc;IACvB,GAAG,QAAQ;IACX,QAAQ,aAAa;IACrB,OAAO,YAAY;CACpB"}
1
+ {"version":3,"file":"quotes.d.ts","sourceRoot":"","sources":["../../../src/types/quotes.ts"],"names":[],"mappings":"AAAA,oBAAY,SAAS;IACnB,YAAY,iBAAiB;IAC7B,UAAU,eAAe;IACzB,oBAAoB,yBAAyB;IAC7C,mBAAmB,wBAAwB;IAC3C,yBAAyB,8BAA8B;IACvD,uBAAuB,4BAA4B;IACnD,aAAa,kBAAkB;IAC/B,qBAAqB,0BAA0B;IAC/C,YAAY,iBAAiB;IAC7B,eAAe,oBAAoB;IACnC,0BAA0B,+BAA+B;IACzD,uBAAuB,4BAA4B;IACnD,qBAAqB,0BAA0B;IAC/C,oBAAoB,yBAAyB;IAC7C,iBAAiB,sBAAsB;IACvC,kBAAkB,uBAAuB;IACzC,YAAY,iBAAiB;IAC7B,aAAa,kBAAkB;IAC/B,SAAS,cAAc;IACvB,gBAAgB,qBAAqB;IACrC,gBAAgB,qBAAqB;IACrC,sBAAsB,2BAA2B;IACjD,uBAAuB,4BAA4B;IACnD,YAAY,iBAAiB;IAC7B,kBAAkB,uBAAuB;IACzC,qCAAqC,0CAA0C;IAC/E,qCAAqC,0CAA0C;IAC/E,2BAA2B,gCAAgC;IAC3D,oCAAoC,yCAAyC;IAC7E,eAAe,oBAAoB;IACnC,eAAe,oBAAoB;IACnC,cAAc,mBAAmB;IACjC,WAAW,gBAAgB;IAC3B,UAAU,eAAe;IACzB,iBAAiB,sBAAsB;IACvC,cAAc,mBAAmB;IACjC,kBAAkB,uBAAuB;IACzC,aAAa,kBAAkB;IAC/B,eAAe,oBAAoB;IACnC,WAAW,gBAAgB;IAC3B,mBAAmB,wBAAwB;IAC3C,oBAAoB,yBAAyB;IAC7C,eAAe,oBAAoB;IACnC,iBAAiB,sBAAsB;IACvC,gBAAgB,qBAAqB;IACrC,gBAAgB,qBAAqB;IACrC,sBAAsB,2BAA2B;IACjD,mBAAmB,wBAAwB;IAC3C,sBAAsB,2BAA2B;IACjD,uBAAuB,4BAA4B;IACnD,oBAAoB,yBAAyB;IAC7C,yBAAyB,8BAA8B;IACvD,4BAA4B,iCAAiC;IAC7D,iCAAiC,sCAAsC;IACvE,cAAc,mBAAmB;IACjC,kBAAkB,uBAAuB;IACzC,qBAAqB,0BAA0B;IAC/C,iBAAiB,sBAAsB;IACvC,mBAAmB,wBAAwB;IAC3C,sBAAsB,2BAA2B;IACjD,kBAAkB,uBAAuB;IACzC,iBAAiB,sBAAsB;IACvC,mBAAmB,wBAAwB;IAC3C,4BAA4B,iCAAiC;IAC7D,sBAAsB,2BAA2B;IACjD,iBAAiB,sBAAsB;IACvC,aAAa,kBAAkB;IAC/B,kBAAkB,uBAAuB;IACzC,wBAAwB,6BAA6B;IACrD,kBAAkB,uBAAuB;IACzC,gBAAgB,qBAAqB;IACrC,wBAAwB,6BAA6B;IACrD,kBAAkB,uBAAuB;IACzC,oBAAoB,yBAAyB;IAC7C,sBAAsB,2BAA2B;IACjD,wBAAwB,6BAA6B;IACrD,qBAAqB,0BAA0B;IAC/C,kBAAkB,sBAAsB;IACxC,uBAAuB,4BAA4B;IACnD,6BAA6B,kCAAkC;IAC/D,iBAAiB,sBAAsB;IACvC,cAAc,mBAAmB;IACjC,gBAAgB,qBAAqB;IACrC,aAAa,kBAAkB;IAC/B,aAAa,kBAAkB;IAC/B,aAAa,kBAAkB;IAC/B,gBAAgB,qBAAqB;IACrC,kBAAkB,uBAAuB;IACzC,qBAAqB,0BAA0B;IAC/C,eAAe,oBAAoB;IACnC,6BAA6B,kCAAkC;IAC/D,cAAc,mBAAmB;IACjC,oBAAoB,yBAAyB;IAC7C,wBAAwB,6BAA6B;IACrD,uBAAuB,4BAA4B;IACnD,sBAAsB,2BAA2B;IACjD,gBAAgB,qBAAqB;IACrC,iBAAiB,sBAAsB;IACvC,gBAAgB,sBAAsB;IACtC,aAAa,oBAAoB;IACjC,cAAc,qBAAqB;IACnC,aAAa,kBAAkB;IAC/B,iBAAiB,sBAAsB;IACvC,yBAAyB,8BAA8B;IACvD,qBAAqB,0BAA0B;IAC/C,oBAAoB,yBAAyB;IAC7C,YAAY,iBAAiB;IAC7B,wBAAwB,6BAA6B;IACrD,gBAAgB,qBAAqB;IACrC,cAAc,mBAAmB;IACjC,qBAAqB,0BAA0B;IAC/C,oBAAoB,yBAAyB;IAC7C,YAAY,iBAAiB;IAC7B,kBAAkB,uBAAuB;IACzC,6BAA6B,kCAAkC;IAC/D,kBAAkB,uBAAuB;IACzC,aAAa,kBAAkB;IAC/B,oBAAoB,yBAAyB;IAC7C,aAAa,kBAAkB;IAC/B,YAAY,iBAAiB;IAC7B,kBAAkB,uBAAuB;IACzC,0BAA0B,+BAA+B;IACzD,kBAAkB,uBAAuB;IACzC,oBAAoB,yBAAyB;IAC7C,uBAAuB,4BAA4B;IACnD,uBAAuB,4BAA4B;IACnD,sBAAsB,2BAA2B;IACjD,YAAY,iBAAiB;IAC7B,iBAAiB,sBAAsB;IACvC,uBAAuB,4BAA4B;IACnD,iBAAiB,sBAAsB;IACvC,qBAAqB,0BAA0B;CAChD;AAED,oBAAY,eAAe;IACzB,YAAY,iBAAiB;IAC7B,eAAe,oBAAoB;CACpC;AAED,oBAAY,YAAY;IACtB,SAAS,cAAc;IACvB,mBAAmB,wBAAwB;IAC3C,OAAO,YAAY;IACnB,SAAS,cAAc;IACvB,mBAAmB,wBAAwB;IAC3C,OAAO,YAAY;IACnB,WAAW,gBAAgB;IAC3B,YAAY,iBAAiB;IAC7B,SAAS,cAAc;IACvB,mBAAmB,wBAAwB;IAC3C,YAAY,iBAAiB;IAC7B,UAAU,eAAe;IACzB,UAAU,eAAe;IACzB,IAAI,SAAS;IACb,MAAM,WAAW;IACjB,GAAG,QAAQ;IACX,MAAM,WAAW;IACjB,QAAQ,aAAa;CACtB;AAED,oBAAY,WAAW;IACrB,SAAS,cAAc;IACvB,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,QAAQ,aAAa;IACrB,SAAS,cAAc;IACvB,GAAG,QAAQ;IACX,QAAQ,aAAa;IACrB,OAAO,YAAY;CACpB"}
package/package.json CHANGED
@@ -2,16 +2,16 @@
2
2
  "author": "swapkit-dev",
3
3
  "dependencies": {
4
4
  "@near-js/providers": "~2.5.0",
5
- "@swapkit/contracts": "4.1.2",
6
- "@swapkit/tokens": "4.2.4",
7
- "@swapkit/types": "0.7.2",
5
+ "@swapkit/contracts": "4.1.3",
6
+ "@swapkit/tokens": "4.2.5",
7
+ "@swapkit/types": "0.7.3",
8
8
  "ethers": "^6.14.0",
9
9
  "ts-pattern": "^5.9.0",
10
10
  "zod": "3.25.74",
11
11
  "zustand": "5.0.8"
12
12
  },
13
13
  "description": "SwapKit - Helpers",
14
- "devDependencies": { "@near-js/providers": "2.5.0", "@swapkit/toolboxes": "4.14.2", "ethers": "6.16.0" },
14
+ "devDependencies": { "@near-js/providers": "2.5.0", "@swapkit/toolboxes": "4.14.4", "ethers": "6.16.0" },
15
15
  "exports": {
16
16
  ".": { "default": "./dist/index.js", "require": "./dist/index.cjs", "types": "./dist/types/index.d.ts" },
17
17
  "./api": {
@@ -41,5 +41,5 @@
41
41
  "type-check:go": "tsgo"
42
42
  },
43
43
  "type": "module",
44
- "version": "4.12.7"
44
+ "version": "4.12.9"
45
45
  }
@@ -1,5 +0,0 @@
1
- var rA=Object.defineProperty;var lA=(N)=>N;function iA(N,A){this[N]=lA.bind(null,A)}var cN=(N,A)=>{for(var T in A)rA(N,T,{get:A[T],enumerable:!0,configurable:!0,set:iA.bind(A,T)})};var RN=((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 QN,getChainConfig as hT}from"@swapkit/types";import{AllChains as WT,Chain as X,EVMChains as qT,getChainConfig as ON}from"@swapkit/types";import{getAddress as FA}from"ethers";import{match as mN}from"ts-pattern";import{Chain as n,EVMChains as XT,getChainConfig as C,UTXOChains as QT}from"@swapkit/types";import{match as FN}from"ts-pattern";import{AllChains as lN,getChainConfig as HT,StagenetChain as rN,StagenetMAYAConfig as PT,StagenetTHORConfig as LT}from"@swapkit/types";import{createStore as RT}from"zustand/vanilla";import{AllChains as sA,getChainConfig as eA}from"@swapkit/types";var bP=sA.reduce((N,A)=>{return N[A]=eA(A).networkDerivationPath,N},{});var uN;((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"})(uN||={});var bN;((T)=>{T.highSlippage="highSlippage";T.highPriceImpact="highPriceImpact"})(bN||={});var j;((x)=>{x.CHAINFLIP="CHAINFLIP";x.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";x.JUPITER="JUPITER";x.MAYACHAIN="MAYACHAIN";x.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";x.ONEINCH="ONEINCH";x.PANCAKESWAP="PANCAKESWAP";x.SUSHISWAP_V2="SUSHISWAP_V2";x.THORCHAIN="THORCHAIN";x.THORCHAIN_STREAMING="THORCHAIN_STREAMING";x.TRADERJOE_V2="TRADERJOE_V2";x.UNISWAP_V2="UNISWAP_V2";x.UNISWAP_V3="UNISWAP_V3";x.NEAR="NEAR";x.GARDEN="GARDEN";x.OKX="OKX";x.HARBOR="HARBOR"})(j||={});var zN;((G)=>{G.LIQUIDITY="liquidity";G.NETWORK="network";G.INBOUND="inbound";G.OUTBOUND="outbound";G.AFFILIATE="affiliate";G.TAX="tax";G.PRIORITY="priority";G.SERVICE="service"})(zN||={});var aA;((H)=>{H.Average="average";H.Fast="fast";H.Fastest="fastest"})(aA||={});var NT;((T)=>{T.Approve="approve";T.CheckOnly="checkOnly"})(NT||={});var AT;((Y)=>{Y.NAME_REGISTER="~";Y.BOND="BOND";Y.DEPOSIT="+";Y.LEAVE="LEAVE";Y.UNBOND="UNBOND";Y.WITHDRAW="-";Y.RUNEPOOL_DEPOSIT="POOL+";Y.RUNEPOOL_WITHDRAW="POOL-";Y.CLAIM_TCY="tcy";Y.STAKE_TCY="tcy+";Y.UNSTAKE_TCY="tcy-"})(AT||={});import{Chain as _}from"@swapkit/types";var JN;((U)=>{U.BITGET="BITGET";U.BRAVE="BRAVE";U.COINBASE_MOBILE="COINBASE_MOBILE";U.COINBASE_WEB="COINBASE_WEB";U.COSMOSTATION="COSMOSTATION";U.CTRL="CTRL";U.EIP6963="EIP6963";U.EXODUS="EXODUS";U.KEEPKEY="KEEPKEY";U.KEEPKEY_BEX="KEEPKEY_BEX";U.KEPLR="KEPLR";U.KEYSTORE="KEYSTORE";U.LEAP="LEAP";U.LEDGER="LEDGER";U.METAMASK="METAMASK";U.OKX="OKX";U.OKX_MOBILE="OKX_MOBILE";U.ONEKEY="ONEKEY";U.PASSKEYS="PASSKEYS";U.PETRA="PETRA";U.PHANTOM="PHANTOM";U.POLKADOT_JS="POLKADOT_JS";U.RADIX_WALLET="RADIX_WALLET";U.TALISMAN="TALISMAN";U.TREZOR="TREZOR";U.TRONLINK="TRONLINK";U.TRUSTWALLET_WEB="TRUSTWALLET_WEB";U.VULTISIG="VULTISIG";U.WALLETCONNECT="WALLETCONNECT";U.WALLET_SELECTOR="WALLET_SELECTOR";U.XAMAN="XAMAN"})(JN||={});var TT;((H)=>{H[H.NoError=36864]="NoError";H[H.LockedDevice=21781]="LockedDevice";H[H.TC_NotFound=65535]="TC_NotFound"})(TT||={});var J=["BITGET","BRAVE","COINBASE_MOBILE","COINBASE_WEB","COSMOSTATION","CTRL","EIP6963","KEEPKEY","KEEPKEY_BEX","KEYSTORE","LEDGER","METAMASK","OKX","OKX_MOBILE","PASSKEYS","PHANTOM","TALISMAN","TREZOR","TRUSTWALLET_WEB","VULTISIG","WALLETCONNECT"],vP={[_.Arbitrum]:J,[_.Aurora]:J,[_.Avalanche]:J,[_.Base]:J,[_.Berachain]:J,[_.BinanceSmartChain]:J,[_.Botanix]:J,[_.Chainflip]:J,[_.Core]:J,[_.Corn]:J,[_.Cronos]:J,[_.Ethereum]:J,[_.Gnosis]:J,[_.Hyperevm]:J,[_.MegaETH]:J,[_.Monad]:J,[_.Optimism]:J,[_.Polygon]:J,[_.Sonic]:J,[_.Unichain]:J,[_.XLayer]:J,[_.Bitcoin]:["BITGET","KEYSTORE","OKX","ONEKEY","PASSKEYS","PHANTOM"],[_.BitcoinCash]:["KEYSTORE"],[_.Dash]:["KEYSTORE"],[_.Dogecoin]:["KEYSTORE"],[_.Litecoin]:["KEYSTORE"],[_.Zcash]:["KEYSTORE"],[_.Cosmos]:["COSMOSTATION","CTRL","KEPLR","KEYSTORE","LEAP"],[_.Kujira]:["COSMOSTATION","CTRL","KEPLR","KEYSTORE","LEAP"],[_.Maya]:["KEYSTORE"],[_.Noble]:["COSMOSTATION","CTRL","KEPLR","KEYSTORE","LEAP"],[_.THORChain]:["COSMOSTATION","KEPLR","KEYSTORE","LEAP"],[_.Aptos]:["BITGET","KEYSTORE","OKX","PETRA"],[_.Cardano]:["KEYSTORE"],[_.HyperCore]:["KEYSTORE"],[_.Near]:["KEYSTORE","LEDGER"],[_.Ripple]:["KEYSTORE","LEDGER"],[_.Solana]:["KEYSTORE","PASSKEYS","PHANTOM"],[_.Sui]:["KEYSTORE"],[_.Tron]:["KEYSTORE","LEDGER"],[_.Stellar]:["KEYSTORE"],[_.Starknet]:["KEYSTORE"]};var uT=lN.reduce((N,A)=>{if(!N.THOR_STAGENET)N[rN.Maya]=PT.rpcUrls,N[rN.THORChain]=LT.rpcUrls;return N[A]=HT(A).rpcUrls,N},{}),iN={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"}}},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:uT,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(JN),widgetKey:""},q=RT((N)=>({...iN,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},rpcUrls:{...T.rpcUrls,...A?.rpcUrls},v3SwapFlow:{...T.v3SwapFlow,...A?.v3SwapFlow},wallets:T.wallets.concat(A?.wallets||[]),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}})),setWidgetKey:(A)=>N({widgetKey:A})})),E={get:(N)=>q.getState()[N],getState:q.getState,reinitialize:()=>q.setState(iN),set:(N)=>q.getState().setConfig(N),setApiKey:(N,A)=>q.getState().setApiKey(N,A),setEndpoint:(N,A)=>q.getState().setEndpoint(N,A),setEnv:(N,A)=>q.getState().setEnv(N,A),setFeeMultipliers:(N)=>q.getState().setFeeMultipliers(N),setIntegrationConfig:(N,A)=>q.getState().setIntegrationConfig(N,A),setRequestOptions:(N)=>q.getState().setRequestOptions(N),setRpcUrl:(N,A)=>q.getState().setRpcUrl(N,A),setWidgetKey:(N)=>q.getState().setWidgetKey(N)};var FT={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_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_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,not_implemented:99999};function ZN(N){return JSON.stringify(N,(A,T)=>typeof T==="bigint"?T.toString():T)}class D extends Error{static ErrorCode=FT;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,D.prototype),this.name="SwapKitError",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 IT=(N)=>new Promise((A)=>setTimeout(A,N)),nT=(N,{baseDelay:A,backoffMultiplier:T,maxDelay:H})=>Math.min(A*T**N,H);function OT(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 BT=async(N,A)=>{let T=await fetch(N,A),H;try{H=await T.json()}catch{if(!T.ok)throw new D({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 D({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 D({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:B,headers:G,dynamicHeader:M,retry:w,timeoutMs:Y,abortController:W,onError:S,onSuccess:K,responseHandler:b,...z}={...A,...P},x=E.get("requestOptions"),r={...x.retry,...w},gN=!!I||H.endsWith(".json"),GN=gT(H,F),CN=M?await M():{},LN=$T(gN,{...G,...CN}),l=gN?JSON.stringify(I):B,wN;for(let tN=0;tN<=r.maxRetries;tN++){let dN=W||new AbortController,hN=setTimeout(()=>dN.abort(),Y||x.timeoutMs);try{let o=await BT(GN,{...z,body:l,headers:LN,method:N,signal:dN.signal});return clearTimeout(hN),K?.(o)||b?.(o)||o}catch(o){clearTimeout(hN),wN=o;let cA=o?.cause?.status;if(tN>=r.maxRetries||!OT(o,cA))return S?S(o):Promise.reject(o);await IT(nT(tN,r))}}return S?S(wN):Promise.reject(wN)}}function $T(N,A){return{...A,...N&&{"Content-Type":"application/json"}}}function gT(N,A){let T=new URL(N);if(A)T.search=new URLSearchParams(A).toString();return T.toString()}var g={extend:(N)=>({extend:(A)=>g.extend({...N,...A}),get:_N("GET",N),post:_N("POST",N)}),get:_N("GET"),post:_N("POST")};import{Chain as Z,CosmosChains as GT,EVMChains as tT,StagenetChains as _T,UTXOChains as DT}from"@swapkit/types";import{match as aN}from"ts-pattern";import{Chain as jN}from"@swapkit/types";function sP(N){if(N<0)throw new D({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:N}});return 10+N}function eP(N){if(N<0)throw new D({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:N}});return Math.round((10+N*1.0512)*10000000000)/10000000000}function aP(N,A){try{return N()}catch(T){if(A)throw new D(A,T);return}}function NL(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 sN=new Set;function i({condition:N,id:A,warning:T}){if(N){if(sN.has(A))return;console.warn(T),sN.add(A)}}function YT(N){return aN(N).with(...tT,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...DT,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...GT,..._T,()=>({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.HyperCore,()=>({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 D("helpers_chain_not_supported",{chain:N})})}function UT(N){return aN(N).with(Z.Aptos,()=>"/-/healthy").with(Z.HyperCore,()=>"/info").with(Z.Radix,()=>"/status/network-configuration").with(Z.Stellar,()=>"").with(Z.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function eN(N,A){try{let T=A.startsWith("wss")?A.replace("wss","https"):A;return(await fetch(`${T}${UT(N)}`,{body:JSON.stringify(YT(N)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var vN=new Map,MT=120000;function ST(N){let[A=""]=E.get("rpcUrls")[N];if(!A)throw i({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 D("helpers_chain_no_public_or_set_rpc_url",{chain:N});let T=vN.get(N);if(T&&Date.now()-T.timestamp<MT)return T.url;return vN.set(N,{timestamp:Date.now(),url:A}),A}async function s(N){let A=ST(N),[,...T]=E.get("rpcUrls")[N];if(await eN(N,A))return A;for(let P of T)if(await eN(N,P))return vN.set(N,{timestamp:Date.now(),url:P}),P;throw new D("helpers_chain_rpc_connection_failed",{chain:N,fallbackUrls:T,primaryRpcUrl:A})}function uL(N){i({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 $L=[`${n.Maya}.MAYA`,`${n.Maya}.CACAO`,`${n.Ethereum}.THOR`,`${n.Ethereum}.vTHOR`,`${n.Kujira}.USK`,`${n.Ethereum}.FLIP`,`${n.Radix}.XRD`],TA=[n.Arbitrum,n.Aurora,n.Base,n.Ethereum,n.Optimism];async function xT(N){let{baseDecimal:A}=C(n.Radix);try{let T=await s(n.Radix),{manager:H}=await g.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 ET(N){try{let A=await s(n.Radix);return(await g.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 HA({chain:N,address:A,methodHex:T,id:H}){let P=await s(N);return g.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 wT(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 bT(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 zT({chain:N,address:A}){let{baseDecimal:T}=C(N),H=A.toLowerCase();if(A===""||!H.startsWith("0x"))return T;let P=await HA({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 bT(P.result,T)}async function JT({chain:N,address:A}){let T=A.toLowerCase();if(T===""||!T.startsWith("0x"))return;let H=await HA({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 wT(H.result)}async function NA({rpcUrl:N,contractAddress:A,functionSelector:T}){return(await g.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 AA(N){let A=N.match(/.{2}/g)?.map((T)=>Number.parseInt(T,16))??[];return new TextDecoder().decode(new Uint8Array(A))}function ZT(N){return FN(N).with(void 0,()=>{return}).when((A)=>A.length>=128,(A)=>{let T=Number.parseInt(A.slice(64,128),16);return AA(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 AA(T);return}).otherwise(()=>{return})}function PA({chain:N,address:A}){let{baseDecimal:T}=C(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,B]=await Promise.all([JT({address:A,chain:N}),zT({address:A,chain:N})]);return{decimals:B,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 s(n.Tron),[F,I]=await Promise.all([NA({contractAddress:A,functionSelector:"symbol()",rpcUrl:P}),NA({contractAddress:A,functionSelector:"decimals()",rpcUrl:P})]),B=ZT(F);return{decimals:F!==void 0&&I?Number(BigInt(`0x${I}`)):T,ticker:B}}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 s(n.Near),B=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"}),G=JSON.parse(Buffer.from(B.result).toString());return{decimals:G?.decimals||T,ticker:G?.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([ET(A),xT(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 DN({chain:N,symbol:A}){return FN(N).with(...TA,()=>A==="ETH").with(n.Avalanche,()=>A==="AVAX").with(n.Berachain,()=>A==="BERA").with(n.Hyperevm,()=>A==="HYPE").with(n.HyperCore,()=>A==="HYPE").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}`===YN(N).identifier).otherwise(()=>A===N)}var YN=(N)=>{let{baseDecimal:A}=C(N);return FN(N.toUpperCase()).with(...TA,(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.HyperCore,(H)=>({decimal:A,identifier:`${H}.HYPE`})).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:C(n.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:C(n.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:C(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 VN({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}`===YN(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.HyperCore,()=>A==="HYPE").with(n.XLayer,()=>A==="OKB").otherwise(()=>A===N)?"Native":N}var d=(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 IN(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 gL(N){return`https://storage.googleapis.com/token-list-swapkit-dev/images/${N.toLowerCase()}.png`}async function GL(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:B}=d(F.identifier);if(I!==N.chain)continue;let{address:G}=IN(B,I);if(G?.toLowerCase()===P)return F.identifier}return}var LA=["TERRA",...E.get("chains")];function RA(N=""){let A=N.toUpperCase(),[T]=A.split(".");if(LA.includes(T))return!0;let[H]=A.split("/");if(LA.includes(H))return!0;throw new D({errorKey:"helpers_invalid_identifier",info:{identifier:N,message:`Invalid identifier: ${N}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}function YL(N){if(N.length>30)return!1;let A=/^[a-zA-Z0-9+_-]+$/g;return!!N.match(A)}import{match as UN}from"ts-pattern";var e=8,jT=10;function c({value:N,bigIntDecimal:A=e,decimal:T=e}){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,B=P.slice(-T);if(Number.parseInt(B[A]||"0",10)>=5){let M=Number.parseInt(B[A-1]||"0",10);B=`${B.substring(0,A-1)}${M+1}`}else B=B.substring(0,A);return`${H?"-":""}${P.slice(0,I)}.${B}`.replace(/\.?0*$/,"")}class y{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(N,A){return new y({decimal:A,value:c({bigIntDecimal:A,decimal:A,value:N})})}static shiftDecimals({value:N,from:A,to:T}){return y.fromBigInt(N.getBaseValue("bigint")*h(T)/h(A),T)}constructor(N){let A=WN(N),T=typeof N==="object";this.decimal=T?N.decimal:void 0,this.decimalMultiplier=T&&"decimalMultiplier"in N?N.decimalMultiplier:h(Math.max(uA(MN(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=nN(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 UN(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/h(A||this.decimal||e),H=VT(this.bigIntValue,T);return UN(N).with("number",()=>Number(H)).with("string",()=>H.toString()).otherwise(()=>H)}getBigIntValue(N,A){if(!A&&typeof N==="object")return N.bigIntValue;let T=WN(N),H=MN(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(),B=I.slice(0,N),G=H.length-I.length;return`0.${B.padStart(G+B.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 B=P[N];if(!(B&&Number.parseInt(B,10)>=5))return`${I}${H}.${P.slice(0,N).padEnd(N,"0")}`;let M=BigInt(P.slice(0,N).padEnd(N,"0"))+1n,w=10n**BigInt(N);if(M>=w)return`${I}${BigInt(H)+1n}.${"0".repeat(N)}`;return`${I}${H}.${M.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),B=A==="end",[G="0",M=""]=I.split("."),w=G.replace(/\B(?=(\d{3})+(?!\d))/g,P),Y=M&&Number.parseInt(M,10)>0,W=Y?`${w}${H}${M}`:w,K=W.length<100&&F&&Y?W.replace(/\.?0*$/,""):W;return B?`${K}${N}`:`${N}${K}`}formatBigIntToSafeValue(N,A){let T=A||this.decimal||e,H=Math.max(T,nN(this.decimalMultiplier));return c({bigIntDecimal:T,decimal:H,value:N})}#A(N,...A){let T=this.#T(this,...A),H=nN(this.decimalMultiplier),F=Math.max(T,H)+jT,I=h(F),B=A.reduce((M,w)=>{let Y=this.getBigIntValue(w,F);return UN(N).with("add",()=>M+Y).with("sub",()=>M-Y).with("mul",()=>M*Y/I).with("div",()=>{if(Y===0n)throw RangeError("Division by zero");return M*I/Y}).otherwise(()=>M)},this.bigIntValue*I/this.decimalMultiplier),G=c({bigIntDecimal:F,decimal:F,value:B});return new this.constructor({decimal:this.decimal,decimalMultiplier:h(F),identifier:this.toString(),value:G})}#N(N,...A){let T=this.#T(this,...A),H=this.getBigIntValue(A[0]||"0",T),P=this.getBigIntValue(this,T);return UN(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=MN(N)||"0";this.bigIntValue=this.#H(A)}#T(...N){let A=N.map((T)=>{return typeof T==="object"?T.decimal||nN(T.decimalMultiplier):uA(MN(T))}).filter(Boolean);return Math.max(...A,e)}#H(N,A){let T=A?h(A):this.decimalMultiplier,H=nN(T),[P="",F=""]=N.split(".");return BigInt(`${P}${F.padEnd(H,"0")}`)}}var vT=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function MN(N){let T=`${typeof N==="number"?vT.format(N):WN(N)}`.replaceAll(",",".").split(".");return T.length>1?`${T.slice(0,-1).join("")}.${T.at(-1)}`:T[0]||"0"}function uA(N){let A=N.split(".")[1]?.length||0;return Math.max(A,e)}function WN(N){return typeof N==="object"?"getValue"in N?N.getValue("string"):N.value:N}function VT(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 h(N){return 10n**BigInt(N)}function nN(N){return Math.log10(Number.parseFloat(N.toString()))}var f=[X.HyperCore,X.Near,X.Ripple,X.Solana,X.Sui,X.Ton,X.Tron],kN=[X.THORChain,X.Maya],a=new Map,SN=new Map,NN=new Map,mT=3600000;function kT(N){let A=NN.get(N);if(A?.timestamp&&Date.now()-A.timestamp>mT){NN.delete(N);return}return A}function KT(N,A){if(NN.size>1000){let T=NN.keys().next().value;if(T)NN.delete(T)}NN.set(N,{...A,timestamp:Date.now()})}class m 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=IA(F||`${H}.${P}`);this.type=VN(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=ON(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 a.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 D({errorKey:"helpers_invalid_asset_url",info:{urlAsset:N}});let H=N.slice(0,T),P=N.slice(T+1),F=mN({chain:H,rest:P}).when(({rest:I})=>I.includes(".."),({chain:I,rest:B})=>`${I}.${B.replace(/\.\./g,"~")}`).when(({chain:I,rest:B})=>kN.includes(I)&&B.includes("."),({chain:I,rest:B})=>`${I}.${B.replace(/\./g,"/")}`).otherwise(({chain:I,rest:B})=>`${I}.${B.replace(/__/g,".")}`);return m.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=fT(H),I=!F.startsWith(X.Sui)&&F.includes(":");if(T&&I){let[LN,l]=F.split(":");return oT({address:l,chain:LN,fromBaseDecimal:A,parsedValue:P})}let B=I?F.split(":").join(".UNKNOWN-"):F,{identifier:G,decimal:M}=YN(B),{chain:w,isSynthetic:Y,isTradeAsset:W,address:S}=IA(G),{baseDecimal:K}=ON(w),b=a.get(f.includes(w)?G:G.toUpperCase());if(!b&&T&&!Y&&!W)return(async()=>{let{ticker:LN}=d(G),l=await nA({address:S,chain:w,ticker:LN});return qN({decimal:l.decimals,identifier:l.identifier,value:A?AN(BigInt(P),A):P})})();let z=b?.decimal||M;i({condition:!z&&!T,id:`assetValue_static_decimal_not_found_${w}`,warning:`Couldn't find static decimal for one or more tokens on ${w} (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:x,identifier:r,tax:gN}=b||{decimal:z||K,identifier:G},GN=A?AN(BigInt(P),A):AN(P,x);return Y||W?pT(r,GN):qN({decimal:x,identifier:r,tax:gN,value:GN})}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:B}=d(F),{address:G}=IN(B,I),{baseDecimal:M}=ON(I),w=f.includes(I)?F:F.toUpperCase(),Y="decimals"in P&&P.decimals!==void 0?P.decimals:M,W="logoURI"in P&&P.logoURI?P.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${F.toLowerCase()}.png`,S={decimal:Y,identifier:F,logoURI:W,tax:"tax"in P?P.tax:void 0};if(a.set(w,S),G){let K=f.includes(I)?`${I}:${G}`:`${I}:${G.toUpperCase()}`;SN.set(K,F)}}return!0}static setStaticAssets(N){a.clear(),SN.clear();for(let[A,T]of N.entries()){let{identifier:H}=T,{chain:P,symbol:F}=d(H),{address:I}=IN(F,P),{baseDecimal:B}=ON(P),G=T.chain??P,M=T.address??I,w=f.includes(G)?H:H.toUpperCase(),Y=T.decimals??T.decimal??B,W=T.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${H.toLowerCase()}.png`,S={decimal:Y,identifier:w,logoURI:W,tax:T.tax};if(a.set(w,S),M){let K=f.includes(G)?`${G}:${M}`:`${G}:${M.toUpperCase()}`;SN.set(K,H)}}return!0}static get staticAssets(){return a}}function ZL(N){let A=m.from({chain:N});return mN(N).with(X.Bitcoin,X.Litecoin,X.BitcoinCash,X.Dash,()=>A.set(0.00010001)).with(X.Dogecoin,()=>A.set(1.00000001)).with(X.Avalanche,X.Ethereum,X.Arbitrum,X.BinanceSmartChain,()=>A.set(0.00000001)).with(X.THORChain,X.Maya,()=>A.set(0)).with(X.Cosmos,X.Kujira,()=>A.set(0.000001)).otherwise(()=>A.set(0.00000001))}async function nA({chain:N,address:A,ticker:T}){let P=f.includes(N)?`${N}:${A||T}`:`${N}:${A||T}`.toUpperCase(),F=kT(P);if(F)return F;if(!A){let{baseDecimal:G}=ON(N);return{decimals:G,identifier:`${N}.${T||"UNKNOWN"}`}}let I=await PA({address:A,chain:N}),B=`${N}.${I.ticker||T||"UNKNOWN"}-${A}`;return i({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&&KT(P,{decimals:I.decimals,identifier:B}),{decimals:I.decimals,identifier:B}}function qN({identifier:N,decimal:A,value:T,tax:H}){return RA(N),new m({decimal:A,identifier:N,tax:H,value:AN(T,A)})}function pT(N,A=0){let T=N.includes(".")?N.split(".")?.[0]?.toUpperCase():void 0,H=T?kN.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 D({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});return new m({decimal:8,identifier:`${T||X.THORChain}.${F}${P}${I}`,value:AN(A,8)})}async function oT({address:N,chain:A,fromBaseDecimal:T,parsedValue:H}){let{decimals:P,identifier:F}=await nA({address:N,chain:A}),I=T?AN(BigInt(H),T):H;return qN({decimal:P,identifier:F,value:I})}function AN(N,A){return typeof N==="bigint"?c({bigIntDecimal:A,decimal:A,value:N}):N}function yT(N){let A=mN(N).when((T)=>("chain"in T)&&T.chain!==void 0,({chain:T})=>T).otherwise((T)=>{let H=d(T.asset);return H.synth?X.THORChain:H.chain});if(!WT.includes(A.toUpperCase()))throw new D({errorKey:"helpers_invalid_asset_identifier",info:{message:"Please use the AssetValue constructor for unsupported chains"}})}function fT(N){if(yT(N),"chain"in N){let{chain:P,address:F}=N;if(F){let I=f.includes(P)?`${P}:${F}`:`${P}:${F.toUpperCase()}`,B=SN.get(I);if(B)return B;return I}return P}let{chain:A,symbol:T}=d(N.asset);return VN({chain:A,symbol:T})==="Native"?A:N.asset}function CT(N,A,T){let H=N.split("."),P=H[0]?.toUpperCase(),F=kN.includes(P),I=T?"~":"/",[B,G=""]=F?H.slice(1).join(".").split(I):N.split(I);if(!(B&&G))throw new D({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});let{ticker:M,address:w}=OA({chain:B,symbol:G}),Y=`${B}${I}${G}`;return{address:w,chain:P,isGasAsset:!1,isSynthetic:A,isTradeAsset:T,symbol:Y,ticker:M}}function dT(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}=OA({chain:T,symbol:H}),I;try{I=P&&qT.includes(T)&&FA(P)?FA(P):P}catch{I=P}let B=I?`${F}-${I}`:H;return{address:I,chain:T,isGasAsset:DN({chain:T,symbol:H}),isSynthetic:!1,isTradeAsset:!1,symbol:B,ticker:F}}function IA(N){let A=N.slice(0,14),T=A.includes("/"),H=A.includes("~");if(T||H)return CT(N,T,H);return dT(N)}function OA({symbol:N,chain:A}){let{ticker:T,address:H}=IN(N,A);return{address:H&&!f.includes(A)?H.toLowerCase():H,ticker:T}}class XN extends y{eq(N){return this.eqValue(N)}static fromBigInt(N,A){return new XN({decimal:A,value:c({bigIntDecimal:A,decimal:A,value:N})})}}function BA(N=!0){return N?"https://midgard.ninerealms.com":"https://midgard.mayachain.info"}function cT(N=!0){let A=BA(N);return N?`${A}/v2/thorname`:`${A}/v2/mayaname`}function rT(N){return function(T){let H=T?`?status=${T}`:"";return g.get(`${N}/v2/pools${H}`)}}function lT(N){return function(T){return g.get(`${N}/v2/pool/${T}`)}}function iT(N){return function(T,H){let P=H?`?period=${H}`:"";return g.get(`${N}/v2/pool/${T}/stats${P}`)}}function sT(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 g.get(`${N}/v2/history/depths/${T}${F}`)}}function eT(N){return function(){return g.get(`${N}/v2/network`)}}function aT(N){return function(){return g.get(`${N}/v2/health`)}}function NH(N){return function(){return g.get(`${N}/v2/nodes`)}}function AH(N){return function(T){return g.get(`${N}/v2/node/${T}`)}}function TH(N){return function(){return g.get(`${N}/v2/mimir/votes`)}}function HH(N){return function(){return g.get(`${N}/v2/mimir`)}}function PH(N){return function(){return g.get(`${N}/v2/constants`)}}function LH(N){return function(){return g.get(`${N}/v2/stats`)}}function RH(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 g.get(`${N}/v2/history/earnings${P}`)}}function uH(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 g.get(`${N}/v2/history${I}${F}`)}}function FH(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 g.get(`${N}/v2/history/tvl${P}`)}}function IH(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 nH(N){return function(T){let H=IH(T);return g.get(`${N}/v2/actions${H}`)}}function OH(N){return function(T){return g.get(`${N}/v2/member/${T}`)}}function BH(N){return function(T){let H=T?`/${T}`:"";return g.get(`${N}/v2/members${H}`)}}function $H(N){return function(T,H){let P=H?`&asset=${H}`:"";return g.get(`${N}/v2/saver/${T}${P?`?${P.substring(1)}`:""}`)}}function gH(N){return function(T){return g.get(`${N}/v2/savers/${T}`)}}function GH(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 g.get(`${N}/v2/history${I}${F}`)}}function tH(N){return function(T){return g.get(`${N}/v2/balance/${T}`)}}function _H(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return;throw P};return await g.get(`${N}/lookup/${T}`,{onError:H,retry:{maxRetries:1}})}}function DH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return[];throw P};return await g.get(`${N}/rlookup/${T}`,{onError:H,retry:{maxRetries:1}})}}function YH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return[];throw P};return await g.get(`${N}/owner/${T}`,{onError:H,retry:{maxRetries:1}})}}function TN({asset:N,value:A}){return m.from({asset:N,fromBaseDecimal:hT(QN.THORChain).baseDecimal,value:A})}function UH({liquidityPositionGetter:N,isThorchain:A}){return async function(H){let P=await N(H),F=A?"rune":"cacao";return P.pools.map((I)=>({[`${F}Pending`]:TN({asset:"THOR.RUNE",value:I.runePending}),[`${F}RegisteredAddress`]:I.runeAddress,[`${F}Withdrawn`]:TN({asset:"THOR.RUNE",value:I.runeWithdrawn}),[F]:TN({asset:"THOR.RUNE",value:I.runeAdded}),asset:TN({asset:I.pool,value:I.assetAdded}),assetPending:TN({asset:I.pool,value:I.assetPending}),assetRegisteredAddress:I.assetAddress,assetWithdrawn:TN({asset:I.pool,value:I.assetWithdrawn}),dateFirstAdded:I.dateFirstAdded,dateLastAdded:I.dateLastAdded,poolShare:new XN(I.liquidityUnits).div(I.pool)}))}}function $A(N){let A=N===QN.THORChain,T=BA(A),H=cT(A),P=OH(T);return{getActions:nH(T),getBalance:tH(T),getConstants:PH(T),getEarningsHistory:RH(T),getHealth:aT(T),getLiquidityPosition:UH({isThorchain:A,liquidityPositionGetter:P}),getLiquidityPositionRaw:P,getMembers:BH(T),getMimir:HH(T),getMimirVotes:TH(T),getNameDetails:_H(H),getNamesByAddress:DH(H),getNamesByOwner:YH(H),getNetworkInfo:eT(T),getNode:AH(T),getNodes:NH(T),getPool:lT(T),getPoolDepthHistory:sT(T),getPoolStats:iT(T),getPools:rT(T),getSaverDetails:$H(T),getSavers:gH(T),getSaversHistory:GH(T),getStats:LH(T),getSwapHistory:uH(T),getTVLHistory:FH(T)}}var gA=$A(QN.THORChain),GA=$A(QN.Maya);var yN={};cN(yN,{getTrackerDetails:()=>rH,getTokenListProviders:()=>aH,getTokenList:()=>NP,getTokenApproval:()=>eH,getSwapTo:()=>FP,getSwapQuote:()=>lH,getRouteWithTx:()=>iH,getPrice:()=>AP,getNearDepositChannel:()=>PP,getGasRate:()=>TP,getChainflipDepositChannel:()=>HP,getChainBalance:()=>sH,SKRequestClient:()=>V});import{EVMChains as hH}from"@swapkit/types";import{match as cH,P as $N}from"ts-pattern";async function tA(N,A,T){let H=`${A}:${T}`,P=new TextEncoder,F=await crypto.subtle.importKey("raw",P.encode(N),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),I=await crypto.subtle.sign("HMAC",F,P.encode(H));return Array.from(new Uint8Array(I)).map((B)=>B.toString(16).padStart(2,"0")).join("")}import{Chain as xN,ChainId as BN}from"@swapkit/types";import{array as Q,boolean as p,coerce as UA,number as t,object as $,optional as O,string as R,union as KN,unknown as MA,z as L}from"zod/v4";var SA;((H)=>{H.CHEAPEST="CHEAPEST";H.FASTEST="FASTEST";H.RECOMMENDED="RECOMMENDED"})(SA||={});var EN;((P)=>{P.PSBT="PSBT";P.EVM="EVM";P.COSMOS="COSMOS";P.RADIX="RADIX"})(EN||={});var XA;((z)=>{z.approve="approve";z.claim="claim";z.deposit="deposit";z.donate="donate";z.lending="lending";z.lp_action="lp_action";z.native_contract_call="native_contract_call";z.native_send="native_send";z.stake="stake";z.streaming_swap="streaming_swap";z.swap="swap";z.thorname_action="thorname_action";z.token_contract_call="token_contract_call";z.token_transfer="token_transfer";z.unknown="unknown";z.unstake="unstake"})(XA||={});var QA;((S)=>{S.swap="swap";S.aggregation="aggregation";S.addLiquidity="addLiquidity";S.withdrawLiquidity="withdrawLiquidity";S.addSavers="addSavers";S.withdrawSavers="withdrawSavers";S.borrow="borrow";S.repay="repay";S.name="name";S.donate="donate";S.claim="claim";S.stake="stake";S.unstake="unstake"})(QA||={});var xA;((B)=>{B.unknown="unknown";B.not_started="not_started";B.pending="pending";B.swapping="swapping";B.completed="completed";B.refunded="refunded";B.failed="failed"})(xA||={});var EA;((b)=>{b.not_started="not_started";b.starting="starting";b.broadcasted="broadcasted";b.mempool="mempool";b.inbound="inbound";b.outbound="outbound";b.swapping="swapping";b.completed="completed";b.refunded="refunded";b.partially_refunded="partially_refunded";b.dropped="dropped";b.reverted="reverted";b.replaced="replaced";b.retries_exceeded="retries_exceeded";b.parsing_error="parsing_error"})(EA||={});var CL=$({address:O(R()),chain:L.enum(xN).optional(),chainId:L.enum(BN),coingeckoId:O(R()),decimals:UA.number(),extensions:O(L.looseObject({})),identifier:R(),logoURI:O(R()),name:O(R()),shortCode:O(R()),symbol:O(R()),ticker:R()}),dL=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"}),hL=L.object({forceUpdate:L.string().toLowerCase().transform((N)=>N==="true").pipe(L.boolean()).optional()}),cL=$({error:R(),message:R()}),HN=$({address:O(R()),chain:L.enum(xN),decimal:O(t()),isGasAsset:p(),isSynthetic:p(),symbol:R(),tax:O($({buy:t(),sell:t()})),ticker:R()}),wA=$({id:R(),market_cap:t(),name:R(),price_change_24h_usd:t(),price_change_percentage_24h_usd:t(),sparkline_in_7d:Q(t()),timestamp:R(),total_volume:t()}).partial(),rL=$({cg:O(wA),identifier:R(),price_usd:t(),provider:R(),timestamp:t()}),bA=Q($({cg:O(wA),identifier:R(),price_usd:t(),provider:R(),timestamp:t()}).partial()),lL=$({affiliate:O(R().describe("Affiliate thorname")),affiliateFee:O(t().describe("Affiliate fee in basis points").refine((N)=>N===Math.floor(N)&&N>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:O(p().describe("Allow smart contract as recipient")),allowSmartContractSender:O(p().describe("Allow smart contract as sender")),buyAsset:R().describe("Asset to buy"),cfBoost:O(p().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:O(R().describe("Address to send asset to")),disableSecurityChecks:O(p().describe("Disable security checks")),includeTx:O(p().describe("Set to true to include an transaction object (EVM only)")),providers:O(Q(R().describe("List of providers to use").refine((N)=>j[N]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:O(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:O(t().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:O(R().describe("Address to send asset from"))}).refine((N)=>N.sellAsset!==N.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),iL=$({metadata:p(),tokens:Q($({identifier:R()}))}),zA=$({destinationAddress:R()}),MH=zA.extend({affiliateFees:Q($({brokerAddress:R(),feeBps:t()})).optional(),brokerCommissionBps:t().optional(),buyAsset:$({asset:R(),chain:R()}),channelMetadata:$({cfParameters:R().optional(),gasBudget:R().optional(),message:R().optional()}).optional(),dcaParameters:$({chunkInterval:t().optional(),numberOfChunks:t().optional()}).optional(),maxBoostFeeBps:t().optional(),refundParameters:$({minPrice:R().optional(),refundAddress:R().optional(),retryDuration:t().optional()}).optional(),sellAsset:$({asset:R(),chain:R()})}),JA=$({channelId:R(),depositAddress:R()}),_A=zA.extend({affiliateFees:$({feeBps:t(),nearId:R()}).optional(),buyAsset:R(),sellAmount:R(),sellAsset:R(),slippage:UA.number(),sourceAddress:R()}),DA=$({amountIn:R(),amountInFormatted:R(),amountInUsd:R(),amountOut:R(),amountOutFormatted:R(),amountOutUsd:R(),deadline:R().optional(),minAmountIn:R(),minAmountOut:R(),timeEstimate:t().optional(),timeWhenInactive:R().optional()}),sL=DA.extend({depositAddress:R(),quote:DA,signature:R(),timestamp:R(),tx:MA()}),ZA=$({buyAsset:R(),buyAssetAmount:R(),buyAssetAmountMaxSlippage:R(),deadline:R().optional(),depositAddress:R(),depositAmount:R(),depositAsset:R(),tx:MA()}),SH=$({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=$({currentStage:R(),inboundConfirmation:t(),inboundObservation:t(),outboundDelay:t(),outboundObservation:t(),streamingSwap:t()}),QH=$({count:O(t()),interval:O(t()),quantity:O(t()),subSwapsMap:O(Q(t()))}),xH=L.object({currentLegIndex:L.optional(L.number()),estimatedTimeToComplete:L.number(),estimates:L.optional(XH),providerDetails:L.optional(L.object({streamingDetails:L.optional(QH)}))}),EH=$({affiliate:O(HN),liquidity:O(HN),network:O(HN),protocol:O(HN),tax:O(HN)}),wH=$({affiliate:R(),bps:R(),isReferrer:p()}),bH=$({affiliate:O(R()),affiliateFees:O(Q(wH)),broadcastedAt:O(t()),explorerUrl:O(R()),fees:O(EH),images:O($({chain:O(R()),from:O(R()),provider:O(R()),to:O(R())})),provider:O(L.enum(j)),providerAction:L.optional(L.enum(QA)),quoteId:O(R()),wallet:O(R())}),PN=L.object({block:L.number(),chainId:L.enum(BN),finalAddress:L.optional(L.string()),finalAsset:L.optional(HN),finalisedAt:L.number(),fromAddress:L.string(),fromAmount:L.string(),fromAsset:L.string(),hash:L.string(),meta:L.optional(bH),payload:L.optional(SH),status:L.enum(xA),toAddress:L.string(),toAmount:L.string(),toAsset:L.string(),trackingStatus:L.optional(L.enum(EA)),transient:L.optional(xH),type:L.enum(XA)}),jA=PN.extend({legs:L.array(PN)}),eL=PN.extend({legs:Q(PN)}),aL=PN.extend({legs:Q(PN)}),pN=Q($({amount:R(),asset:R(),chain:R(),protocol:L.enum(j),type:L.enum(zN)})),oN=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")}),vA=$({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")}),VA=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()}),zH=Q(KN([R(),t(),Q(R()),$({from:R(),value:R()}).describe("Parameters to pass to the contract method")])),NR=$({approvalSpender:O(R().describe("Address of the spender to approve")),approvalToken:O(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:Q(R().describe("Names of the parameters to pass to the contract method")),contractParams:zH}),JH=$({typeUrl:R("/types.MsgDeposit"),value:$({coins:Q($({amount:R(),asset:$({chain:R(),symbol:R(),synth:p(),ticker:R()})})),memo:R(),signer:R()})}),ZH=$({typeUrl:R("/types.MsgSend"),value:$({amount:Q($({amount:R(),denom:R()})),fromAddress:R(),toAddress:R()})}),jH=$({typeUrl:R(),value:ZH.or(JH)}),vH=$({amount:Q($({amount:R(),denom:R()})),gas:R()}),WA=$({accountNumber:t(),chainId:L.enum(BN),fee:vH,memo:R(),msgs:Q(jH),sequence:t()}),VH=L.array(L.object({calldata:L.array(L.string()),contractAddress:L.string(),entrypoint:L.string()})),qA=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")})),WH=$({affiliate:R().describe("Affiliate address").optional(),affiliateFee:t().describe("Affiliate fee").optional(),buyAsset:R().describe("Asset to buy"),destinationAddress:R().describe("Destination address"),estimatedTime:oN.optional(),provider:L.enum(j),sellAsset:R().describe("Asset to sell"),slipPercentage:t().describe("Slippage as a percentage"),sourceAddress:R().describe("Source address")}),AR=WH.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),qH=$({asset:R().describe("Asset name"),image:R().describe("Asset image"),price:t().describe("Price in USD")}),mH=MH,mA=$({assets:O(Q(qH)),maxStreamingQuantity:t().optional(),referrer:R().optional(),streamingInterval:t().optional(),tags:Q(L.enum(SA))}),kA=mA.extend({affiliate:O(R()),affiliateFee:O(R()),approvalAddress:O(R().describe("Approval address for swap")),chainflip:mH.optional(),garden:_A.optional(),near:_A.optional(),priceImpact:O(t().describe("Price impact")),referrer:O(R()),txType:O(L.enum(EN))}),KA=Q($({code:L.enum(bN),display:R(),tooltip:R().optional()})),kH=$({buyAmount:R().describe("Buy amount"),buyAmountMaxSlippage:R().describe("Buy amount max slippage"),buyAsset:R().describe("Asset to buy"),fees:O(pN),provider:L.enum(j),sellAmount:R().describe("Sell amount"),sellAsset:R().describe("Asset to sell")}),KH=$({buyAsset:R().describe("Asset to buy"),destinationAddress:O(R().describe("Destination address")),estimatedTime:O(oN),expectedBuyAmount:R().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:R().describe("Expected Buy amount max slippage"),expiration:O(R().describe("Expiration")),fees:pN,inboundAddress:O(R().describe("Inbound address")),legs:Q(kH),memo:O(R().describe("Memo")),meta:kA,providers:Q(L.enum(j)),routeId:R().describe("Route ID"),sellAmount:R().describe("Sell amount"),sellAsset:R().describe("Asset to sell"),sourceAddress:O(R().describe("Source address")),targetAddress:O(R().describe("Target address")),totalSlippageBps:t().describe("Total slippage in bps"),tx:O(KN([vA,WA,VA,VH,qA,R()])),txType:O(L.enum(EN)),warnings:KA}),pA=$({error:O(R().describe("Error message")),providerErrors:O(Q($({errorCode:O(L.enum(uN)),message:O(R()),provider:L.enum(j).optional()}))),quoteId:R().describe("Quote ID"),routes:Q(KH)}),oA=L.object({chainId:L.enum(BN),createdAt:L.date(),id:L.number(),unit:L.string(),value:L.string()}),pH=L.array(oA),yA=L.union([oA,pH]),TR=Q($({chain:L.enum(xN),decimal:t(),identifier:R(),symbol:R(),ticker:R(),value:R()})),HR=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()})]),PR=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()}),oH=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)")}),YA=L.object({buyAmount:L.string().describe("Buy amount"),buyAmountMaxSlippage:L.string().describe("Buy amount max slippage"),buyAsset:L.string().describe("Asset to buy"),expectedBuyAmount:L.string().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:L.string().describe("Expected Buy amount max slippage"),fees:pN,provider:L.enum(j),sellAmount:L.string().describe("Sell amount"),sellAsset:L.string().describe("Asset to sell")}),fA=YA.extend({estimatedTime:L.optional(oN),expiration:L.optional(L.string().describe("Expiration")),legs:L.array(YA),providers:L.array(L.enum(j)),routeId:L.string().describe("Route ID"),totalSlippageBps:L.number().describe("Total slippage in bps"),warnings:KA}).omit({provider:!0}),yH=L.object({method:L.string(),payload:L.optional(L.unknown()),url:L.string()}),fH=fA.extend({meta:mA,nextActions:L.optional(L.array(yH))}),LR=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(L.object({errorCode:L.optional(L.enum(uN)),message:L.optional(L.string()),provider:L.enum(j).optional()}))),quoteId:L.string().describe("Quote ID"),routes:L.array(fH)}),RR=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(xN).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")}),uR=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=fA.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:kA,sourceAddress:L.string().describe("Source address"),targetAddress:L.optional(L.string().describe("Target address")),tx:O(KN([vA,WA,VA,qA,R()])),txType:L.optional(L.enum(EN))}),dH=L.object({data:L.optional(L.record(L.string(),L.string().optional())),errorCode:L.enum(uN),message:L.string().optional(),provider:L.enum(j).optional()}),FR=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(dH)),quoteId:L.string().describe("Quote ID"),routes:L.array(CA)}),dA=CA.extend({approvalTx:oH.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=g.extend({dynamicHeader:async()=>{let N=E.get("widgetKey");if(N&&typeof window<"u"){let T=Math.floor(Date.now()/1000),H=window.location.origin;return{"X-Signature":await tA(N,H,T),"X-Timestamp":T.toString()}}let{swapKit:A}=E.get("apiKeys");return A?{"x-api-key":A}:{}}});async function rH(N){let A=await V.post(v("/track"),{json:N});try{let T=jA.safeParse(A);if(!T.success)throw new D("api_v2_invalid_response",T.error);return T.data}catch(T){return A}}async function lH(N){let{getQuote:A}=E.get("endpoints");if(A)return A(N);let H=E.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",P=await V.post(v(H),{json:N});if(P.error)throw new D("api_v2_server_error",{message:P.error});try{let F=pA.safeParse(P);if(!F.success)throw new D("api_v2_invalid_response",F.error);return F.data}catch{return P}}async function iH(N){let{getRouteWithTx:A}=E.get("endpoints");if(A)return A(N);let H=E.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",P=await V.post(v(H),{json:N});try{let F=dA.safeParse(P);if(!F.success)throw new D("api_v2_invalid_response",F.error);return F.data}catch(F){return console.error(new D("api_v2_invalid_response",F)),P}}async function sH({chain:N,address:A,scamFilter:T=!0}){let{getBalance:H}=E.get("endpoints");if(H)return H({address:A,chain:N});let P=v(`/balance?chain=${N}&address=${A}`),F=await V.get(P),I=Array.isArray(F)?F:[];return T?uP(I):I}function eH(N){let A=cH(N).with({routeId:$N.string,spender:$N.string},({routeId:T,spender:H})=>v(`/approve?routeId=${T}&sourceAddress=${H}`)).with({assetValue:$N.instanceOf(m),spender:$N.string,userWallet:$N.string},({spender:T,userWallet:H,assetValue:P})=>v(`/approve?tokenIdentifier=${P.toString()}&userWalletAddress=${H}&spender=${T}&amount=${P.getValue("string")}`)).exhaustive();return V.get(A)}function aH(){let N=v("/providers");return V.get(N)}function NP(N){let A=v(`/tokens?provider=${N}`);return V.get(A)}async function AP(N){let A=v("/price"),T=await V.post(A,{json:N});try{let H=bA.safeParse(T);if(!H.success)throw new D("api_v2_invalid_response",H.error);return H.data}catch(H){throw new D("api_v2_invalid_response",H)}}async function TP(){let N=v("/gas"),A=await V.get(N);try{let T=yA.safeParse(A);if(!T.success)throw new D("api_v2_invalid_response",T.error);return Array.isArray(T)?T:[T]}catch(T){throw new D("api_v2_invalid_response",T)}}async function HP(N){let{destinationAddress:A}=N;if(!A)throw new D("chainflip_broker_invalid_params");let T=E.get("integrations").chainflip?.brokerUrl||v("/chainflip/broker/channel"),H=await V.post(T,{json:N});try{let P=JA.safeParse(H);if(!P.success)throw new D("api_v2_invalid_response",P.error);return P.data}catch(P){throw new D("api_v2_invalid_response",P)}}async function PP(N){let{destinationAddress:A}=N;if(!A)throw new D("chainflip_broker_invalid_params");let T=v("/near/channel"),H=await V.post(T,{json:N});try{let P=ZA.safeParse(H);if(!P.success)throw new D("api_v2_invalid_response",P.error);return P.data}catch(P){throw new D("api_v2_invalid_response",P)}}function v(N){let{isDev:A,apiUrl:T,devApiUrl:H}=E.get("envs");return`${A?H:T}${N}`}function LP(N){let[A,T]=N.split(".");if(!hH.includes(A))return!0;let H=T.split("-"),P=H.length===1?void 0:H[H.length-1];return DN({chain:A,symbol:T})||!!P}var RP=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi");function uP(N){return N.filter((A)=>{return!RP.test(A.identifier)&&LP(A.identifier)})}async function FP(N){let{getSwapTo:A}=E.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=v(`/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 B=m.from({asset:I});F.push({chain:B.chain,identifier:B.toString(),providers:[],symbol:B.symbol,ticker:B.ticker})}catch{}return{buyAssets:F,sellAsset:N.sellAsset}}var fN={};cN(fN,{getThorchainQueue:()=>GP,getTcyStakers:()=>XP,getTcyStaker:()=>SP,getTcyClaimers:()=>xP,getTcyClaimer:()=>QP,getTNSPreferredAsset:()=>YP,getTHORNodeTNSDetails:()=>hA,getRunePoolProviderInfo:()=>MP,getRunePoolInfo:()=>UP,getNodes:()=>tP,getMimirInfo:()=>_P,getLastBlock:()=>gP,getInboundAddresses:()=>DP});import{MAYAConfig as IP,StagenetMAYAConfig as nP,StagenetTHORConfig as OP,THORConfig as BP}from"@swapkit/types";function k(N){let{isStagenet:A}=E.get("envs");switch(N){case"mayachain":return`${A?nP.nodeUrl:IP.nodeUrl}/mayachain`;default:return`${A?OP.nodeUrl:BP.nodeUrl}/thorchain`}}function $P(N){let A=N==="mayachain"?"mayaname":"thorname";return`${k(N)}/${A}`}function gP(N="thorchain"){return g.get(`${k(N)}/lastblock`)}function GP(N){return g.get(`${k(N)}/queue`)}function tP(N){return g.get(`${k(N)}/nodes`)}function _P(N){return g.get(`${k(N)}/mimir`)}function DP(N){return g.get(`${k(N)}/inbound_addresses`)}async function hA({type:N,name:A}){try{return await g.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 hA({name:A,type:N});if(!T.preferred_asset||T.preferred_asset===".")return;return m.from({asset:T.preferred_asset,asyncTokenLookup:!0})}function UP(N){return g.get(`${k(N)}/runepool`)}function MP({type:N,thorAddress:A}){return g.get(`${k(N)}/rune_provider/${A}`)}function SP({type:N,address:A}){return g.get(`${k(N)}/tcy_staker/${A}`)}function XP(N){return g.get(`${k(N)}/tcy_stakers`)}function QP({type:N,address:A}){return g.get(`${k(N)}/tcy_claimer/${A}`)}function xP(N){return g.get(`${k(N)}/tcy_claimers`)}var QR={...yN,mayachainMidgard:GA,thorchainMidgard:gA,thornode:fN};
5
- export{bP as a,uN as b,bN as c,j as d,zN as e,aA as f,NT as g,AT as h,JN as i,TT as j,vP as k,q as l,E as m,D as n,g as o,sP as p,eP as q,aP as r,NL as s,i as t,vN as u,ST as v,s as w,uL as x,$L as y,PA as z,DN as A,YN as B,VN as C,d as D,IN as E,gL as F,GL as G,RA as H,YL as I,c as J,y as K,m as L,ZL as M,XN as N,tA as O,SA as P,EN as Q,XA as R,QA as S,xA as T,EA as U,CL as V,dL as W,hL as X,cL as Y,HN as Z,wA as _,rL as $,bA as aa,lL as ba,iL as ca,zA as da,MH as ea,JA as fa,_A as ga,sL as ha,ZA as ia,jA as ja,eL as ka,aL as la,pN as ma,oN as na,vA as oa,VA as pa,zH as qa,NR as ra,WA as sa,VH as ta,qA as ua,WH as va,AR as wa,qH as xa,mH as ya,mA as za,kA as Aa,KA as Ba,KH as Ca,pA as Da,oA as Ea,yA as Fa,HR as Ga,PR as Ha,oH as Ia,LR as Ja,RR as Ka,CH as La,uR as Ma,CA as Na,dH as Oa,FR as Pa,dA as Qa,QR as Ra};
@@ -1,4 +0,0 @@
1
- var qP={};b(qP,{TxnType:()=>yN,TxnStatus:()=>CN,TronTransactionSchema:()=>aN,TransactionSchema:()=>yH,TransactionDTOSchema:()=>fH,TrackingStatus:()=>dN,TrackingRequestSchema:()=>bH,TrackingRequestQuerySchema:()=>zH,TrackerResponseSchema:()=>sN,TokenSchema:()=>wH,TokenDetailsMetadataSchema:()=>ZH,TONTransactionSchema:()=>AA,SwapToResponseSchema:()=>PP,SwapToRequestSchema:()=>HP,SwapToAssetSchema:()=>rA,SwapRouteV2ResponseSchema:()=>IA,SwapKitApi:()=>WP,StarknetTransactionSchema:()=>oA,RouteQuoteWarningSchema:()=>PA,RouteQuoteTxType:()=>$N,RouteQuoteProviderErrorSchema:()=>lA,RouteQuoteMetadataV2Schema:()=>HA,RouteQuoteMetadataSchema:()=>TA,RouteQuoteMetadataAssetSchema:()=>fA,RouteLegWithoutAddressesSchema:()=>lH,RouteLegSchema:()=>yA,QuoteV3ResponseSchema:()=>TP,QuoteV2ResponseSchema:()=>LP,QuoteRouteV2Response:()=>FA,QuoteResponseSchema:()=>LA,QuoteResponseRouteItem:()=>dA,QuoteRequestSchema:()=>jH,ProviderAction:()=>fN,PriorityLabel:()=>oN,PriceResponseSchema:()=>cN,PriceRequestSchema:()=>vH,NearSwapResponseSchema:()=>iN,NearDepositChannelResultSchema:()=>VH,NearDepositChannelParamsSchema:()=>pN,GasSchema:()=>RA,GasResponseSchema:()=>uA,FeesSchema:()=>bN,EstimatedTimeSchema:()=>zN,EVMTransactionSchema:()=>eN,EVMTransactionDetailsSchema:()=>CH,EVMTransactionDetailsParamsSchema:()=>pA,DepositChannelResponseSchema:()=>lN,DepositChannelParamsSchema:()=>rN,CosmosTransactionSchema:()=>NA,CoinGeckoMetadataSchema:()=>hN,ChainflipMetadataSchema:()=>CA,BrokerDepositChannelParamsSchema:()=>KA,AssetValueSchema:()=>l,ApproveResponseSchema:()=>aH,ApproveRequestParams:()=>eH,ApprovalTransactionSchema:()=>hA,ApiV2ErrorSchema:()=>JH});module.exports=VP(qP);var r=require("@swapkit/types");var iT={};b(iT,{getMinAmountByChain:()=>fT,AssetValue:()=>J});var G=require("@swapkit/types"),qN=require("ethers"),wN=require("ts-pattern");var vT={};b(vT,{parseSymbolForAddress:()=>NN,isGasAsset:()=>FN,getTokenLogoURI:()=>ZT,getCommonAssetInfo:()=>IN,getAssetType:()=>QN,findAssetBy:()=>jT,fetchTokenInfo:()=>vN,assetFromString:()=>p,CommonAssetStrings:()=>XT});var I=require("@swapkit/types"),a=require("ts-pattern");var BT={};b(BT,{RequestClient:()=>O});var HT={};b(HT,{swapKitConfigStore:()=>z,SKConfig:()=>S});var V=require("@swapkit/types"),YA=require("zustand/vanilla");var AT={};b(AT,{WarningCodeEnum:()=>DN,WalletOption:()=>UN,V3SwapFlowSupport:()=>NT,ProviderName:()=>w,NetworkDerivationPath:()=>aA,MemoType:()=>_A,LedgerErrorCode:()=>DA,FeeTypeEnum:()=>YN,FeeOption:()=>GA,ErrorCode:()=>e,ApproveMode:()=>tA});var _N=require("@swapkit/types"),aA=_N.AllChains.reduce((A,T)=>{return A[T]=_N.getChainConfig(T).networkDerivationPath,A},{});var e;((R)=>{R.unknownError="unknownError";R.test_error="test_error";R.providerDetailsError="providerDetailsError";R.blockHeaderNotFound="blockHeaderNotFound";R.blockHashNotFoundAtHeight="blockHashNotFoundAtHeight";R.blockHashNotFoundAtHash="blockHashNotFoundAtHash";R.txHashMissing="txHashMissing";R.assetValueMissingInfo="assetValueMissingInfo";R.invalidAsset="invalidAsset";R.blockIsRequired="blockIsRequired";R.currentBlockHeaderNotFound="currentBlockHeaderNotFound";R.failedToRetrieveBalance="failedToRetrieveBalance";R.failedToRetrieveBlock="failedToRetrieveBlock";R.failedToRetrieveFees="failedToRetrieveFees";R.notImplementedBCH="notImplementedBCH";R.notImplementedDoge="notImplementedDoge";R.noPoolsFound="noPoolsFound";R.noVaultsFound="noVaultsFound";R.noTxFound="noTxFound";R.noInputCoinFound="noInputCoinFound";R.noBlockDataFound="noBlockDataFound";R.multipleCosmosMessages="multipleCosmosMessages";R.heightOrHashNotProvided="heightOrHashNotProvided";R.unknownDenom="unknownDenom";R.invalidBlockHeight="invalidBlockHeight";R.timestampExtrinsicNoArgumentsForBlock="timestampExtrinsicNoArgumentsForBlock";R.timestampExtrinsicNoTimestampForBlock="timestampExtrinsicNoTimestampForBlock";R.noTimestampExtrinsicForHash="noTimestampExtrinsicForHash";R.timestampExtrinsicNoArgumentsForHash="timestampExtrinsicNoArgumentsForHash";R.txMemoUndefined="txMemoUndefined";R.txMemoIncorrect="txMemoIncorrect";R.txTypeNotFound="txTypeNotFound";R.txNoMessage="txNoMessage";R.txNotFound="txNotFound";R.txReceiptNotFound="txReceiptNotFound";R.txParsingError="txParsingError";R.txLogsParsingError="txLogsParsingError";R.blockNotFound="blockNotFound";R.balanceNotFound="balanceNotFound";R.configError="configError";R.synthSwapDisallowed="synthSwapDisallowed";R.providerQuoteTimeout="providerQuoteTimeout";R.noQuoteResponse="noQuoteResponse";R.noPoolAssetsFound="noPoolAssetsFound";R.noThorchainPools="noThorchainPools";R.noMayachainPools="noMayachainPools";R.noThorchainNetworkInfo="noThorchainNetworkInfo";R.invalidAffiliateFee="invalidAffiliateFee";R.invalidBuyAssetAddress="invalidBuyAssetAddress";R.invalidSellAssetAddress="invalidSellAssetAddress";R.invalidSourceAddress="invalidSourceAddress";R.invalidDestinationAddress="invalidDestinationAddress";R.sourceAddressIsSmartContract="sourceAddressIsSmartContract";R.destinationAddressIsSmartContract="destinationAddressIsSmartContract";R.invalidChainId="invalidChainId";R.unsupportedChainId="unsupportedChainId";R.unsupportedEVMChainId="unsupportedEVMChainId";R.unsupportedMethod="unsupportedMethod";R.unsupportedProvider="unsupportedProvider";R.invalidParamsForMethod="invalidParamsForMethod";R.unsupportedAdapter="unsupportedAdapter";R.noWhitelistTokens="noWhitelistTokens";R.failedFetchGasPrice="failedFetchGasPrice";R.failedToCreateDepositChannel="failedToCreateDepositChannel";R.noProviderDetailsFound="noProviderDetailsFound";R.noTokenListsFound="noTokenListsFound";R.tokenNotFound="tokenNotFound";R.tokenPriceNotFound="tokenPriceNotFound";R.tokenPriceFailedToUpdate="tokenPriceFailedToUpdate";R.swapAmountTooSmall="swapAmountTooSmall";R.legsArrayIsEmpty="legsArrayIsEmpty";R.failedToFetchQuoteForLeg="failedToFetchQuoteForLeg";R.noBlockHeaderFound="noBlockHeaderFound";R.failedToSimulateSwap="failedToSimulateSwap";R.addressScreeningFailed="addressScreeningFailed";R.noLiquidtyProvidersFound="noLiquidtyProvidersFound";R.insufficientLiquidity="insufficientLiquidity";R.noInboundDataFound="noInbounDataFound";R.noInboundAddressesFound="noInboundAddressesFound";R.noInboundAddressFoundForChain="noInboundAddressFoundForChain";R.noLastBlocksFound="noLastBlocksFound";R.noVersionFound="noVersionFound";R.noConstantsFound="noConstantsFound";R.noMimirsFound="noMimirsFound";R.noRoutesFound="noRoutesFound";R.quoteNotFound="quoteNotFound";R.ledgerSignFailed="ledgerSignFailed";R.ledgerWrongPayload="ledgerWrongPayload";R.ledgerFetchSwapFailed="ledgerFetchSwapFailed";R.failedToFetchTx="failedToFetchTx";R.failedBuildTransactionDetails="failedBuildTransactionDetails";R.noLegsForRoute="noLegsForRoute";R.noRouterAddressFound="noRouterAddressFound";R.noAggregatorAddressFound="noAggregatorAddressFound";R.noContractInstanceFound="noContractInstanceFound";R.noContractAddressFound="noContractAddressFound";R.invalidAffiliate="invalidAffiliate";R.thornameAffiliate="thornameAffiliate";R.providerNotfound="No provider found";R.noRecordFound="No Record found";R.slippageTooLow="Slippage too low";R.tradingHalted="tradingHalted";R.noWrappedGasAsset="noWrappedGasAsset";R.aggregatorAddressNotFound="aggregatorAddressNotFound";R.routerAddressNotFound="routerAddressNotFound";R.dummyAddressNotFound="dummyAddressNotFound";R.trackerError="trackerError";R.thorchainPoolUnavailable="thorchainPoolUnavailable";R.noOhlcvDataFound="noOhlcvDataFound";R.noTradingPairs="noTradingPairs";R.noLendingAvailability="noLendingAvailability";R.lendingRepayTooSmall="lendingRepayTooSmall";R.missingState="missingState";R.ledgerSwapNotFound="ledgerSwapNotFound";R.ledgerSwapNotReadyForTracking="ledgerSwapNotReadyForTracking";R.errorEstimatingGas="errorEstimatingGas";R.apiKeyInvalid="apiKeyInvalid";R.apiKeyFailedToUpdate="apiKeyFailedToUpdate";R.apiKeyExpired="apiKeyExpired";R.unauthorized="unauthorized";R.failedToCreateMemo="failedToCreateMemo";R.radixIncorrectInstructions="radixIncorrectInstructions";R.radixTxMissedParam="radixTxMissedParam";R.radixTxMissedAccount="radixTxMissedAccount";R.radixManifestParseError="radixManifestParseError";R.radixManifestBuildError="radixManifestBuildError";R.invalidAddressForChain="invalidAddressForChain";R.riskyAddress="riskyAddress";R.noRoutesToProcess="noRoutesToProcess";R.sellAssetAmountTooSmall="sellAssetAmountTooSmall";R.missingPrivateKey="missingPrivateKey";R.noMemoPriceProtection="noMemoPriceProtection"})(e||={});var DN;((H)=>{H.highSlippage="highSlippage";H.highPriceImpact="highPriceImpact"})(DN||={});var w;((M)=>{M.CHAINFLIP="CHAINFLIP";M.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";M.JUPITER="JUPITER";M.MAYACHAIN="MAYACHAIN";M.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";M.ONEINCH="ONEINCH";M.PANCAKESWAP="PANCAKESWAP";M.SUSHISWAP_V2="SUSHISWAP_V2";M.THORCHAIN="THORCHAIN";M.THORCHAIN_STREAMING="THORCHAIN_STREAMING";M.TRADERJOE_V2="TRADERJOE_V2";M.UNISWAP_V2="UNISWAP_V2";M.UNISWAP_V3="UNISWAP_V3";M.NEAR="NEAR";M.GARDEN="GARDEN";M.OKX="OKX";M.HARBOR="HARBOR"})(w||={});var YN;((B)=>{B.LIQUIDITY="liquidity";B.NETWORK="network";B.INBOUND="inbound";B.OUTBOUND="outbound";B.AFFILIATE="affiliate";B.TAX="tax";B.PRIORITY="priority";B.SERVICE="service"})(YN||={});var GA;((P)=>{P.Average="average";P.Fast="fast";P.Fastest="fastest"})(GA||={});var tA;((H)=>{H.Approve="approve";H.CheckOnly="checkOnly"})(tA||={});var _A;((t)=>{t.NAME_REGISTER="~";t.BOND="BOND";t.DEPOSIT="+";t.LEAVE="LEAVE";t.UNBOND="UNBOND";t.WITHDRAW="-";t.RUNEPOOL_DEPOSIT="POOL+";t.RUNEPOOL_WITHDRAW="POOL-";t.CLAIM_TCY="tcy";t.STAKE_TCY="tcy+";t.UNSTAKE_TCY="tcy-"})(_A||={});var $=require("@swapkit/types"),UN;((_)=>{_.BITGET="BITGET";_.BRAVE="BRAVE";_.COINBASE_MOBILE="COINBASE_MOBILE";_.COINBASE_WEB="COINBASE_WEB";_.COSMOSTATION="COSMOSTATION";_.CTRL="CTRL";_.EIP6963="EIP6963";_.EXODUS="EXODUS";_.KEEPKEY="KEEPKEY";_.KEEPKEY_BEX="KEEPKEY_BEX";_.KEPLR="KEPLR";_.KEYSTORE="KEYSTORE";_.LEAP="LEAP";_.LEDGER="LEDGER";_.METAMASK="METAMASK";_.OKX="OKX";_.OKX_MOBILE="OKX_MOBILE";_.ONEKEY="ONEKEY";_.PASSKEYS="PASSKEYS";_.PETRA="PETRA";_.PHANTOM="PHANTOM";_.POLKADOT_JS="POLKADOT_JS";_.RADIX_WALLET="RADIX_WALLET";_.TALISMAN="TALISMAN";_.TREZOR="TREZOR";_.TRONLINK="TRONLINK";_.TRUSTWALLET_WEB="TRUSTWALLET_WEB";_.VULTISIG="VULTISIG";_.WALLETCONNECT="WALLETCONNECT";_.WALLET_SELECTOR="WALLET_SELECTOR";_.XAMAN="XAMAN"})(UN||={});var DA;((P)=>{P[P.NoError=36864]="NoError";P[P.LockedDevice=21781]="LockedDevice";P[P.TC_NotFound=65535]="TC_NotFound"})(DA||={});var E=["BITGET","BRAVE","COINBASE_MOBILE","COINBASE_WEB","COSMOSTATION","CTRL","EIP6963","KEEPKEY","KEEPKEY_BEX","KEYSTORE","LEDGER","METAMASK","OKX","OKX_MOBILE","PASSKEYS","PHANTOM","TALISMAN","TREZOR","TRUSTWALLET_WEB","VULTISIG","WALLETCONNECT"],NT={[$.Chain.Arbitrum]:E,[$.Chain.Aurora]:E,[$.Chain.Avalanche]:E,[$.Chain.Base]:E,[$.Chain.Berachain]:E,[$.Chain.BinanceSmartChain]:E,[$.Chain.Botanix]:E,[$.Chain.Chainflip]:E,[$.Chain.Core]:E,[$.Chain.Corn]:E,[$.Chain.Cronos]:E,[$.Chain.Ethereum]:E,[$.Chain.Gnosis]:E,[$.Chain.Hyperevm]:E,[$.Chain.MegaETH]:E,[$.Chain.Monad]:E,[$.Chain.Optimism]:E,[$.Chain.Polygon]:E,[$.Chain.Sonic]:E,[$.Chain.Unichain]:E,[$.Chain.XLayer]:E,[$.Chain.Bitcoin]:["BITGET","KEYSTORE","OKX","ONEKEY","PASSKEYS","PHANTOM"],[$.Chain.BitcoinCash]:["KEYSTORE"],[$.Chain.Dash]:["KEYSTORE"],[$.Chain.Dogecoin]:["KEYSTORE"],[$.Chain.Litecoin]:["KEYSTORE"],[$.Chain.Zcash]:["KEYSTORE"],[$.Chain.Cosmos]:["COSMOSTATION","CTRL","KEPLR","KEYSTORE","LEAP"],[$.Chain.Kujira]:["COSMOSTATION","CTRL","KEPLR","KEYSTORE","LEAP"],[$.Chain.Maya]:["KEYSTORE"],[$.Chain.Noble]:["COSMOSTATION","CTRL","KEPLR","KEYSTORE","LEAP"],[$.Chain.THORChain]:["COSMOSTATION","KEPLR","KEYSTORE","LEAP"],[$.Chain.Aptos]:["BITGET","KEYSTORE","OKX","PETRA"],[$.Chain.Cardano]:["KEYSTORE"],[$.Chain.HyperCore]:["KEYSTORE"],[$.Chain.Near]:["KEYSTORE","LEDGER"],[$.Chain.Ripple]:["KEYSTORE","LEDGER"],[$.Chain.Solana]:["KEYSTORE","PASSKEYS","PHANTOM"],[$.Chain.Sui]:["KEYSTORE"],[$.Chain.Tron]:["KEYSTORE","LEDGER"],[$.Chain.Stellar]:["KEYSTORE"],[$.Chain.Starknet]:["KEYSTORE"]};var TT=V.AllChains.reduce((A,T)=>{if(!A.THOR_STAGENET)A[V.StagenetChain.Maya]=V.StagenetMAYAConfig.rpcUrls,A[V.StagenetChain.THORChain]=V.StagenetTHORConfig.rpcUrls;return A[T]=V.getChainConfig(T).rpcUrls,A},{}),UA={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:V.AllChains,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"}}},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:TT,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(UN),widgetKey:""},z=YA.createStore((A)=>({...UA,setApiKey:(T,H)=>A((P)=>({apiKeys:{...P.apiKeys,[T]:H}})),setConfig:(T)=>A((H)=>({apiKeys:{...H.apiKeys,...T?.apiKeys},chains:H.chains.concat(T?.chains||[]),endpoints:{...H.endpoints,...T?.endpoints},envs:{...H.envs,...T?.envs},feeMultipliers:T?.feeMultipliers||H.feeMultipliers,integrations:{...H.integrations,...T?.integrations},rpcUrls:{...H.rpcUrls,...T?.rpcUrls},v3SwapFlow:{...H.v3SwapFlow,...T?.v3SwapFlow},wallets:H.wallets.concat(T?.wallets||[]),widgetKey:T?.widgetKey||H.widgetKey})),setEndpoint:(T,H)=>A((P)=>({endpoints:{...P.endpoints,[T]:H}})),setEnv:(T,H)=>A((P)=>({envs:{...P.envs,[T]:H}})),setFeeMultipliers:(T)=>A(()=>({feeMultipliers:T})),setIntegrationConfig:(T,H)=>A((P)=>({integrations:{...P.integrations,[T]:H}})),setRequestOptions:(T)=>A((H)=>({requestOptions:{retry:{...H.requestOptions.retry,...T.retry},timeoutMs:T.timeoutMs||H.requestOptions.timeoutMs}})),setRpcUrl:(T,H)=>A((P)=>({rpcUrls:{...P.rpcUrls,[T]:H}})),setWidgetKey:(T)=>A({widgetKey:T})})),S={get:(A)=>z.getState()[A],getState:z.getState,reinitialize:()=>z.setState(UA),set:(A)=>z.getState().setConfig(A),setApiKey:(A,T)=>z.getState().setApiKey(A,T),setEndpoint:(A,T)=>z.getState().setEndpoint(A,T),setEnv:(A,T)=>z.getState().setEnv(A,T),setFeeMultipliers:(A)=>z.getState().setFeeMultipliers(A),setIntegrationConfig:(A,T)=>z.getState().setIntegrationConfig(A,T),setRequestOptions:(A)=>z.getState().setRequestOptions(A),setRpcUrl:(A,T)=>z.getState().setRpcUrl(A,T),setWidgetKey:(A)=>z.getState().setWidgetKey(A)};var LT={};b(LT,{SwapKitError:()=>g});var PT={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_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_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,not_implemented:99999};function ZN(A){return JSON.stringify(A,(T,H)=>typeof H==="bigint"?H.toString():H)}class g extends Error{static ErrorCode=PT;constructor(A,T){let H=typeof A==="string",P=H?A:A.errorKey,L=H?void 0:A.info,u=`${P}${L?`: ${ZN(L)}`:""}`;super(u);if(Object.setPrototypeOf(this,g.prototype),this.name="SwapKitError",this.cause=T,T){let F=T instanceof Error?`${T.message}${T.cause?` (${T.cause})`:""}`:ZN(T);console.error(`SwapKitError [${P}]: ${F}`)}else if(L)console.error(`SwapKitError [${P}]: ${ZN(L)}`)}}var RT=(A)=>new Promise((T)=>setTimeout(T,A)),uT=(A,{baseDelay:T,backoffMultiplier:H,maxDelay:P})=>Math.min(T*H**A,P);function FT(A,T){if(A instanceof Error&&A.name==="AbortError")return!0;if(A instanceof TypeError)return!0;if(T===429)return!0;if(T&&T>=500&&T<600)return!0;return!1}var IT=async(A,T)=>{let H=await fetch(A,T),P;try{P=await H.json()}catch{if(!H.ok)throw new g({errorKey:"helpers_invalid_response",info:{status:H.status,statusText:H.statusText}},{status:H.status,statusText:H.statusText});return{}}if(!H.ok){let u={data:P?.data,error:P?.error,message:P?.message,status:H.status};throw new g({errorKey:P?.error||"helpers_invalid_response",info:u},u)}let L=P?.routes?.length||P?.result||P?.data&&!P?.error;if(P?.error&&!L){let u={data:P.data,error:P.error,message:P.message,status:H.status};throw new g({errorKey:P.error,info:u},u)}if(P?.providerErrors?.length||P?.error&&L)console.warn("[SwapKit] Partial errors in response:",P.providerErrors||P.error);return P};function MN(A,T={}){return async function(P,L={}){let{searchParams:u,json:F,body:n,headers:B,dynamicHeader:D,retry:X,timeoutMs:t,abortController:v,onError:U,onSuccess:q,responseHandler:Q,...x}={...T,...L},M=S.get("requestOptions"),i={...M.retry,...X},gN=!!F||P.endsWith(".json"),GN=OT(P,u),BA=D?await D():{},uN=nT(gN,{...B,...BA}),s=gN?JSON.stringify(F):n,JN;for(let tN=0;tN<=i.maxRetries;tN++){let $A=v||new AbortController,gA=setTimeout(()=>$A.abort(),t||M.timeoutMs);try{let k=await IT(GN,{...x,body:s,headers:uN,method:A,signal:$A.signal});return clearTimeout(gA),q?.(k)||Q?.(k)||k}catch(k){clearTimeout(gA),JN=k;let eA=k?.cause?.status;if(tN>=i.maxRetries||!FT(k,eA))return U?U(k):Promise.reject(k);await RT(uT(tN,i))}}return U?U(JN):Promise.reject(JN)}}function nT(A,T){return{...T,...A&&{"Content-Type":"application/json"}}}function OT(A,T){let H=new URL(A);if(T)H.search=new URLSearchParams(T).toString();return H.toString()}var O={extend:(A)=>({extend:(T)=>O.extend({...A,...T}),get:MN("GET",A),post:MN("POST",A)}),get:MN("GET"),post:MN("POST")};var ST={};b(ST,{initializeRPCUrlsWithFallback:()=>MT,getRPCUrlSync:()=>XA,getRPCUrl:()=>h,_rpcCache:()=>XN});var Y=require("@swapkit/types"),jN=require("ts-pattern");var _T={};b(_T,{wrapWithThrow:()=>GT,warnOnce:()=>d,getTHORNameCost:()=>$T,getMAYANameCost:()=>gT,getChainIdentifier:()=>tT});var SN=require("@swapkit/types");function $T(A){if(A<0)throw new g({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:A}});return 10+A}function gT(A){if(A<0)throw new g({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:A}});return Math.round((10+A*1.0512)*10000000000)/10000000000}function GT(A,T){try{return A()}catch(H){if(T)throw new g(T,H);return}}function tT(A){switch(A){case SN.Chain.THORChain:return`${A}.RUNE`;case SN.Chain.Cosmos:return`${A}.ATOM`;case SN.Chain.BinanceSmartChain:return`${A}`;default:return`${A}.${A}`}}var MA=new Set;function d({condition:A,id:T,warning:H}){if(A){if(MA.has(T))return;console.warn(H),MA.add(T)}}function DT(A){return jN.match(A).with(...Y.EVMChains,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...Y.UTXOChains,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...Y.CosmosChains,...Y.StagenetChains,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(Y.Chain.Polkadot,Y.Chain.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(Y.Chain.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(Y.Chain.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(Y.Chain.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(Y.Chain.Aptos,Y.Chain.Tron,Y.Chain.Radix,Y.Chain.Stellar,()=>"").with(Y.Chain.HyperCore,()=>({type:"meta"})).with(Y.Chain.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(Y.Chain.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(Y.Chain.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new g("helpers_chain_not_supported",{chain:A})})}function YT(A){return jN.match(A).with(Y.Chain.Aptos,()=>"/-/healthy").with(Y.Chain.HyperCore,()=>"/info").with(Y.Chain.Radix,()=>"/status/network-configuration").with(Y.Chain.Stellar,()=>"").with(Y.Chain.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function SA(A,T){try{let H=T.startsWith("wss")?T.replace("wss","https"):T;return(await fetch(`${H}${YT(A)}`,{body:JSON.stringify(DT(A)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var XN=new Map,UT=120000;function XA(A){let[T=""]=S.get("rpcUrls")[A];if(!T)throw d({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 ${A}.`}),new g("helpers_chain_no_public_or_set_rpc_url",{chain:A});let H=XN.get(A);if(H&&Date.now()-H.timestamp<UT)return H.url;return XN.set(A,{timestamp:Date.now(),url:T}),T}async function h(A){let T=XA(A),[,...H]=S.get("rpcUrls")[A];if(await SA(A,T))return T;for(let L of H)if(await SA(A,L))return XN.set(A,{timestamp:Date.now(),url:L}),L;throw new g("helpers_chain_rpc_connection_failed",{chain:A,fallbackUrls:H,primaryRpcUrl:T})}function MT(A){d({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 XT=[`${I.Chain.Maya}.MAYA`,`${I.Chain.Maya}.CACAO`,`${I.Chain.Ethereum}.THOR`,`${I.Chain.Ethereum}.vTHOR`,`${I.Chain.Kujira}.USK`,`${I.Chain.Ethereum}.FLIP`,`${I.Chain.Radix}.XRD`],EA=[I.Chain.Arbitrum,I.Chain.Aurora,I.Chain.Base,I.Chain.Ethereum,I.Chain.Optimism];async function QT(A){let{baseDecimal:T}=I.getChainConfig(I.Chain.Radix);try{let H=await h(I.Chain.Radix),{manager:P}=await O.post(`${H}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:A}),headers:{Accept:"*/*","Content-Type":"application/json"}});return P?.divisibility?.value?.divisibility}catch(H){let P=H instanceof Error?H.message:String(H);return console.warn(`Failed to fetch Radix asset decimals for ${A}: ${P}`),T}}async function xT(A){try{let T=await h(I.Chain.Radix);return(await O.post(`${T}/state/entity/details`,{body:JSON.stringify({addresses:[A],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((L)=>L.key==="symbol")?.value.typed.value||void 0}catch(T){let H=T instanceof Error?T.message:String(T);return console.warn(`Failed to fetch Radix asset symbol for ${A}: ${H}`),""}}async function wA({chain:A,address:T,methodHex:H,id:P}){let L=await h(A);return O.post(L,{body:JSON.stringify({id:P,jsonrpc:"2.0",method:"eth_call",params:[{data:H,to:T.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}async function ET(A){if(!A||A==="0x")return"UNKNOWN";try{let{AbiCoder:T}=await import("ethers");return T.defaultAbiCoder().decode(["string"],A)[0].trim()}catch(T){return console.warn(`Failed to decode ABI string from ${A}: ${T}`),"UNKNOWN"}}function wT(A,T){if(!A||A==="0x")return T;try{return Number(A)}catch(H){return console.warn(`Failed to decode ABI uint8 from ${A}: ${H}`),T}}async function bT({chain:A,address:T}){let{baseDecimal:H}=I.getChainConfig(A),P=T.toLowerCase();if(T===""||!P.startsWith("0x"))return H;let L=await wA({address:T,chain:A,id:2,methodHex:"0x313ce567"}).catch((F)=>{return console.warn(`Could not fetch decimals for ${T} on ${A}: ${F.message}`),{result:""}});return wT(L.result,H)}async function zT({chain:A,address:T}){let H=T.toLowerCase();if(H===""||!H.startsWith("0x"))return;let P=await wA({address:T,chain:A,id:1,methodHex:"0x95d89b41"}).catch((u)=>{return console.warn(`Could not fetch symbol for ${T} on ${A}: ${u.message}`),{result:""}});return await ET(P.result)}async function QA({rpcUrl:A,contractAddress:T,functionSelector:H}){return(await O.post(`${A}/wallet/triggerconstantcontract`,{body:JSON.stringify({contract_address:T,function_selector:H,owner_address:T,parameter:"",visible:!0}),headers:{accept:"application/json","content-type":"application/json"}}).catch(()=>{return}))?.constant_result?.[0]}function xA(A){let T=A.match(/.{2}/g)?.map((H)=>Number.parseInt(H,16))??[];return new TextDecoder().decode(new Uint8Array(T))}function JT(A){return a.match(A).with(void 0,()=>{return}).when((T)=>T.length>=128,(T)=>{let H=Number.parseInt(T.slice(64,128),16);return xA(T.slice(128,128+H*2))}).when((T)=>T.length===64,(T)=>{let H=T.replace(/0+$/,"");if(H.length>0&&H.length%2===0)return xA(H);return}).otherwise(()=>{return})}function vN({chain:A,address:T}){let{baseDecimal:H}=I.getChainConfig(A),P={decimals:H,ticker:void 0};return a.match(A).with(...I.EVMChains,async()=>{try{let{isAddress:L,getAddress:u}=await import("ethers");if(!L(u(T.replace(/^0X/,"0x"))))return P;let[F,n]=await Promise.all([zT({address:T,chain:A}),bT({address:T,chain:A})]);return{decimals:n,ticker:F}}catch(L){return console.warn(`Failed to fetch token info for ${T} on ${A}: ${L?.code} ${L?.message}`),P}}).with(I.Chain.Solana,async()=>{if(!T)return P;try{let L=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${T}`);if(L.ok){let u=await L.json(),F=Array.isArray(u)?u[0]:u;if(F)return{decimals:F.decimals??H,ticker:F.symbol||void 0}}}catch(L){console.warn(`Failed to fetch Solana token info for ${T}: ${L?.code} ${L?.message}`)}return P}).with(I.Chain.Tron,async()=>{if(!T)return P;try{let L=await h(I.Chain.Tron),[u,F]=await Promise.all([QA({contractAddress:T,functionSelector:"symbol()",rpcUrl:L}),QA({contractAddress:T,functionSelector:"decimals()",rpcUrl:L})]),n=JT(u);return{decimals:u!==void 0&&F?Number(BigInt(`0x${F}`)):H,ticker:n}}catch(L){let u=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Tron token info for ${T}: ${u}`),P}}).with(I.Chain.Near,async()=>{if(!T)return P;try{let{JsonRpcProvider:L}=await import("@near-js/providers"),u=await h(I.Chain.Near),n=await new L({url:u}).query({account_id:T,args_base64:Buffer.from("{}").toString("base64"),finality:"final",method_name:"ft_metadata",request_type:"call_function"}),B=JSON.parse(Buffer.from(n.result).toString());return{decimals:B?.decimals||H,ticker:B?.symbol}}catch(L){let u=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Near token info for ${T}: ${u}`),P}}).with(I.Chain.Radix,async()=>{if(!T)return P;try{let[L,u]=await Promise.all([xT(T),QT(T)]);return{decimals:u,ticker:L}}catch(L){let u=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Radix token info for ${T}: ${u}`),P}}).otherwise(async()=>P)}function FN({chain:A,symbol:T}){return a.match(A).with(...EA,()=>T==="ETH").with(I.Chain.Avalanche,()=>T==="AVAX").with(I.Chain.Berachain,()=>T==="BERA").with(I.Chain.Hyperevm,()=>T==="HYPE").with(I.Chain.HyperCore,()=>T==="HYPE").with(I.Chain.BinanceSmartChain,()=>T==="BNB").with(I.Chain.Gnosis,()=>T==="xDAI"||T==="XDAI").with(I.Chain.Monad,()=>T==="MON").with(I.Chain.XLayer,()=>T==="OKB").with(I.Chain.Maya,()=>T==="CACAO").with(I.Chain.Cosmos,()=>T==="ATOM").with(I.Chain.THORChain,()=>T==="RUNE").with(I.Chain.Tron,()=>T==="TRX").with(I.Chain.Ripple,()=>T==="XRP").with(I.Chain.Radix,()=>`${A}.${T}`===IN(A).identifier).otherwise(()=>T===A)}var IN=(A)=>{let{baseDecimal:T}=I.getChainConfig(A);return a.match(A.toUpperCase()).with(...EA,(P)=>({decimal:T,identifier:`${P}.ETH`})).with(I.Chain.THORChain,(P)=>({decimal:T,identifier:`${P}.RUNE`})).with(I.Chain.Cosmos,(P)=>({decimal:T,identifier:`${P}.ATOM`})).with(I.Chain.Maya,(P)=>({decimal:10,identifier:`${P}.CACAO`})).with(I.Chain.BinanceSmartChain,(P)=>({decimal:T,identifier:`${P}.BNB`})).with(I.Chain.Monad,(P)=>({decimal:T,identifier:`${P}.MON`})).with(I.Chain.Avalanche,(P)=>({decimal:T,identifier:`${P}.AVAX`})).with(I.Chain.Gnosis,(P)=>({decimal:T,identifier:`${P}.xDAI`})).with(I.Chain.XLayer,(P)=>({decimal:T,identifier:`${P}.OKB`})).with(I.Chain.Berachain,(P)=>({decimal:T,identifier:`${P}.BERA`})).with(I.Chain.Hyperevm,(P)=>({decimal:T,identifier:`${P}.HYPE`})).with(I.Chain.HyperCore,(P)=>({decimal:T,identifier:`${P}.HYPE`})).with(I.Chain.Tron,(P)=>({decimal:T,identifier:`${P}.TRX`})).with(I.Chain.Solana,I.Chain.Chainflip,I.Chain.Kujira,I.Chain.Ripple,I.Chain.Polkadot,I.Chain.Near,...I.UTXOChains,(P)=>({decimal:T,identifier:`${P}.${P}`})).with(I.Chain.Radix,"XRD.XRD",()=>({decimal:T,identifier:"XRD.XRD"})).with(I.Chain.Polygon,"POL.POL",()=>({decimal:T,identifier:"POL.POL"})).with("KUJI.USK",(P)=>({decimal:6,identifier:P})).with("ETH.FLIP",()=>({decimal:I.getChainConfig(I.Chain.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:I.getChainConfig(I.Chain.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:I.getChainConfig(I.Chain.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(P)=>({decimal:10,identifier:P})).with("MAYA.MAYA",(P)=>({decimal:4,identifier:P})).otherwise(()=>({decimal:T,identifier:A}))};function QN({chain:A,symbol:T}){if(T.includes("/"))return"Synth";if(T.includes("~"))return"Trade";return a.match(A).with(I.Chain.Radix,()=>T===I.Chain.Radix||`${A}.${T}`===IN(A).identifier).with(I.Chain.Arbitrum,I.Chain.Optimism,I.Chain.Base,I.Chain.Aurora,()=>T===I.Chain.Ethereum).with(I.Chain.Cosmos,()=>T==="ATOM").with(I.Chain.BinanceSmartChain,()=>T==="BNB").with(I.Chain.Maya,()=>T==="CACAO").with(I.Chain.Monad,()=>T==="MON").with(I.Chain.THORChain,()=>T==="RUNE").with(I.Chain.Tron,()=>T==="TRX").with(I.Chain.Hyperevm,()=>T==="HYPE").with(I.Chain.HyperCore,()=>T==="HYPE").with(I.Chain.XLayer,()=>T==="OKB").otherwise(()=>T===A)?"Native":A}var p=(A)=>{let[T,...H]=A.split("."),P=A.includes("/"),L=H.join("."),u=L?.split("-"),F=u?.length?u.length===1?u[0]:u.slice(0,-1).join("-"):void 0;return{chain:T,symbol:L,synth:P,ticker:F}};function NN(A,T){let P=T===I.Chain.Near?A.indexOf("-"):A.lastIndexOf("-");if(P===-1)return{address:void 0,ticker:A};return{address:A.slice(P+1),ticker:A.slice(0,P)}}function ZT(A){return`https://storage.googleapis.com/token-list-swapkit-dev/images/${A.toLowerCase()}.png`}async function jT(A){let{loadTokenLists:T}=await import("././tokens.cjs"),H=await T(),P=Object.values(H).flatMap((u)=>u.tokens);if("identifier"in A)return P.find((u)=>u.identifier===A.identifier)?.identifier;let L=A.contract.toLowerCase();for(let u of P){let{chain:F,symbol:n}=p(u.identifier);if(F!==A.chain)continue;let{address:B}=NN(n,F);if(B?.toLowerCase()===L)return u.identifier}return}var WT={};b(WT,{validateTNS:()=>VT,validateIdentifier:()=>VN});var bA=["TERRA",...S.get("chains")];function VN(A=""){let T=A.toUpperCase(),[H]=T.split(".");if(bA.includes(H))return!0;let[P]=T.split("/");if(bA.includes(P))return!0;throw new g({errorKey:"helpers_invalid_identifier",info:{identifier:A,message:`Invalid identifier: ${A}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}function VT(A){if(A.length>30)return!1;let T=/^[a-zA-Z0-9+_-]+$/g;return!!A.match(T)}var KT={};b(KT,{formatBigIntToSafeValue:()=>o,BigIntArithmetics:()=>K});var ON=require("ts-pattern"),AN=8,qT=10;function o({value:A,bigIntDecimal:T=AN,decimal:H=AN}){if(H===0)return A.toString();let P=A<0n,L=A.toString().substring(P?1:0),u=H-(L.length-1);if(u>0)L="0".repeat(u)+L;let F=L.length-H,n=L.slice(-H);if(Number.parseInt(n[T]||"0",10)>=5){let D=Number.parseInt(n[T-1]||"0",10);n=`${n.substring(0,T-1)}${D+1}`}else n=n.substring(0,T);return`${P?"-":""}${L.slice(0,F)}.${n}`.replace(/\.?0*$/,"")}class K{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(A,T){return new K({decimal:T,value:o({bigIntDecimal:T,decimal:T,value:A})})}static shiftDecimals({value:A,from:T,to:H}){return K.fromBigInt(A.getBaseValue("bigint")*c(H)/c(T),H)}constructor(A){let T=WN(A),H=typeof A==="object";this.decimal=H?A.decimal:void 0,this.decimalMultiplier=H&&"decimalMultiplier"in A?A.decimalMultiplier:c(Math.max(zA(xN(T)),this.decimal||0)),this.#P(T)}set(A){return new this.constructor({decimal:this.decimal,identifier:this.toString?.({includeSynthProtocol:!0}),value:A})}add(...A){return this.#A("add",...A)}sub(...A){return this.#A("sub",...A)}mul(...A){return this.#A("mul",...A)}div(...A){return this.#A("div",...A)}gt(A){return this.#N("gt",A)}gte(A){return this.#N("gte",A)}lt(A){return this.#N("lt",A)}lte(A){return this.#N("lte",A)}eqValue(A){return this.#N("eqValue",A)}getValue(A,T){let H=nN(this.decimalMultiplier),P=T!==void 0?T:this.decimal,L=P!==void 0?P:H;if(P!==void 0&&P<H){if(this.formatBigIntToSafeValue(this.bigIntValue,P)==="0"&&this.bigIntValue!==0n)L=H}let u=this.formatBigIntToSafeValue(this.bigIntValue,L);return ON.match(A).with("number",()=>Number(u)).with("string",()=>u).with("bigint",()=>{return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}).otherwise(()=>u)}getBaseValue(A,T){let H=this.decimalMultiplier/c(T||this.decimal||AN),P=kT(this.bigIntValue,H);return ON.match(A).with("number",()=>Number(P)).with("string",()=>P.toString()).otherwise(()=>P)}getBigIntValue(A,T){if(!T&&typeof A==="object")return A.bigIntValue;let H=WN(A),P=xN(H);if(P==="0"||P==="undefined")return 0n;return this.#H(P,T)}toSignificant(A=6){let T=this.getValue("string"),[H="",P=""]=T.split("."),L=Number.parseInt(H,10)>0;if((L?H.length+P.length:P.length)<=A)return T;if(H.length>=A)return H.slice(0,A).padEnd(H.length,"0");if(L)return`${H}.${P.slice(0,A-H.length)}`;let F=Number.parseInt(P,10).toString(),n=F.slice(0,A),B=P.length-F.length;return`0.${n.padStart(B+n.length,"0")}`}toFixed(A=6){let T=this.getValue("string"),H=T.startsWith("-"),[P="0",L=""]=(H?T.slice(1):T).split("."),u=P==="0"&&Number.parseInt(L.slice(0,A),10)===0,F=H&&!u?"-":"";if(A===0){if(P==="0"&&!L)return"0";return L&&Number.parseInt(L[0]||"0",10)>=5?`${F}${BigInt(P)+1n}.0`:`${F}${P}.0`}if(!L)return`${F}${P}.${"0".repeat(A)}`;let n=L[A];if(!(n&&Number.parseInt(n,10)>=5))return`${F}${P}.${L.slice(0,A).padEnd(A,"0")}`;let D=BigInt(L.slice(0,A).padEnd(A,"0"))+1n,X=10n**BigInt(A);if(D>=X)return`${F}${BigInt(P)+1n}.${"0".repeat(A)}`;return`${F}${P}.${D.toString().padStart(A,"0")}`}toAbbreviation(A=2){let T=this.getValue("string"),H=Number(T),P=["","K","M","B","T","Q","Qi","S"],L=Math.floor(Math.log10(Math.abs(H))/3);if(L===0||!P[L])return T;return`${(H/10**(L*3)).toFixed(A)}${P[L]}`}toCurrency(A="$",{currencyPosition:T="start",decimal:H=2,decimalSeparator:P=".",thousandSeparator:L=",",trimTrailingZeros:u=!0}={}){let F=this.toFixed(H),n=T==="end",[B="0",D=""]=F.split("."),X=B.replace(/\B(?=(\d{3})+(?!\d))/g,L),t=D&&Number.parseInt(D,10)>0,v=t?`${X}${P}${D}`:X,q=v.length<100&&u&&t?v.replace(/\.?0*$/,""):v;return n?`${q}${A}`:`${A}${q}`}formatBigIntToSafeValue(A,T){let H=T||this.decimal||AN,P=Math.max(H,nN(this.decimalMultiplier));return o({bigIntDecimal:H,decimal:P,value:A})}#A(A,...T){let H=this.#T(this,...T),P=nN(this.decimalMultiplier),u=Math.max(H,P)+qT,F=c(u),n=T.reduce((D,X)=>{let t=this.getBigIntValue(X,u);return ON.match(A).with("add",()=>D+t).with("sub",()=>D-t).with("mul",()=>D*t/F).with("div",()=>{if(t===0n)throw RangeError("Division by zero");return D*F/t}).otherwise(()=>D)},this.bigIntValue*F/this.decimalMultiplier),B=o({bigIntDecimal:u,decimal:u,value:n});return new this.constructor({decimal:this.decimal,decimalMultiplier:c(u),identifier:this.toString(),value:B})}#N(A,...T){let H=this.#T(this,...T),P=this.getBigIntValue(T[0]||"0",H),L=this.getBigIntValue(this,H);return ON.match(A).with("gt",()=>L>P).with("gte",()=>L>=P).with("lt",()=>L<P).with("lte",()=>L<=P).with("eqValue",()=>L===P).otherwise(()=>!1)}#P(A){let T=xN(A)||"0";this.bigIntValue=this.#H(T)}#T(...A){let T=A.map((H)=>{return typeof H==="object"?H.decimal||nN(H.decimalMultiplier):zA(xN(H))}).filter(Boolean);return Math.max(...T,AN)}#H(A,T){let H=T?c(T):this.decimalMultiplier,P=nN(H),[L="",u=""]=A.split(".");return BigInt(`${L}${u.padEnd(P,"0")}`)}}var mT=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function xN(A){let H=`${typeof A==="number"?mT.format(A):WN(A)}`.replaceAll(",",".").split(".");return H.length>1?`${H.slice(0,-1).join("")}.${H.at(-1)}`:H[0]||"0"}function zA(A){let T=A.split(".")[1]?.length||0;return Math.max(T,AN)}function WN(A){return typeof A==="object"?"getValue"in A?A.getValue("string"):A.value:A}function kT(A,T){if(T===0n)throw Error("Cannot divide by zero");let H=T/2n;return A>=0n&&T>=0n||A<0n&&T<0n?(A+H)/T:(A-H)/T}function c(A){return 10n**BigInt(A)}function nN(A){return Math.log10(Number.parseFloat(A.toString()))}var y=[G.Chain.HyperCore,G.Chain.Near,G.Chain.Ripple,G.Chain.Solana,G.Chain.Sui,G.Chain.Ton,G.Chain.Tron],kN=[G.Chain.THORChain,G.Chain.Maya],TN=new Map,EN=new Map,HN=new Map,pT=3600000;function oT(A){let T=HN.get(A);if(T?.timestamp&&Date.now()-T.timestamp>pT){HN.delete(A);return}return T}function yT(A,T){if(HN.size>1000){let H=HN.keys().next().value;if(H)HN.delete(H)}HN.set(A,{...T,timestamp:Date.now()})}class J extends K{address;chain;isGasAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:A,decimal:T,tax:H,chain:P,symbol:L,identifier:u}){super(typeof A==="object"?A:{decimal:T,value:A});let F=JA(u||`${P}.${L}`);this.type=QN(F),this.tax=H,this.chain=F.chain,this.ticker=F.ticker,this.symbol=F.symbol,this.address=F.address,this.isSynthetic=F.isSynthetic,this.isTradeAsset=F.isTradeAsset,this.isGasAsset=F.isGasAsset,this.chainId=G.getChainConfig(F.chain).chainId}toString({includeSynthProtocol:A}={}){return(this.isSynthetic||this.isTradeAsset)&&!A?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 A=this.symbol.replace(/\./g,"__");return`${this.chain}.${A}`}getIconUrl(){return TN.get(this.toString())?.logoURI}eqAsset({chain:A,symbol:T}){return this.chain===A&&this.symbol===T}eq(A){return this.eqAsset(A)&&this.eqValue(A)}static fromUrl(A,T=0){let H=A.indexOf(".");if(H===-1)throw new g({errorKey:"helpers_invalid_asset_url",info:{urlAsset:A}});let P=A.slice(0,H),L=A.slice(H+1),u=wN.match({chain:P,rest:L}).when(({rest:F})=>F.includes(".."),({chain:F,rest:n})=>`${F}.${n.replace(/\.\./g,"~")}`).when(({chain:F,rest:n})=>kN.includes(F)&&n.includes("."),({chain:F,rest:n})=>`${F}.${n.replace(/\./g,"/")}`).otherwise(({chain:F,rest:n})=>`${F}.${n.replace(/__/g,".")}`);return J.from({asset:u,value:T})}static from({value:A=0,fromBaseDecimal:T,asyncTokenLookup:H,...P}){let L=A instanceof K?A.getValue("string"):A,u=cT(P),F=!u.startsWith(G.Chain.Sui)&&u.includes(":");if(H&&F){let[uN,s]=u.split(":");return dT({address:s,chain:uN,fromBaseDecimal:T,parsedValue:L})}let n=F?u.split(":").join(".UNKNOWN-"):u,{identifier:B,decimal:D}=IN(n),{chain:X,isSynthetic:t,isTradeAsset:v,address:U}=JA(B),{baseDecimal:q}=G.getChainConfig(X),Q=TN.get(y.includes(X)?B:B.toUpperCase());if(!Q&&H&&!t&&!v)return(async()=>{let{ticker:uN}=p(B),s=await ZA({address:U,chain:X,ticker:uN});return mN({decimal:s.decimals,identifier:s.identifier,value:T?PN(BigInt(L),T):L})})();let x=Q?.decimal||D;d({condition:!x&&!H,id:`assetValue_static_decimal_not_found_${X}`,warning:`Couldn't find static decimal for one or more tokens on ${X} (Using default ${q} 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:M,identifier:i,tax:gN}=Q||{decimal:x||q,identifier:B},GN=T?PN(BigInt(L),T):PN(L,M);return t||v?CT(i,GN):mN({decimal:M,identifier:i,tax:gN,value:GN})}static async loadStaticAssets(A){let{loadTokenLists:T}=await import("@swapkit/tokens"),H=await T(A);for(let{tokens:P}of Object.values(H))for(let L of P){let{identifier:u}=L,{chain:F,symbol:n}=p(u),{address:B}=NN(n,F),{baseDecimal:D}=G.getChainConfig(F),X=y.includes(F)?u:u.toUpperCase(),t="decimals"in L&&L.decimals!==void 0?L.decimals:D,v="logoURI"in L&&L.logoURI?L.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${u.toLowerCase()}.png`,U={decimal:t,identifier:u,logoURI:v,tax:"tax"in L?L.tax:void 0};if(TN.set(X,U),B){let q=y.includes(F)?`${F}:${B}`:`${F}:${B.toUpperCase()}`;EN.set(q,u)}}return!0}static setStaticAssets(A){TN.clear(),EN.clear();for(let[T,H]of A.entries()){let{identifier:P}=H,{chain:L,symbol:u}=p(P),{address:F}=NN(u,L),{baseDecimal:n}=G.getChainConfig(L),B=H.chain??L,D=H.address??F,X=y.includes(B)?P:P.toUpperCase(),t=H.decimals??H.decimal??n,v=H.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${P.toLowerCase()}.png`,U={decimal:t,identifier:X,logoURI:v,tax:H.tax};if(TN.set(X,U),D){let q=y.includes(B)?`${B}:${D}`:`${B}:${D.toUpperCase()}`;EN.set(q,P)}}return!0}static get staticAssets(){return TN}}function fT(A){let T=J.from({chain:A});return wN.match(A).with(G.Chain.Bitcoin,G.Chain.Litecoin,G.Chain.BitcoinCash,G.Chain.Dash,()=>T.set(0.00010001)).with(G.Chain.Dogecoin,()=>T.set(1.00000001)).with(G.Chain.Avalanche,G.Chain.Ethereum,G.Chain.Arbitrum,G.Chain.BinanceSmartChain,()=>T.set(0.00000001)).with(G.Chain.THORChain,G.Chain.Maya,()=>T.set(0)).with(G.Chain.Cosmos,G.Chain.Kujira,()=>T.set(0.000001)).otherwise(()=>T.set(0.00000001))}async function ZA({chain:A,address:T,ticker:H}){let L=y.includes(A)?`${A}:${T||H}`:`${A}:${T||H}`.toUpperCase(),u=oT(L);if(u)return u;if(!T){let{baseDecimal:B}=G.getChainConfig(A);return{decimals:B,identifier:`${A}.${H||"UNKNOWN"}`}}let F=await vN({address:T,chain:A}),n=`${A}.${F.ticker||H||"UNKNOWN"}-${T}`;return d({condition:!!(!F.ticker&&H),id:`async_token_lookup_failed_${A}_${T}`,warning:`Could not fetch token metadata for ${A}:${T} from chain. Using user-provided ticker (${H}) with baseDecimal (${F.decimals}).`}),F.ticker&&yT(L,{decimals:F.decimals,identifier:n}),{decimals:F.decimals,identifier:n}}function mN({identifier:A,decimal:T,value:H,tax:P}){return VN(A),new J({decimal:T,identifier:A,tax:P,value:PN(H,T)})}function CT(A,T=0){let H=A.includes(".")?A.split(".")?.[0]?.toUpperCase():void 0,P=H?kN.includes(H):!1,L=A.slice(0,14).includes("~")?"~":"/",[u,F]=P?A.split(".").slice(1).join().split(L):A.split(L);if(!(u&&F))throw new g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:A}});return new J({decimal:8,identifier:`${H||G.Chain.THORChain}.${u}${L}${F}`,value:PN(T,8)})}async function dT({address:A,chain:T,fromBaseDecimal:H,parsedValue:P}){let{decimals:L,identifier:u}=await ZA({address:A,chain:T}),F=H?PN(BigInt(P),H):P;return mN({decimal:L,identifier:u,value:F})}function PN(A,T){return typeof A==="bigint"?o({bigIntDecimal:T,decimal:T,value:A}):A}function hT(A){let T=wN.match(A).when((H)=>("chain"in H)&&H.chain!==void 0,({chain:H})=>H).otherwise((H)=>{let P=p(H.asset);return P.synth?G.Chain.THORChain:P.chain});if(!G.AllChains.includes(T.toUpperCase()))throw new g({errorKey:"helpers_invalid_asset_identifier",info:{message:"Please use the AssetValue constructor for unsupported chains"}})}function cT(A){if(hT(A),"chain"in A){let{chain:L,address:u}=A;if(u){let F=y.includes(L)?`${L}:${u}`:`${L}:${u.toUpperCase()}`,n=EN.get(F);if(n)return n;return F}return L}let{chain:T,symbol:H}=p(A.asset);return QN({chain:T,symbol:H})==="Native"?T:A.asset}function rT(A,T,H){let P=A.split("."),L=P[0]?.toUpperCase(),u=kN.includes(L),F=H?"~":"/",[n,B=""]=u?P.slice(1).join(".").split(F):A.split(F);if(!(n&&B))throw new g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:A}});let{ticker:D,address:X}=jA({chain:n,symbol:B}),t=`${n}${F}${B}`;return{address:X,chain:L,isGasAsset:!1,isSynthetic:T,isTradeAsset:H,symbol:t,ticker:D}}function lT(A){let T=A.indexOf("."),H=(T===-1?A:A.slice(0,T)).toUpperCase(),P=T===-1?A:A.slice(T+1),{address:L,ticker:u}=jA({chain:H,symbol:P}),F;try{F=L&&G.EVMChains.includes(H)&&qN.getAddress(L)?qN.getAddress(L):L}catch{F=L}let n=F?`${u}-${F}`:P;return{address:F,chain:H,isGasAsset:FN({chain:H,symbol:P}),isSynthetic:!1,isTradeAsset:!1,symbol:n,ticker:u}}function JA(A){let T=A.slice(0,14),H=T.includes("/"),P=T.includes("~");if(H||P)return rT(A,H,P);return lT(A)}function jA({symbol:A,chain:T}){let{ticker:H,address:P}=NN(A,T);return{address:P&&!y.includes(T)?P.toLowerCase():P,ticker:H}}var sT={};b(sT,{SwapKitNumber:()=>BN});class BN extends K{eq(A){return this.eqValue(A)}static fromBigInt(A,T){return new BN({decimal:T,value:o({bigIntDecimal:T,decimal:T,value:A})})}}function vA(A=!0){return A?"https://midgard.ninerealms.com":"https://midgard.mayachain.info"}function eT(A=!0){let T=vA(A);return A?`${T}/v2/thorname`:`${T}/v2/mayaname`}function aT(A){return function(H){let P=H?`?status=${H}`:"";return O.get(`${A}/v2/pools${P}`)}}function NH(A){return function(H){return O.get(`${A}/v2/pool/${H}`)}}function AH(A){return function(H,P){let L=P?`?period=${P}`:"";return O.get(`${A}/v2/pool/${H}/stats${L}`)}}function TH(A){return function(H,P){let L=new URLSearchParams;if(P?.interval)L.append("interval",P.interval);if(P?.count)L.append("count",P.count.toString());if(P?.from)L.append("from",P.from.toString());if(P?.to)L.append("to",P.to.toString());let u=L.toString()?`?${L.toString()}`:"";return O.get(`${A}/v2/history/depths/${H}${u}`)}}function HH(A){return function(){return O.get(`${A}/v2/network`)}}function PH(A){return function(){return O.get(`${A}/v2/health`)}}function LH(A){return function(){return O.get(`${A}/v2/nodes`)}}function RH(A){return function(H){return O.get(`${A}/v2/node/${H}`)}}function uH(A){return function(){return O.get(`${A}/v2/mimir/votes`)}}function FH(A){return function(){return O.get(`${A}/v2/mimir`)}}function IH(A){return function(){return O.get(`${A}/v2/constants`)}}function nH(A){return function(){return O.get(`${A}/v2/stats`)}}function OH(A){return function(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 L=P.toString()?`?${P.toString()}`:"";return O.get(`${A}/v2/history/earnings${L}`)}}function BH(A){return function(H,P){let L=new URLSearchParams;if(P?.interval)L.append("interval",P.interval);if(P?.count)L.append("count",P.count.toString());if(P?.from)L.append("from",P.from.toString());if(P?.to)L.append("to",P.to.toString());let u=L.toString()?`?${L.toString()}`:"",F=H?`/swaps/${H}`:"/swaps";return O.get(`${A}/v2/history${F}${u}`)}}function $H(A){return function(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 L=P.toString()?`?${P.toString()}`:"";return O.get(`${A}/v2/history/tvl${L}`)}}function gH(A){if(!A)return"";let T=new URLSearchParams,H=(P,L)=>{if(L!==void 0)T.append(P,typeof L==="number"?L.toString():L)};return H("address",A.address),H("txid",A.txid),H("asset",A.asset),H("type",A.type),H("affiliate",A.affiliate),H("limit",A.limit),H("offset",A.offset),T.toString()?`?${T.toString()}`:""}function GH(A){return function(H){let P=gH(H);return O.get(`${A}/v2/actions${P}`)}}function tH(A){return function(H){return O.get(`${A}/v2/member/${H}`)}}function _H(A){return function(H){let P=H?`/${H}`:"";return O.get(`${A}/v2/members${P}`)}}function DH(A){return function(H,P){let L=P?`&asset=${P}`:"";return O.get(`${A}/v2/saver/${H}${L?`?${L.substring(1)}`:""}`)}}function YH(A){return function(H){return O.get(`${A}/v2/savers/${H}`)}}function UH(A){return function(H,P){let L=new URLSearchParams;if(P?.interval)L.append("interval",P.interval);if(P?.count)L.append("count",P.count.toString());if(P?.from)L.append("from",P.from.toString());if(P?.to)L.append("to",P.to.toString());let u=L.toString()?`?${L.toString()}`:"",F=H?`/savers/${H}`:"/savers";return O.get(`${A}/v2/history${F}${u}`)}}function MH(A){return function(H){return O.get(`${A}/v2/balance/${H}`)}}function SH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return;throw L};return await O.get(`${A}/lookup/${H}`,{onError:P,retry:{maxRetries:1}})}}function XH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return[];throw L};return await O.get(`${A}/rlookup/${H}`,{onError:P,retry:{maxRetries:1}})}}function QH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return[];throw L};return await O.get(`${A}/owner/${H}`,{onError:P,retry:{maxRetries:1}})}}function LN({asset:A,value:T}){return J.from({asset:A,fromBaseDecimal:r.getChainConfig(r.Chain.THORChain).baseDecimal,value:T})}function xH({liquidityPositionGetter:A,isThorchain:T}){return async function(P){let L=await A(P),u=T?"rune":"cacao";return L.pools.map((F)=>({[`${u}Pending`]:LN({asset:"THOR.RUNE",value:F.runePending}),[`${u}RegisteredAddress`]:F.runeAddress,[`${u}Withdrawn`]:LN({asset:"THOR.RUNE",value:F.runeWithdrawn}),[u]:LN({asset:"THOR.RUNE",value:F.runeAdded}),asset:LN({asset:F.pool,value:F.assetAdded}),assetPending:LN({asset:F.pool,value:F.assetPending}),assetRegisteredAddress:F.assetAddress,assetWithdrawn:LN({asset:F.pool,value:F.assetWithdrawn}),dateFirstAdded:F.dateFirstAdded,dateLastAdded:F.dateLastAdded,poolShare:new BN(F.liquidityUnits).div(F.pool)}))}}function VA(A){let T=A===r.Chain.THORChain,H=vA(T),P=eT(T),L=tH(H);return{getActions:GH(H),getBalance:MH(H),getConstants:IH(H),getEarningsHistory:OH(H),getHealth:PH(H),getLiquidityPosition:xH({isThorchain:T,liquidityPositionGetter:L}),getLiquidityPositionRaw:L,getMembers:_H(H),getMimir:FH(H),getMimirVotes:uH(H),getNameDetails:SH(P),getNamesByAddress:XH(P),getNamesByOwner:QH(P),getNetworkInfo:HH(H),getNode:RH(H),getNodes:LH(H),getPool:NH(H),getPoolDepthHistory:TH(H),getPoolStats:AH(H),getPools:aT(H),getSaverDetails:DH(H),getSavers:YH(H),getSaversHistory:UH(H),getStats:nH(H),getSwapHistory:BH(H),getTVLHistory:$H(H)}}var WA=VA(r.Chain.THORChain),qA=VA(r.Chain.Maya);var nA={};b(nA,{getTrackerDetails:()=>RP,getTokenListProviders:()=>OP,getTokenList:()=>BP,getTokenApproval:()=>nP,getSwapTo:()=>UP,getSwapQuote:()=>uP,getRouteWithTx:()=>FP,getPrice:()=>$P,getNearDepositChannel:()=>tP,getGasRate:()=>gP,getChainflipDepositChannel:()=>GP,getChainBalance:()=>IP,SKRequestClient:()=>j});var iA=require("@swapkit/types"),f=require("ts-pattern");var EH={};b(EH,{signWidgetRequest:()=>KN});async function KN(A,T,H){let P=`${T}:${H}`,L=new TextEncoder,u=await crypto.subtle.importKey("raw",L.encode(A),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),F=await crypto.subtle.sign("HMAC",u,L.encode(P));return Array.from(new Uint8Array(F)).map((n)=>n.toString(16).padStart(2,"0")).join("")}var m=require("@swapkit/types"),N=require("zod/v4");var oN;((P)=>{P.CHEAPEST="CHEAPEST";P.FASTEST="FASTEST";P.RECOMMENDED="RECOMMENDED"})(oN||={});var $N;((L)=>{L.PSBT="PSBT";L.EVM="EVM";L.COSMOS="COSMOS";L.RADIX="RADIX"})($N||={});var yN;((x)=>{x.approve="approve";x.claim="claim";x.deposit="deposit";x.donate="donate";x.lending="lending";x.lp_action="lp_action";x.native_contract_call="native_contract_call";x.native_send="native_send";x.stake="stake";x.streaming_swap="streaming_swap";x.swap="swap";x.thorname_action="thorname_action";x.token_contract_call="token_contract_call";x.token_transfer="token_transfer";x.unknown="unknown";x.unstake="unstake"})(yN||={});var fN;((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"})(fN||={});var CN;((n)=>{n.unknown="unknown";n.not_started="not_started";n.pending="pending";n.swapping="swapping";n.completed="completed";n.refunded="refunded";n.failed="failed"})(CN||={});var dN;((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"})(dN||={});var wH=N.object({address:N.optional(N.string()),chain:N.z.enum(m.Chain).optional(),chainId:N.z.enum(m.ChainId),coingeckoId:N.optional(N.string()),decimals:N.coerce.number(),extensions:N.optional(N.z.looseObject({})),identifier:N.string(),logoURI:N.optional(N.string()),name:N.optional(N.string()),shortCode:N.optional(N.string()),symbol:N.optional(N.string()),ticker:N.string()}),bH=N.z.object({block:N.z.optional(N.z.number().describe("Block number. Required for Polkadot chain. e.g. `123456`")),chainId:N.z.optional(N.z.string().describe("ChainId for the hash. e.g. `thorchain-1`")),depositChannelId:N.z.optional(N.z.string().describe("Deposit channel ID, required for Chainflip if tx was broadcasted without wallet connection")),hash:N.z.optional(N.z.string().describe("Hash for the first transaction broadcasted by the end user. e.g. `88D1819378ECD09E5284C54937CDC1E99B52F253C007617A02DD1200710CE677`"))}).refine((A)=>A.hash&&A.chainId||A.depositChannelId,{message:"Either `hash` and `chainId` or `depositChannelId` must be provided"}),zH=N.z.object({forceUpdate:N.z.string().toLowerCase().transform((A)=>A==="true").pipe(N.z.boolean()).optional()}),JH=N.object({error:N.string(),message:N.string()}),l=N.object({address:N.optional(N.string()),chain:N.z.enum(m.Chain),decimal:N.optional(N.number()),isGasAsset:N.boolean(),isSynthetic:N.boolean(),symbol:N.string(),tax:N.optional(N.object({buy:N.number(),sell:N.number()})),ticker:N.string()}),hN=N.object({id:N.string(),market_cap:N.number(),name:N.string(),price_change_24h_usd:N.number(),price_change_percentage_24h_usd:N.number(),sparkline_in_7d:N.array(N.number()),timestamp:N.string(),total_volume:N.number()}).partial(),ZH=N.object({cg:N.optional(hN),identifier:N.string(),price_usd:N.number(),provider:N.string(),timestamp:N.number()}),cN=N.array(N.object({cg:N.optional(hN),identifier:N.string(),price_usd:N.number(),provider:N.string(),timestamp:N.number()}).partial()),jH=N.object({affiliate:N.optional(N.string().describe("Affiliate thorname")),affiliateFee:N.optional(N.number().describe("Affiliate fee in basis points").refine((A)=>A===Math.floor(A)&&A>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:N.optional(N.boolean().describe("Allow smart contract as recipient")),allowSmartContractSender:N.optional(N.boolean().describe("Allow smart contract as sender")),buyAsset:N.string().describe("Asset to buy"),cfBoost:N.optional(N.boolean().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:N.optional(N.string().describe("Address to send asset to")),disableSecurityChecks:N.optional(N.boolean().describe("Disable security checks")),includeTx:N.optional(N.boolean().describe("Set to true to include an transaction object (EVM only)")),providers:N.optional(N.array(N.string().describe("List of providers to use").refine((A)=>w[A]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:N.optional(N.string().describe("Referrer address (referral program)")),sellAmount:N.string().describe("Amount of asset to sell").refine((A)=>+A>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:N.string().describe("Asset to sell"),slippage:N.optional(N.number().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:N.optional(N.string().describe("Address to send asset from"))}).refine((A)=>A.sellAsset!==A.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),vH=N.object({metadata:N.boolean(),tokens:N.array(N.object({identifier:N.string()}))}),rN=N.object({destinationAddress:N.string()}),KA=rN.extend({affiliateFees:N.array(N.object({brokerAddress:N.string(),feeBps:N.number()})).optional(),brokerCommissionBps:N.number().optional(),buyAsset:N.object({asset:N.string(),chain:N.string()}),channelMetadata:N.object({cfParameters:N.string().optional(),gasBudget:N.string().optional(),message:N.string().optional()}).optional(),dcaParameters:N.object({chunkInterval:N.number().optional(),numberOfChunks:N.number().optional()}).optional(),maxBoostFeeBps:N.number().optional(),refundParameters:N.object({minPrice:N.string().optional(),refundAddress:N.string().optional(),retryDuration:N.number().optional()}).optional(),sellAsset:N.object({asset:N.string(),chain:N.string()})}),lN=N.object({channelId:N.string(),depositAddress:N.string()}),pN=rN.extend({affiliateFees:N.object({feeBps:N.number(),nearId:N.string()}).optional(),buyAsset:N.string(),sellAmount:N.string(),sellAsset:N.string(),slippage:N.coerce.number(),sourceAddress:N.string()}),mA=N.object({amountIn:N.string(),amountInFormatted:N.string(),amountInUsd:N.string(),amountOut:N.string(),amountOutFormatted:N.string(),amountOutUsd:N.string(),deadline:N.string().optional(),minAmountIn:N.string(),minAmountOut:N.string(),timeEstimate:N.number().optional(),timeWhenInactive:N.string().optional()}),VH=mA.extend({depositAddress:N.string(),quote:mA,signature:N.string(),timestamp:N.string(),tx:N.unknown()}),iN=N.object({buyAsset:N.string(),buyAssetAmount:N.string(),buyAssetAmountMaxSlippage:N.string(),deadline:N.string().optional(),depositAddress:N.string(),depositAmount:N.string(),depositAsset:N.string(),tx:N.unknown()}),WH=N.object({evmCalldata:N.z.optional(N.z.string()),intentHash:N.z.optional(N.z.string()),logs:N.z.optional(N.z.unknown()),manifest:N.z.optional(N.z.unknown()),memo:N.z.optional(N.z.string()),spender:N.z.optional(N.z.string()),thorname:N.z.optional(N.z.string())}),qH=N.object({currentStage:N.string(),inboundConfirmation:N.number(),inboundObservation:N.number(),outboundDelay:N.number(),outboundObservation:N.number(),streamingSwap:N.number()}),mH=N.object({count:N.optional(N.number()),interval:N.optional(N.number()),quantity:N.optional(N.number()),subSwapsMap:N.optional(N.array(N.number()))}),kH=N.z.object({currentLegIndex:N.z.optional(N.z.number()),estimatedTimeToComplete:N.z.number(),estimates:N.z.optional(qH),providerDetails:N.z.optional(N.z.object({streamingDetails:N.z.optional(mH)}))}),KH=N.object({affiliate:N.optional(l),liquidity:N.optional(l),network:N.optional(l),protocol:N.optional(l),tax:N.optional(l)}),pH=N.object({affiliate:N.string(),bps:N.string(),isReferrer:N.boolean()}),oH=N.object({affiliate:N.optional(N.string()),affiliateFees:N.optional(N.array(pH)),broadcastedAt:N.optional(N.number()),explorerUrl:N.optional(N.string()),fees:N.optional(KH),images:N.optional(N.object({chain:N.optional(N.string()),from:N.optional(N.string()),provider:N.optional(N.string()),to:N.optional(N.string())})),provider:N.optional(N.z.enum(w)),providerAction:N.z.optional(N.z.enum(fN)),quoteId:N.optional(N.string()),wallet:N.optional(N.string())}),RN=N.z.object({block:N.z.number(),chainId:N.z.enum(m.ChainId),finalAddress:N.z.optional(N.z.string()),finalAsset:N.z.optional(l),finalisedAt:N.z.number(),fromAddress:N.z.string(),fromAmount:N.z.string(),fromAsset:N.z.string(),hash:N.z.string(),meta:N.z.optional(oH),payload:N.z.optional(WH),status:N.z.enum(CN),toAddress:N.z.string(),toAmount:N.z.string(),toAsset:N.z.string(),trackingStatus:N.z.optional(N.z.enum(dN)),transient:N.z.optional(kH),type:N.z.enum(yN)}),sN=RN.extend({legs:N.z.array(RN)}),yH=RN.extend({legs:N.array(RN)}),fH=RN.extend({legs:N.array(RN)}),bN=N.array(N.object({amount:N.string(),asset:N.string(),chain:N.string(),protocol:N.z.enum(w),type:N.z.enum(YN)})),zN=N.z.object({inbound:N.z.optional(N.z.number().describe("Time to receive inbound asset in seconds")),outbound:N.z.optional(N.z.number().describe("Time to receive outbound asset in seconds")),swap:N.z.optional(N.z.number().describe("Time to swap assets in seconds")),total:N.z.number().describe("Total time in seconds")}),eN=N.object({data:N.string().describe("Data to send"),from:N.string().describe("Address of the sender"),to:N.string().describe("Address of the recipient"),value:N.string().describe("Value to send")}),aN=N.z.object({raw_data:N.z.object({contract:N.z.any(),data:N.z.string().optional(),expiration:N.z.number(),fee_limit:N.z.number().optional(),ref_block_bytes:N.z.string(),ref_block_hash:N.z.string(),timestamp:N.z.number()}).passthrough(),raw_data_hex:N.z.string(),txID:N.z.string(),visible:N.z.boolean()}),pA=N.array(N.union([N.string(),N.number(),N.array(N.string()),N.object({from:N.string(),value:N.string()}).describe("Parameters to pass to the contract method")])),CH=N.object({approvalSpender:N.optional(N.string().describe("Address of the spender to approve")),approvalToken:N.optional(N.string().describe("Address of the token to approve spending of")),contractAddress:N.string().describe("Address of the contract to interact with"),contractMethod:N.string().describe("Name of the method to call"),contractParamNames:N.array(N.string().describe("Names of the parameters to pass to the contract method")),contractParams:pA}),dH=N.object({typeUrl:N.string("/types.MsgDeposit"),value:N.object({coins:N.array(N.object({amount:N.string(),asset:N.object({chain:N.string(),symbol:N.string(),synth:N.boolean(),ticker:N.string()})})),memo:N.string(),signer:N.string()})}),hH=N.object({typeUrl:N.string("/types.MsgSend"),value:N.object({amount:N.array(N.object({amount:N.string(),denom:N.string()})),fromAddress:N.string(),toAddress:N.string()})}),cH=N.object({typeUrl:N.string(),value:hH.or(dH)}),rH=N.object({amount:N.array(N.object({amount:N.string(),denom:N.string()})),gas:N.string()}),NA=N.object({accountNumber:N.number(),chainId:N.z.enum(m.ChainId),fee:rH,memo:N.string(),msgs:N.array(cH),sequence:N.number()}),oA=N.z.array(N.z.object({calldata:N.z.array(N.z.string()),contractAddress:N.z.string(),entrypoint:N.z.string()})),AA=N.z.array(N.z.object({address:N.z.string().describe("Destination address in friendly format"),amount:N.z.string().describe("Amount in nanotons"),payload:N.z.string().optional().describe("Base64 BOC of body cell"),stateInit:N.z.string().optional().describe("Base64 BOC of state init")})),yA=N.object({affiliate:N.string().describe("Affiliate address").optional(),affiliateFee:N.number().describe("Affiliate fee").optional(),buyAsset:N.string().describe("Asset to buy"),destinationAddress:N.string().describe("Destination address"),estimatedTime:zN.optional(),provider:N.z.enum(w),sellAsset:N.string().describe("Asset to sell"),slipPercentage:N.number().describe("Slippage as a percentage"),sourceAddress:N.string().describe("Source address")}),lH=yA.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),fA=N.object({asset:N.string().describe("Asset name"),image:N.string().describe("Asset image"),price:N.number().describe("Price in USD")}),CA=KA,TA=N.object({assets:N.optional(N.array(fA)),maxStreamingQuantity:N.number().optional(),referrer:N.string().optional(),streamingInterval:N.number().optional(),tags:N.array(N.z.enum(oN))}),HA=TA.extend({affiliate:N.optional(N.string()),affiliateFee:N.optional(N.string()),approvalAddress:N.optional(N.string().describe("Approval address for swap")),chainflip:CA.optional(),garden:pN.optional(),near:pN.optional(),priceImpact:N.optional(N.number().describe("Price impact")),referrer:N.optional(N.string()),txType:N.optional(N.z.enum($N))}),PA=N.array(N.object({code:N.z.enum(DN),display:N.string(),tooltip:N.string().optional()})),iH=N.object({buyAmount:N.string().describe("Buy amount"),buyAmountMaxSlippage:N.string().describe("Buy amount max slippage"),buyAsset:N.string().describe("Asset to buy"),fees:N.optional(bN),provider:N.z.enum(w),sellAmount:N.string().describe("Sell amount"),sellAsset:N.string().describe("Asset to sell")}),dA=N.object({buyAsset:N.string().describe("Asset to buy"),destinationAddress:N.optional(N.string().describe("Destination address")),estimatedTime:N.optional(zN),expectedBuyAmount:N.string().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:N.string().describe("Expected Buy amount max slippage"),expiration:N.optional(N.string().describe("Expiration")),fees:bN,inboundAddress:N.optional(N.string().describe("Inbound address")),legs:N.array(iH),memo:N.optional(N.string().describe("Memo")),meta:HA,providers:N.array(N.z.enum(w)),routeId:N.string().describe("Route ID"),sellAmount:N.string().describe("Sell amount"),sellAsset:N.string().describe("Asset to sell"),sourceAddress:N.optional(N.string().describe("Source address")),targetAddress:N.optional(N.string().describe("Target address")),totalSlippageBps:N.number().describe("Total slippage in bps"),tx:N.optional(N.union([eN,NA,aN,oA,AA,N.string()])),txType:N.optional(N.z.enum($N)),warnings:PA}),LA=N.object({error:N.optional(N.string().describe("Error message")),providerErrors:N.optional(N.array(N.object({errorCode:N.optional(N.z.enum(e)),message:N.optional(N.string()),provider:N.z.enum(w).optional()}))),quoteId:N.string().describe("Quote ID"),routes:N.array(dA)}),RA=N.z.object({chainId:N.z.enum(m.ChainId),createdAt:N.z.date(),id:N.z.number(),unit:N.z.string(),value:N.z.string()}),sH=N.z.array(RA),uA=N.z.union([RA,sH]),gL=N.array(N.object({chain:N.z.enum(m.Chain),decimal:N.number(),identifier:N.string(),symbol:N.string(),ticker:N.string(),value:N.string()})),eH=N.z.union([N.z.object({amount:N.z.string(),spender:N.z.string(),tokenIdentifier:N.z.string(),userWalletAddress:N.z.string()}),N.z.object({amount:N.z.string(),chainId:N.z.enum(m.ChainId),spender:N.z.string(),tokenContractAddress:N.z.string(),userWalletAddress:N.z.string()}),N.z.object({routeId:N.z.string()})]),aH=N.z.object({approvalTransaction:N.z.optional(N.z.object({data:N.z.string(),from:N.z.string(),gasLimit:N.z.optional(N.z.string()),gasPrice:N.z.optional(N.z.string()),to:N.z.string(),value:N.z.string()})),approvedAmount:N.z.string(),isApproved:N.z.boolean()}),hA=N.z.object({data:N.z.string().describe("Encoded approval call data"),from:N.z.string().describe("User wallet address"),gasLimit:N.z.string().optional().describe("Estimated gas limit"),gasPrice:N.z.string().optional().describe("Current gas price"),to:N.z.string().describe("Token contract address"),value:N.z.string().describe("ETH value (always '0' for approvals)")}),kA=N.z.object({buyAmount:N.z.string().describe("Buy amount"),buyAmountMaxSlippage:N.z.string().describe("Buy amount max slippage"),buyAsset:N.z.string().describe("Asset to buy"),expectedBuyAmount:N.z.string().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:N.z.string().describe("Expected Buy amount max slippage"),fees:bN,provider:N.z.enum(w),sellAmount:N.z.string().describe("Sell amount"),sellAsset:N.z.string().describe("Asset to sell")}),cA=kA.extend({estimatedTime:N.z.optional(zN),expiration:N.z.optional(N.z.string().describe("Expiration")),legs:N.z.array(kA),providers:N.z.array(N.z.enum(w)),routeId:N.z.string().describe("Route ID"),totalSlippageBps:N.z.number().describe("Total slippage in bps"),warnings:PA}).omit({provider:!0}),NP=N.z.object({method:N.z.string(),payload:N.z.optional(N.z.unknown()),url:N.z.string()}),AP=cA.extend({meta:TA,nextActions:N.z.optional(N.z.array(NP))}),TP=N.z.object({error:N.z.optional(N.z.string().describe("Error message")),providerErrors:N.z.optional(N.z.array(N.z.object({errorCode:N.z.optional(N.z.enum(e)),message:N.z.optional(N.z.string()),provider:N.z.enum(w).optional()}))),quoteId:N.z.string().describe("Quote ID"),routes:N.z.array(AP)}),HP=N.z.object({providers:N.z.array(N.z.enum(w)).optional().describe("Optional list of providers to query for trading pairs"),sellAsset:N.z.string().describe("Asset identifier to sell (e.g., 'BTC.BTC' or 'ETH.ETH')")}),rA=N.z.object({chain:N.z.enum(m.Chain).describe("Chain the asset is on"),identifier:N.z.string().describe("Asset identifier (e.g., 'ETH.USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')"),providers:N.z.array(N.z.enum(w)).describe("Providers that support this trading pair"),symbol:N.z.string().describe("Asset symbol"),ticker:N.z.string().describe("Asset ticker")}),PP=N.z.object({buyAssets:N.z.array(rA).describe("List of assets that can be swapped to"),sellAsset:N.z.string().describe("The input sell asset identifier")}),FA=cA.extend({destinationAddress:N.z.string().describe("Destination address"),inboundAddress:N.z.optional(N.z.string().describe("Inbound address")),memo:N.z.optional(N.z.string().describe("Memo to include in the transaction")),meta:HA,sourceAddress:N.z.string().describe("Source address"),targetAddress:N.z.optional(N.z.string().describe("Target address")),tx:N.optional(N.union([eN,NA,aN,AA,N.string()])),txType:N.z.optional(N.z.enum($N))}),lA=N.z.object({data:N.z.optional(N.z.record(N.z.string(),N.z.string().optional())),errorCode:N.z.enum(e),message:N.z.string().optional(),provider:N.z.enum(w).optional()}),LP=N.z.object({error:N.z.optional(N.z.string().describe("Error message")),providerErrors:N.z.optional(N.z.array(lA)),quoteId:N.z.string().describe("Quote ID"),routes:N.z.array(FA)}),IA=FA.extend({approvalTx:hA.optional().describe("Optional approval transaction if ERC-20 approval is required before swap"),swapId:N.z.string().describe("The unique swap ID for tracking")});var j=O.extend({dynamicHeader:async()=>{let A=S.get("widgetKey");if(A&&typeof window<"u"){let H=Math.floor(Date.now()/1000),P=window.location.origin;return{"X-Signature":await KN(A,P,H),"X-Timestamp":H.toString()}}let{swapKit:T}=S.get("apiKeys");return T?{"x-api-key":T}:{}}});async function RP(A){let T=await j.post(Z("/track"),{json:A});try{let H=sN.safeParse(T);if(!H.success)throw new g("api_v2_invalid_response",H.error);return H.data}catch(H){return T}}async function uP(A){let{getQuote:T}=S.get("endpoints");if(T)return T(A);let P=S.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",L=await j.post(Z(P),{json:A});if(L.error)throw new g("api_v2_server_error",{message:L.error});try{let u=LA.safeParse(L);if(!u.success)throw new g("api_v2_invalid_response",u.error);return u.data}catch{return L}}async function FP(A){let{getRouteWithTx:T}=S.get("endpoints");if(T)return T(A);let P=S.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",L=await j.post(Z(P),{json:A});try{let u=IA.safeParse(L);if(!u.success)throw new g("api_v2_invalid_response",u.error);return u.data}catch(u){return console.error(new g("api_v2_invalid_response",u)),L}}async function IP({chain:A,address:T,scamFilter:H=!0}){let{getBalance:P}=S.get("endpoints");if(P)return P({address:T,chain:A});let L=Z(`/balance?chain=${A}&address=${T}`),u=await j.get(L),F=Array.isArray(u)?u:[];return H?YP(F):F}function nP(A){let T=f.match(A).with({routeId:f.P.string,spender:f.P.string},({routeId:H,spender:P})=>Z(`/approve?routeId=${H}&sourceAddress=${P}`)).with({assetValue:f.P.instanceOf(J),spender:f.P.string,userWallet:f.P.string},({spender:H,userWallet:P,assetValue:L})=>Z(`/approve?tokenIdentifier=${L.toString()}&userWalletAddress=${P}&spender=${H}&amount=${L.getValue("string")}`)).exhaustive();return j.get(T)}function OP(){let A=Z("/providers");return j.get(A)}function BP(A){let T=Z(`/tokens?provider=${A}`);return j.get(T)}async function $P(A){let T=Z("/price"),H=await j.post(T,{json:A});try{let P=cN.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 gP(){let A=Z("/gas"),T=await j.get(A);try{let H=uA.safeParse(T);if(!H.success)throw new g("api_v2_invalid_response",H.error);return Array.isArray(H)?H:[H]}catch(H){throw new g("api_v2_invalid_response",H)}}async function GP(A){let{destinationAddress:T}=A;if(!T)throw new g("chainflip_broker_invalid_params");let H=S.get("integrations").chainflip?.brokerUrl||Z("/chainflip/broker/channel"),P=await j.post(H,{json:A});try{let L=lN.safeParse(P);if(!L.success)throw new g("api_v2_invalid_response",L.error);return L.data}catch(L){throw new g("api_v2_invalid_response",L)}}async function tP(A){let{destinationAddress:T}=A;if(!T)throw new g("chainflip_broker_invalid_params");let H=Z("/near/channel"),P=await j.post(H,{json:A});try{let L=iN.safeParse(P);if(!L.success)throw new g("api_v2_invalid_response",L.error);return L.data}catch(L){throw new g("api_v2_invalid_response",L)}}function Z(A){let{isDev:T,apiUrl:H,devApiUrl:P}=S.get("envs");return`${T?P:H}${A}`}function _P(A){let[T,H]=A.split(".");if(!iA.EVMChains.includes(T))return!0;let P=H.split("-"),L=P.length===1?void 0:P[P.length-1];return FN({chain:T,symbol:H})||!!L}var DP=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi");function YP(A){return A.filter((T)=>{return!DP.test(T.identifier)&&_P(T.identifier)})}async function UP(A){let{getSwapTo:T}=S.get("endpoints");if(T)return T(A);let H=new URLSearchParams({sellAsset:A.sellAsset});if(A.providers?.length)for(let F of A.providers)H.append("providers",F);let P=Z(`/swapTo?${H.toString()}`),L=await j.get(P);if(!Array.isArray(L))return{buyAssets:[],sellAsset:A.sellAsset};let u=[];for(let F of L)try{let n=J.from({asset:F});u.push({chain:n.chain,identifier:n.toString(),providers:[],symbol:n.symbol,ticker:n.ticker})}catch{}return{buyAssets:u,sellAsset:A.sellAsset}}var OA={};b(OA,{getThorchainQueue:()=>XP,getTcyStakers:()=>ZP,getTcyStaker:()=>JP,getTcyClaimers:()=>vP,getTcyClaimer:()=>jP,getTNSPreferredAsset:()=>wP,getTHORNodeTNSDetails:()=>sA,getRunePoolProviderInfo:()=>zP,getRunePoolInfo:()=>bP,getNodes:()=>QP,getMimirInfo:()=>xP,getLastBlock:()=>SP,getInboundAddresses:()=>EP});var C=require("@swapkit/types");function W(A){let{isStagenet:T}=S.get("envs");switch(A){case"mayachain":return`${T?C.StagenetMAYAConfig.nodeUrl:C.MAYAConfig.nodeUrl}/mayachain`;default:return`${T?C.StagenetTHORConfig.nodeUrl:C.THORConfig.nodeUrl}/thorchain`}}function MP(A){let T=A==="mayachain"?"mayaname":"thorname";return`${W(A)}/${T}`}function SP(A="thorchain"){return O.get(`${W(A)}/lastblock`)}function XP(A){return O.get(`${W(A)}/queue`)}function QP(A){return O.get(`${W(A)}/nodes`)}function xP(A){return O.get(`${W(A)}/mimir`)}function EP(A){return O.get(`${W(A)}/inbound_addresses`)}async function sA({type:A,name:T}){try{return await O.get(`${MP(A)}/${T}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:T,owner:"",preferred_asset:""}}}async function wP({type:A,tns:T}){let H=await sA({name:T,type:A});if(!H.preferred_asset||H.preferred_asset===".")return;return J.from({asset:H.preferred_asset,asyncTokenLookup:!0})}function bP(A){return O.get(`${W(A)}/runepool`)}function zP({type:A,thorAddress:T}){return O.get(`${W(A)}/rune_provider/${T}`)}function JP({type:A,address:T}){return O.get(`${W(A)}/tcy_staker/${T}`)}function ZP(A){return O.get(`${W(A)}/tcy_stakers`)}function jP({type:A,address:T}){return O.get(`${W(A)}/tcy_claimer/${T}`)}function vP(A){return O.get(`${W(A)}/tcy_claimers`)}var WP={...nA,mayachainMidgard:qA,thorchainMidgard:WA,thornode:OA};