@swapkit/helpers 4.13.5 → 4.13.7

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 n,Aa as O,Ba as P,Ca as Q,Da as R,Ea as S,Fa as T,Ga as U,Ha as V,Ia as W,Ja as X,Ka as Y,La as Z,Ma as _,Na as $,O as a,Oa as aa,P as b,Pa as ba,Q as c,Qa as ca,R as d,S as e,T as f,U as g,V as h,W as i,X as j,Y as k,Z as l,_ as m,aa as o,ba as p,ca as q,da as r,ea as s,fa as t,ga as u,ha as v,ia as w,ja as x,ka as y,la as z,ma as A,na as B,oa as C,pa as D,qa as E,ra as F,sa as G,ta as H,ua as I,va as J,wa as K,xa as L,ya as M,za as N}from"../chunk-x05xsas4.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 n,Aa as O,Ba as P,Ca as Q,Da as R,Ea as S,Fa as T,Ga as U,Ha as V,Ia as W,Ja as X,Ka as Y,La as Z,Ma as _,Na as $,O as a,Oa as aa,P as b,Pa as ba,Q as c,Qa as ca,R as d,S as e,T as f,U as g,V as h,W as i,X as j,Y as k,Z as l,_ as m,aa as o,ba as p,ca as q,da as r,ea as s,fa as t,ga as u,ha as v,ia as w,ja as x,ka as y,la as z,ma as A,na as B,oa as C,pa as D,qa as E,ra as F,sa as G,ta as H,ua as I,va as J,wa as K,xa as L,ya as M,za as N}from"../chunk-48as5x5v.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,5 +1,5 @@
1
1
  var rA=Object.defineProperty;var iA=(N)=>N;function sA(N,A){this[N]=iA.bind(null,A)}var dN=(N,A)=>{for(var T in A)rA(N,T,{get:A[T],enumerable:!0,configurable:!0,set:sA.bind(A,T)})};var PN=((N)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(N,{get:(A,T)=>(typeof require<"u"?require:A)[T]}):N)(function(N){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+N+'" is not supported')});import{Chain as XN,getChainConfig as lT}from"@swapkit/types";import{AllChains as kT,Chain as Q,EVMChains as KT,getChainConfig as IN}from"@swapkit/types";import{getAddress as IA}from"ethers";import{match as qN}from"ts-pattern";import{Chain as n,EVMChains as QT,getChainConfig as o,UTXOChains as xT}from"@swapkit/types";import{match as RN}from"ts-pattern";import{AllChains as lN,Chain as cN,getChainConfig as PT,MAYAConfig as LT,StagenetChain as MN,StagenetMAYAConfig as rN,StagenetTHORConfig as iN,THORConfig as RT}from"@swapkit/types";import{createStore as uT}from"zustand/vanilla";import{AllChains as eA,getChainConfig as aA}from"@swapkit/types";var wP=eA.reduce((N,A)=>{return N[A]=aA(A).networkDerivationPath,N},{});var LN;((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"})(LN||={});var wN;((T)=>{T.highSlippage="highSlippage";T.highPriceImpact="highPriceImpact"})(wN||={});var J;((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"})(J||={});var bN;((M)=>{M.LIQUIDITY="liquidity";M.NETWORK="network";M.INBOUND="inbound";M.OUTBOUND="outbound";M.AFFILIATE="affiliate";M.TAX="tax";M.PRIORITY="priority";M.SERVICE="service"})(bN||={});var NT;((H)=>{H.Average="average";H.Fast="fast";H.Fastest="fastest"})(NT||={});var AT;((T)=>{T.Approve="approve";T.CheckOnly="checkOnly"})(AT||={});var TT;((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-"})(TT||={});var zN;((D)=>{D.BITGET="BITGET";D.BRAVE="BRAVE";D.COINBASE_MOBILE="COINBASE_MOBILE";D.COINBASE_WEB="COINBASE_WEB";D.COSMOSTATION="COSMOSTATION";D.CTRL="CTRL";D.EIP6963="EIP6963";D.EXODUS="EXODUS";D.KEEPKEY="KEEPKEY";D.KEEPKEY_BEX="KEEPKEY_BEX";D.KEPLR="KEPLR";D.KEYSTORE="KEYSTORE";D.LEAP="LEAP";D.LEDGER="LEDGER";D.METAMASK="METAMASK";D.OKX="OKX";D.OKX_MOBILE="OKX_MOBILE";D.ONEKEY="ONEKEY";D.PASSKEYS="PASSKEYS";D.PETRA="PETRA";D.PHANTOM="PHANTOM";D.POLKADOT_JS="POLKADOT_JS";D.RADIX_WALLET="RADIX_WALLET";D.TALISMAN="TALISMAN";D.TREZOR="TREZOR";D.TRONLINK="TRONLINK";D.TRUSTWALLET_WEB="TRUSTWALLET_WEB";D.VULTISIG="VULTISIG";D.WALLETCONNECT="WALLETCONNECT";D.WALLET_SELECTOR="WALLET_SELECTOR";D.XAMAN="XAMAN"})(zN||={});var HT;((H)=>{H[H.NoError=36864]="NoError";H[H.LockedDevice=21781]="LockedDevice";H[H.TC_NotFound=65535]="TC_NotFound"})(HT||={});var FT=lN.reduce((N,A)=>{if(!N.THOR_STAGENET)N[MN.Maya]=rN.rpcUrls,N[MN.THORChain]=iN.rpcUrls;return N[A]=PT(A).rpcUrls,N},{}),IT={[cN.THORChain]:RT.nodeUrl,[cN.Maya]:LT.nodeUrl,[MN.THORChain]:iN.nodeUrl,[MN.Maya]:rN.nodeUrl},sN={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:lN,endpoints:{},envs:{apiUrl:"https://api.swapkit.dev",devApiUrl:"https://dev-api.swapkit.dev",isDev:!1,isStagenet:!1},feeMultipliers:void 0,integrations:{radix:{applicationName:"Swapkit Playground",applicationVersion:"0.0.1",dAppDefinitionAddress:"account_rdx128r289p58222hcvev7frs6kue76pl7pdcnw8725aw658v0zggkh9ws",network:{dashboardBase:"https://dashboard.radixdlt.com",networkId:1,networkName:"mainnet"}}},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:FT,thornodeUrls:IT,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(zN),widgetId:"",widgetKey:""},Z=uT((N)=>({...sN,setApiKey:(A,T)=>N((H)=>({apiKeys:{...H.apiKeys,[A]:T}})),setConfig:(A)=>N((T)=>({apiKeys:{...T.apiKeys,...A?.apiKeys},chains:T.chains.concat(A?.chains||[]),endpoints:{...T.endpoints,...A?.endpoints},envs:{...T.envs,...A?.envs},feeMultipliers:A?.feeMultipliers||T.feeMultipliers,integrations:{...T.integrations,...A?.integrations},rpcUrls:{...T.rpcUrls,...A?.rpcUrls},thornodeUrls:{...T.thornodeUrls,...A?.thornodeUrls},v3SwapFlow:{...T.v3SwapFlow,...A?.v3SwapFlow},wallets:T.wallets.concat(A?.wallets||[]),widgetId:A?.widgetId||T.widgetId,widgetKey:A?.widgetKey||T.widgetKey})),setEndpoint:(A,T)=>N((H)=>({endpoints:{...H.endpoints,[A]:T}})),setEnv:(A,T)=>N((H)=>({envs:{...H.envs,[A]:T}})),setFeeMultipliers:(A)=>N(()=>({feeMultipliers:A})),setIntegrationConfig:(A,T)=>N((H)=>({integrations:{...H.integrations,[A]:T}})),setRequestOptions:(A)=>N((T)=>({requestOptions:{retry:{...T.requestOptions.retry,...A.retry},timeoutMs:A.timeoutMs||T.requestOptions.timeoutMs}})),setRpcUrl:(A,T)=>N((H)=>({rpcUrls:{...H.rpcUrls,[A]:T}})),setThornodeUrl:(A,T)=>N((H)=>({thornodeUrls:{...H.thornodeUrls,[A]:T}})),setWidgetId:(A)=>N({widgetId:A}),setWidgetKey:(A)=>N({widgetKey:A})})),E={get:(N)=>Z.getState()[N],getState:Z.getState,reinitialize:()=>Z.setState(sN),set:(N)=>Z.getState().setConfig(N),setApiKey:(N,A)=>Z.getState().setApiKey(N,A),setEndpoint:(N,A)=>Z.getState().setEndpoint(N,A),setEnv:(N,A)=>Z.getState().setEnv(N,A),setFeeMultipliers:(N)=>Z.getState().setFeeMultipliers(N),setIntegrationConfig:(N,A)=>Z.getState().setIntegrationConfig(N,A),setRequestOptions:(N)=>Z.getState().setRequestOptions(N),setRpcUrl:(N,A)=>Z.getState().setRpcUrl(N,A),setThornodeUrl:(N,A)=>Z.getState().setThornodeUrl(N,A),setWidgetId:(N)=>Z.getState().setWidgetId(N),setWidgetKey:(N)=>Z.getState().setWidgetKey(N)};var nT={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 JN(N){return JSON.stringify(N,(A,T)=>typeof T==="bigint"?T.toString():T)}class g extends Error{static ErrorCode=nT;errorKey;info;constructor(N,A){let T=typeof N==="string",H=T?N:N.errorKey,P=T?void 0:N.info,F=`${H}${P?`: ${JN(P)}`:""}`;super(F);if(Object.setPrototypeOf(this,g.prototype),this.name="SwapKitError",this.errorKey=H,this.info=P,this.cause=A,A){let I=A instanceof Error?`${A.message}${A.cause?` (${A.cause})`:""}`:JN(A);console.error(`SwapKitError [${H}]: ${I}`)}else if(P)console.error(`SwapKitError [${H}]: ${JN(P)}`)}}var BT=(N)=>new Promise((A)=>setTimeout(A,N)),OT=(N,{baseDelay:A,backoffMultiplier:T,maxDelay:H})=>Math.min(A*T**N,H);function $T(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 GT=async(N,A)=>{let T=await fetch(N,A),H;try{H=await T.json()}catch{if(!T.ok)throw new g({errorKey:"helpers_invalid_response",info:{status:T.status,statusText:T.statusText}},{status:T.status,statusText:T.statusText});return{}}if(!T.ok){let F={data:H?.data,error:H?.error,message:H?.message,status:T.status};throw new g({errorKey:H?.error||"helpers_invalid_response",info:F},F)}let P=H?.routes?.length||H?.result||H?.data&&!H?.error;if(H?.error&&!P){let F={data:H.data,error:H.error,message:H.message,status:T.status};throw new g({errorKey:H.error,info:F},F)}if(H?.providerErrors?.length||H?.error&&P)console.warn("[SwapKit] Partial errors in response:",H.providerErrors||H.error);return H};function _N(N,A={}){return async function(H,P={}){let{searchParams:F,json:I,body:O,headers:M,dynamicHeader:Y,retry:x,timeoutMs:t,abortController:j,onError:U,onSuccess:k,responseHandler:w,...b}={...A,...P},TN=E.get("requestOptions"),S={...TN.retry,...x},ON=!!I||H.endsWith(".json"),$N=_T(H,F),fN=Y?await Y():{},HN=MT(ON,{...M,...fN}),d=ON?JSON.stringify(I):O,xN;for(let GN=0;GN<=S.maxRetries;GN++){let CN=j||new AbortController,hN=setTimeout(()=>CN.abort(),t||TN.timeoutMs);try{let m=await GT($N,{...b,body:d,headers:HN,method:N,signal:CN.signal});return clearTimeout(hN),k?.(m)||w?.(m)||m}catch(m){clearTimeout(hN),xN=m;let lA=m?.cause?.status;if(GN>=S.maxRetries||!$T(m,lA))return U?U(m):Promise.reject(m);await BT(OT(GN,S))}}return U?U(xN):Promise.reject(xN)}}function MT(N,A){return{...A,...N&&{"Content-Type":"application/json"}}}function _T(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 DT,UTXOChains as YT}from"@swapkit/types";import{match as NA}from"ts-pattern";import{Chain as ZN}from"@swapkit/types";function lP(N){if(N<0)throw new g({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:N}});return 10+N}function rP(N){if(N<0)throw new g({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:N}});return Math.round((10+N*1.0512)*10000000000)/10000000000}function iP(N,A){try{return N()}catch(T){if(A)throw new g(A,T);return}}function sP(N){switch(N){case ZN.THORChain:return`${N}.RUNE`;case ZN.Cosmos:return`${N}.ATOM`;case ZN.BinanceSmartChain:return`${N}`;default:return`${N}.${N}`}}var eN=new Set;function c({condition:N,id:A,warning:T}){if(N){if(eN.has(A))return;console.warn(T),eN.add(A)}}function UT(N){return NA(N).with(...tT,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...YT,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...gT,...DT,()=>({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 g("helpers_chain_not_supported",{chain:N})})}function ST(N){return NA(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 aN(N,A){try{let T=A.startsWith("wss")?A.replace("wss","https"):A;return(await fetch(`${T}${ST(N)}`,{body:JSON.stringify(UT(N)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var VN=new Map,XT=120000;function ET(N){let[A=""]=E.get("rpcUrls")[N];if(!A)throw c({condition:!0,id:"helpers_chain_no_public_or_set_rpc_url",warning:`No public or set RPC URL found for chain. Please ensure you configured rpcUrls for ${N}.`}),new g("helpers_chain_no_public_or_set_rpc_url",{chain:N});let T=VN.get(N);if(T&&Date.now()-T.timestamp<XT)return T.url;return VN.set(N,{timestamp:Date.now(),url:A}),A}async function l(N){let A=ET(N),[,...T]=E.get("rpcUrls")[N];if(await aN(N,A))return A;for(let P of T)if(await aN(N,P))return VN.set(N,{timestamp:Date.now(),url:P}),P;throw new g("helpers_chain_rpc_connection_failed",{chain:N,fallbackUrls:T,primaryRpcUrl:A})}function PL(N){c({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 nL=[`${n.Maya}.MAYA`,`${n.Maya}.CACAO`,`${n.Ethereum}.THOR`,`${n.Ethereum}.vTHOR`,`${n.Kujira}.USK`,`${n.Ethereum}.FLIP`,`${n.Radix}.XRD`],HA=[n.Arbitrum,n.Aurora,n.Base,n.Ethereum,n.Optimism];async function wT(N){let{baseDecimal:A}=o(n.Radix);try{let T=await l(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 bT(N){try{let A=await l(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 PA({chain:N,address:A,methodHex:T,id:H}){let P=await l(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 zT(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 JT(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}=o(N),H=A.toLowerCase();if(A===""||!H.startsWith("0x"))return T;let P=await PA({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 JT(P.result,T)}async function VT({chain:N,address:A}){let T=A.toLowerCase();if(T===""||!T.startsWith("0x"))return;let H=await PA({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 zT(H.result)}async function AA({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 TA(N){let A=N.match(/.{2}/g)?.map((T)=>Number.parseInt(T,16))??[];return new TextDecoder().decode(new Uint8Array(A))}function WT(N){return RN(N).with(void 0,()=>{return}).when((A)=>A.length>=128,(A)=>{let T=Number.parseInt(A.slice(64,128),16);return TA(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 TA(T);return}).otherwise(()=>{return})}function LA({chain:N,address:A}){let{baseDecimal:T}=o(N),H={decimals:T,ticker:void 0};return RN(N).with(...QT,async()=>{try{let{isAddress:P,getAddress:F}=await import("ethers");if(!P(F(A.replace(/^0X/,"0x"))))return H;let[I,O]=await Promise.all([VT({address:A,chain:N}),ZT({address:A,chain:N})]);return{decimals:O,ticker:I}}catch(P){return console.warn(`Failed to fetch token info for ${A} on ${N}: ${P?.code} ${P?.message}`),H}}).with(n.Solana,async()=>{if(!A)return H;try{let P=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${A}`);if(P.ok){let F=await P.json(),I=Array.isArray(F)?F[0]:F;if(I)return{decimals:I.decimals??T,ticker:I.symbol||void 0}}}catch(P){console.warn(`Failed to fetch Solana token info for ${A}: ${P?.code} ${P?.message}`)}return H}).with(n.Tron,async()=>{if(!A)return H;try{let P=await l(n.Tron),[F,I]=await Promise.all([AA({contractAddress:A,functionSelector:"symbol()",rpcUrl:P}),AA({contractAddress:A,functionSelector:"decimals()",rpcUrl:P})]),O=WT(F);return{decimals:F!==void 0&&I?Number(BigInt(`0x${I}`)):T,ticker:O}}catch(P){let F=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Tron token info for ${A}: ${F}`),H}}).with(n.Near,async()=>{if(!A)return H;try{let{JsonRpcProvider:P}=await import("@near-js/providers"),F=await l(n.Near),O=await new P({url:F}).query({account_id:A,args_base64:Buffer.from("{}").toString("base64"),finality:"final",method_name:"ft_metadata",request_type:"call_function"}),M=JSON.parse(Buffer.from(O.result).toString());return{decimals:M?.decimals||T,ticker:M?.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([bT(A),wT(A)]);return{decimals:F,ticker:P}}catch(P){let F=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Radix token info for ${A}: ${F}`),H}}).otherwise(async()=>H)}function gN({chain:N,symbol:A}){return RN(N).with(...HA,()=>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}`===tN(N).identifier).otherwise(()=>A===N)}var tN=(N)=>{let{baseDecimal:A}=o(N);return RN(N.toUpperCase()).with(...HA,(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,...xT,(H)=>({decimal:A,identifier:`${H}.${H}`})).with(n.Radix,"XRD.XRD",()=>({decimal:A,identifier:"XRD.XRD"})).with(n.Polygon,"POL.POL",()=>({decimal:A,identifier:"POL.POL"})).with("KUJI.USK",(H)=>({decimal:6,identifier:H})).with("ETH.FLIP",()=>({decimal:o(n.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:o(n.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:o(n.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(H)=>({decimal:10,identifier:H})).with("MAYA.MAYA",(H)=>({decimal:4,identifier:H})).otherwise(()=>({decimal:A,identifier:N}))};function WN({chain:N,symbol:A}){if(A.includes("/"))return"Synth";if(A.includes("~"))return"Trade";return RN(N).with(n.Radix,()=>A===n.Radix||`${N}.${A}`===tN(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 f=(N)=>{let[A,...T]=N.split("."),H=N.includes("/"),P=T.join("."),F=P?.split("-"),I=F?.length?F.length===1?F[0]:F.slice(0,-1).join("-"):void 0;return{chain:A,symbol:P,synth:H,ticker:I}};function uN(N,A){let H=A===n.Near?N.indexOf("-"):N.lastIndexOf("-");if(H===-1)return{address:void 0,ticker:N};return{address:N.slice(H+1),ticker:N.slice(0,H)}}function BL(N){return`https://storage.googleapis.com/token-list-swapkit-dev/images/${N.toLowerCase()}.png`}async function OL(N){let{loadTokenLists:A}=await import("./tokens.js"),T=await A(),H=Object.values(T).flatMap((F)=>F.tokens);if("identifier"in N)return H.find((F)=>F.identifier===N.identifier)?.identifier;let P=N.contract.toLowerCase();for(let F of H){let{chain:I,symbol:O}=f(F.identifier);if(I!==N.chain)continue;let{address:M}=uN(O,I);if(M?.toLowerCase()===P)return F.identifier}return}var RA=["TERRA",...E.get("chains")];function uA(N=""){let A=N.toUpperCase(),[T]=A.split(".");if(RA.includes(T))return!0;let[H]=A.split("/");if(RA.includes(H))return!0;throw new g({errorKey:"helpers_invalid_identifier",info:{identifier:N,message:`Invalid identifier: ${N}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}function _L(N){if(N.length>30)return!1;let A=/^[a-zA-Z0-9+_-]+$/g;return!!N.match(A)}import{match as DN}from"ts-pattern";var r=8,jT=10;function h({value:N,bigIntDecimal:A=r,decimal:T=r}){if(T===0)return N.toString();let H=N<0n,P=N.toString().substring(H?1:0),F=T-(P.length-1);if(F>0)P="0".repeat(F)+P;let I=P.length-T,O=P.slice(-T);if(Number.parseInt(O[A]||"0",10)>=5){let Y=Number.parseInt(O[A-1]||"0",10);O=`${O.substring(0,A-1)}${Y+1}`}else O=O.substring(0,A);return`${H?"-":""}${P.slice(0,I)}.${O}`.replace(/\.?0*$/,"")}class p{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(N,A){return new p({decimal:A,value:h({bigIntDecimal:A,decimal:A,value:N})})}static shiftDecimals({value:N,from:A,to:T}){return p.fromBigInt(N.getBaseValue("bigint")*C(T)/C(A),T)}constructor(N){let A=jN(N),T=typeof N==="object";this.decimal=T?N.decimal:void 0,this.decimalMultiplier=T&&"decimalMultiplier"in N?N.decimalMultiplier:C(Math.max(FA(YN(A)),this.decimal||0)),this.#P(A)}set(N){return new this.constructor({decimal:this.decimal,identifier:this.toString?.({includeSynthProtocol:!0}),value:N})}add(...N){return this.#A("add",...N)}sub(...N){return this.#A("sub",...N)}mul(...N){return this.#A("mul",...N)}div(...N){return this.#A("div",...N)}gt(N){return this.#N("gt",N)}gte(N){return this.#N("gte",N)}lt(N){return this.#N("lt",N)}lte(N){return this.#N("lte",N)}eqValue(N){return this.#N("eqValue",N)}getValue(N,A){let T=FN(this.decimalMultiplier),H=A!==void 0?A:this.decimal,P=H!==void 0?H:T;if(H!==void 0&&H<T){if(this.formatBigIntToSafeValue(this.bigIntValue,H)==="0"&&this.bigIntValue!==0n)P=T}let F=this.formatBigIntToSafeValue(this.bigIntValue,P);return DN(N).with("number",()=>Number(F)).with("string",()=>F).with("bigint",()=>{return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}).otherwise(()=>F)}getBaseValue(N,A){let T=this.decimalMultiplier/C(A||this.decimal||r),H=qT(this.bigIntValue,T);return DN(N).with("number",()=>Number(H)).with("string",()=>H.toString()).otherwise(()=>H)}getBigIntValue(N,A){if(!A&&typeof N==="object")return N.bigIntValue;let T=jN(N),H=YN(T);if(H==="0"||H==="undefined")return 0n;return this.#H(H,A)}toSignificant(N=6){let A=this.getValue("string"),[T="",H=""]=A.split("."),P=Number.parseInt(T,10)>0;if((P?T.length+H.length:H.length)<=N)return A;if(T.length>=N)return T.slice(0,N).padEnd(T.length,"0");if(P)return`${T}.${H.slice(0,N-T.length)}`;let I=Number.parseInt(H,10).toString(),O=I.slice(0,N),M=H.length-I.length;return`0.${O.padStart(M+O.length,"0")}`}toFixed(N=6){let A=this.getValue("string"),T=A.startsWith("-"),[H="0",P=""]=(T?A.slice(1):A).split("."),F=H==="0"&&Number.parseInt(P.slice(0,N),10)===0,I=T&&!F?"-":"";if(N===0){if(H==="0"&&!P)return"0";return P&&Number.parseInt(P[0]||"0",10)>=5?`${I}${BigInt(H)+1n}.0`:`${I}${H}.0`}if(!P)return`${I}${H}.${"0".repeat(N)}`;let O=P[N];if(!(O&&Number.parseInt(O,10)>=5))return`${I}${H}.${P.slice(0,N).padEnd(N,"0")}`;let Y=BigInt(P.slice(0,N).padEnd(N,"0"))+1n,x=10n**BigInt(N);if(Y>=x)return`${I}${BigInt(H)+1n}.${"0".repeat(N)}`;return`${I}${H}.${Y.toString().padStart(N,"0")}`}toAbbreviation(N=2){let A=this.getValue("string"),T=Number(A),H=["","K","M","B","T","Q","Qi","S"],P=Math.floor(Math.log10(Math.abs(T))/3);if(P===0||!H[P])return A;return`${(T/10**(P*3)).toFixed(N)}${H[P]}`}toCurrency(N="$",{currencyPosition:A="start",decimal:T=2,decimalSeparator:H=".",thousandSeparator:P=",",trimTrailingZeros:F=!0}={}){let I=this.toFixed(T),O=A==="end",[M="0",Y=""]=I.split("."),x=M.replace(/\B(?=(\d{3})+(?!\d))/g,P),t=Y&&Number.parseInt(Y,10)>0,j=t?`${x}${H}${Y}`:x,k=j.length<100&&F&&t?j.replace(/\.?0*$/,""):j;return O?`${k}${N}`:`${N}${k}`}formatBigIntToSafeValue(N,A){let T=A||this.decimal||r,H=Math.max(T,FN(this.decimalMultiplier));return h({bigIntDecimal:T,decimal:H,value:N})}#A(N,...A){let T=this.#T(this,...A),H=FN(this.decimalMultiplier),F=Math.max(T,H)+jT,I=C(F),O=A.reduce((Y,x)=>{let t=this.getBigIntValue(x,F);return DN(N).with("add",()=>Y+t).with("sub",()=>Y-t).with("mul",()=>Y*t/I).with("div",()=>{if(t===0n)throw RangeError("Division by zero");return Y*I/t}).otherwise(()=>Y)},this.bigIntValue*I/this.decimalMultiplier),M=h({bigIntDecimal:F,decimal:F,value:O});return new this.constructor({decimal:this.decimal,decimalMultiplier:C(F),identifier:this.toString(),value:M})}#N(N,...A){let T=this.#T(this,...A),H=this.getBigIntValue(A[0]||"0",T),P=this.getBigIntValue(this,T);return DN(N).with("gt",()=>P>H).with("gte",()=>P>=H).with("lt",()=>P<H).with("lte",()=>P<=H).with("eqValue",()=>P===H).otherwise(()=>!1)}#P(N){let A=YN(N)||"0";this.bigIntValue=this.#H(A)}#T(...N){let A=N.map((T)=>{return typeof T==="object"?T.decimal||FN(T.decimalMultiplier):FA(YN(T))}).filter(Boolean);return Math.max(...A,r)}#H(N,A){let T=A?C(A):this.decimalMultiplier,H=FN(T),[P="",F=""]=N.split(".");return BigInt(`${P}${F.padEnd(H,"0")}`)}}var vT=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function YN(N){let T=`${typeof N==="number"?vT.format(N):jN(N)}`.replaceAll(",",".").split(".");return T.length>1?`${T.slice(0,-1).join("")}.${T.at(-1)}`:T[0]||"0"}function FA(N){let A=N.split(".")[1]?.length||0;return Math.max(A,r)}function jN(N){return typeof N==="object"?"getValue"in N?N.getValue("string"):N.value:N}function qT(N,A){if(A===0n)throw Error("Cannot divide by zero");let T=A/2n;return N>=0n&&A>=0n||N<0n&&A<0n?(N+T)/A:(N-T)/A}function C(N){return 10n**BigInt(N)}function FN(N){return Math.log10(Number.parseFloat(N.toString()))}var y=[Q.HyperCore,Q.Near,Q.Ripple,Q.Solana,Q.Sui,Q.Ton,Q.Tron],kN=[Q.THORChain,Q.Maya],i=new Map,UN=new Map,s=new Map,mT=3600000;function pT(N){let A=s.get(N);if(A?.timestamp&&Date.now()-A.timestamp>mT){s.delete(N);return}return A}function yT(N,A){if(s.size>1000){let T=s.keys().next().value;if(T)s.delete(T)}s.set(N,{...A,timestamp:Date.now()})}class v extends p{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=nA(F||`${H}.${P}`);this.type=WN(I),this.tax=T,this.chain=I.chain,this.ticker=I.ticker,this.symbol=I.symbol,this.address=I.address,this.isSynthetic=I.isSynthetic,this.isTradeAsset=I.isTradeAsset,this.isGasAsset=I.isGasAsset,this.chainId=IN(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 i.get(this.toString())?.logoURI}eqAsset({chain:N,symbol:A}){return this.chain===N&&this.symbol===A}eq(N){return this.eqAsset(N)&&this.eqValue(N)}static fromUrl(N,A=0){let T=N.indexOf(".");if(T===-1)throw new g({errorKey:"helpers_invalid_asset_url",info:{urlAsset:N}});let H=N.slice(0,T),P=N.slice(T+1),F=qN({chain:H,rest:P}).when(({rest:I})=>I.includes(".."),({chain:I,rest:O})=>`${I}.${O.replace(/\.\./g,"~")}`).when(({chain:I,rest:O})=>kN.includes(I)&&O.includes("."),({chain:I,rest:O})=>`${I}.${O.replace(/\./g,"/")}`).otherwise(({chain:I,rest:O})=>`${I}.${O.replace(/__/g,".")}`);return v.from({asset:F,value:A})}static from({value:N=0,fromBaseDecimal:A,asyncTokenLookup:T,...H}){let P=N instanceof p?N.getValue("string"):N,F="address"in H&&"chain"in H,I=hT(H);if(I===null&&T&&F){let{chain:HN,address:d}=H;return fT({address:d,chain:HN,fromBaseDecimal:A,parsedValue:P})}let O=F&&!I?`${H.chain}.UNKNOWN-${H.address}`:I,{identifier:M,decimal:Y}=tN(O),{chain:x,isSynthetic:t,isTradeAsset:j,address:U}=nA(M),{baseDecimal:k}=IN(x),w=i.get(y.includes(x)?M:M.toUpperCase());if(!w&&T&&!t&&!j)return(async()=>{let{ticker:HN}=f(M),d=await BA({address:U,chain:x,ticker:HN});return vN({decimal:d.decimals,identifier:d.identifier,value:A?e(BigInt(P),A):P})})();let b=w?.decimal||Y;c({condition:!b&&!T,id:`assetValue_static_decimal_not_found_${x}`,warning:`Couldn't find static decimal for one or more tokens on ${x} (Using default ${k} decimal as fallback).
2
2
  This can result in incorrect calculations and mess with amount sent on transactions.
3
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:TN,identifier:S,tax:ON}=w||{decimal:b||k,identifier:M},$N=A?e(BigInt(P),A):e(P,TN);return t||j?oT(S,$N):vN({decimal:TN,identifier:S,tax:ON,value:$N})}static async loadStaticAssets(N){let{loadTokenLists:A}=await import("@swapkit/tokens"),T=await A(N);for(let{tokens:H}of Object.values(T))for(let P of H){let{identifier:F}=P,{chain:I,symbol:O}=f(F),{address:M}=uN(O,I),{baseDecimal:Y}=IN(I),x=y.includes(I)?F:F.toUpperCase(),t="decimals"in P&&P.decimals!==void 0?P.decimals:Y,j="logoURI"in P&&P.logoURI?P.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${F.toLowerCase()}.png`,U={decimal:t,identifier:F,logoURI:j,tax:"tax"in P?P.tax:void 0};if(i.set(x,U),M){let k=y.includes(I)?`${I}:${M}`:`${I}:${M.toUpperCase()}`;UN.set(k,F)}}return!0}static setStaticAssets(N){i.clear(),UN.clear();for(let[A,T]of N.entries()){let{identifier:H}=T,{chain:P,symbol:F}=f(H),{address:I}=uN(F,P),{baseDecimal:O}=IN(P),M=T.chain??P,Y=T.address??I,x=y.includes(M)?H:H.toUpperCase(),t=T.decimals??T.decimal??O,j=T.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${H.toLowerCase()}.png`,U={decimal:t,identifier:x,logoURI:j,tax:T.tax};if(i.set(x,U),Y){let k=y.includes(M)?`${M}:${Y}`:`${M}:${Y.toUpperCase()}`;UN.set(k,H)}}return!0}static get staticAssets(){return i}}function bL(N){let A=v.from({chain:N});return qN(N).with(Q.Bitcoin,Q.Litecoin,Q.BitcoinCash,Q.Dash,()=>A.set(0.00010001)).with(Q.Dogecoin,()=>A.set(1.00000001)).with(Q.Avalanche,Q.Ethereum,Q.Arbitrum,Q.BinanceSmartChain,()=>A.set(0.00000001)).with(Q.THORChain,Q.Maya,()=>A.set(0)).with(Q.Cosmos,Q.Kujira,()=>A.set(0.000001)).otherwise(()=>A.set(0.00000001))}async function BA({chain:N,address:A,ticker:T}){let P=y.includes(N)?`${N}:${A||T}`:`${N}:${A||T}`.toUpperCase(),F=pT(P);if(F)return F;if(!A){let{baseDecimal:M}=IN(N);return{decimals:M,identifier:`${N}.${T||"UNKNOWN"}`}}let I=await LA({address:A,chain:N}),O=`${N}.${I.ticker||T||"UNKNOWN"}-${A}`;return c({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&&yT(P,{decimals:I.decimals,identifier:O}),{decimals:I.decimals,identifier:O}}function vN({identifier:N,decimal:A,value:T,tax:H}){return uA(N),new v({decimal:A,identifier:N,tax:H,value:e(T,A)})}function oT(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 g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});return new v({decimal:8,identifier:`${T||Q.THORChain}.${F}${P}${I}`,value:e(A,8)})}async function fT({address:N,chain:A,fromBaseDecimal:T,parsedValue:H}){let{decimals:P,identifier:F}=await BA({address:N,chain:A}),I=T?e(BigInt(H),T):H;return vN({decimal:P,identifier:F,value:I})}function e(N,A){return typeof N==="bigint"?h({bigIntDecimal:A,decimal:A,value:N}):N}function CT(N){let A=qN(N).when((T)=>("chain"in T)&&T.chain!==void 0,({chain:T})=>T).otherwise((T)=>{let H=f(T.asset);return H.synth?Q.THORChain:H.chain});if(!kT.includes(A.toUpperCase())){let T="asset"in N?N.asset:A;throw new g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:T,message:`Unsupported chain "${A}" - use the AssetValue constructor directly`}})}}function hT(N){if(CT(N),"chain"in N){let{chain:P,address:F}=N;if(F){let I=y.includes(P)?`${P}:${F}`:`${P}:${F.toUpperCase()}`,O=UN.get(I);if(O)return O;return null}return P}let{chain:A,symbol:T}=f(N.asset);return WN({chain:A,symbol:T})==="Native"?A:N.asset}function dT(N,A,T){let H=N.split("."),P=H[0]?.toUpperCase(),F=kN.includes(P),I=T?"~":"/",[O,M=""]=F?H.slice(1).join(".").split(I):N.split(I);if(!(O&&M))throw new g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});let{ticker:Y,address:x}=OA({chain:O,symbol:M}),t=`${O}${I}${M}`;return{address:x,chain:P,isGasAsset:!1,isSynthetic:A,isTradeAsset:T,symbol:t,ticker:Y}}function cT(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&&KT.includes(T)&&IA(P)?IA(P):P}catch{I=P}let O=I?`${F}-${I}`:H;return{address:I,chain:T,isGasAsset:gN({chain:T,symbol:H}),isSynthetic:!1,isTradeAsset:!1,symbol:O,ticker:F}}function nA(N){let A=N.slice(0,14),T=A.includes("/"),H=A.includes("~");if(T||H)return dT(N,T,H);return cT(N)}function OA({symbol:N,chain:A}){let{ticker:T,address:H}=uN(N,A);return{address:H&&!y.includes(A)?H.toLowerCase():H,ticker:T}}class SN extends p{eq(N){return this.eqValue(N)}static fromBigInt(N,A){return new SN({decimal:A,value:h({bigIntDecimal:A,decimal:A,value:N})})}}function $A(N=!0){return N?"https://midgard.thorchain.network":"https://midgard.mayachain.info"}function rT(N=!0){let A=$A(N);return N?`${A}/v2/thorname`:`${A}/v2/mayaname`}function iT(N){return function(T){let H=T?`?status=${T}`:"";return G.get(`${N}/v2/pools${H}`)}}function sT(N){return function(T){return G.get(`${N}/v2/pool/${T}`)}}function eT(N){return function(T,H){let P=H?`?period=${H}`:"";return G.get(`${N}/v2/pool/${T}/stats${P}`)}}function aT(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 NH(N){return function(){return G.get(`${N}/v2/network`)}}function AH(N){return function(){return G.get(`${N}/v2/health`)}}function TH(N){return function(){return G.get(`${N}/v2/nodes`)}}function HH(N){return function(T){return G.get(`${N}/v2/node/${T}`)}}function PH(N){return function(){return G.get(`${N}/v2/mimir/votes`)}}function LH(N){return function(){return G.get(`${N}/v2/mimir`)}}function RH(N){return function(){return G.get(`${N}/v2/constants`)}}function uH(N){return function(){return G.get(`${N}/v2/stats`)}}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/earnings${P}`)}}function IH(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 nH(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 BH(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 OH(N){return function(T){let H=BH(T);return G.get(`${N}/v2/actions${H}`)}}function $H(N){return function(T){return G.get(`${N}/v2/member/${T}`)}}function GH(N){return function(T){let H=T?`/${T}`:"";return G.get(`${N}/v2/members${H}`)}}function MH(N){return function(T,H){let P=H?`&asset=${H}`:"";return G.get(`${N}/v2/saver/${T}${P?`?${P.substring(1)}`:""}`)}}function _H(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 DH(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 YH(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 UH(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 a({asset:N,value:A}){return v.from({asset:N,fromBaseDecimal:lT(XN.THORChain).baseDecimal,value:A})}function SH({liquidityPositionGetter:N,isThorchain:A}){return async function(H){let P=await N(H),F=A?"rune":"cacao";return P.pools.map((I)=>({[`${F}Pending`]:a({asset:"THOR.RUNE",value:I.runePending}),[`${F}RegisteredAddress`]:I.runeAddress,[`${F}Withdrawn`]:a({asset:"THOR.RUNE",value:I.runeWithdrawn}),[F]:a({asset:"THOR.RUNE",value:I.runeAdded}),asset:a({asset:I.pool,value:I.assetAdded}),assetPending:a({asset:I.pool,value:I.assetPending}),assetRegisteredAddress:I.assetAddress,assetWithdrawn:a({asset:I.pool,value:I.assetWithdrawn}),dateFirstAdded:I.dateFirstAdded,dateLastAdded:I.dateLastAdded,poolShare:new SN(I.liquidityUnits).div(I.pool)}))}}function GA(N){let A=N===XN.THORChain,T=$A(A),H=rT(A),P=$H(T);return{getActions:OH(T),getBalance:tH(T),getConstants:RH(T),getEarningsHistory:FH(T),getHealth:AH(T),getLiquidityPosition:SH({isThorchain:A,liquidityPositionGetter:P}),getLiquidityPositionRaw:P,getMembers:GH(T),getMimir:LH(T),getMimirVotes:PH(T),getNameDetails:DH(H),getNamesByAddress:YH(H),getNamesByOwner:UH(H),getNetworkInfo:NH(T),getNode:HH(T),getNodes:TH(T),getPool:sT(T),getPoolDepthHistory:aT(T),getPoolStats:eT(T),getPools:iT(T),getSaverDetails:MH(T),getSavers:_H(T),getSaversHistory:gH(T),getStats:uH(T),getSwapHistory:IH(T),getTVLHistory:nH(T)}}var MA=GA(XN.THORChain),_A=GA(XN.Maya);var yN={};dN(yN,{getTrackerDetails:()=>iH,getTokenListProviders:()=>AP,getTokenList:()=>TP,getTokenApproval:()=>NP,getSwapTo:()=>nP,getSwapQuote:()=>sH,getRouteWithTx:()=>eH,getPrice:()=>HP,getNearDepositChannel:()=>RP,getGasRate:()=>PP,getChainflipDepositChannel:()=>LP,getChainBalance:()=>aH,SKRequestClient:()=>W});import{EVMChains as lH}from"@swapkit/types";import{match as rH,P as BN}from"ts-pattern";async function gA(N,A,T,H){let P=`${A}:${T}:${H}`,F=new TextEncoder,I=await crypto.subtle.importKey("raw",F.encode(N),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),O=await crypto.subtle.sign("HMAC",I,F.encode(P));return Array.from(new Uint8Array(O)).map((M)=>M.toString(16).padStart(2,"0")).join("")}import{Chain as EN,ChainId as nN}from"@swapkit/types";import{array as X,boolean as K,coerce as UA,number as _,object as $,optional as B,string as R,union as KN,unknown as SA,z as L}from"zod/v4";var XA;((H)=>{H.CHEAPEST="CHEAPEST";H.FASTEST="FASTEST";H.RECOMMENDED="RECOMMENDED"})(XA||={});var QN;((P)=>{P.PSBT="PSBT";P.EVM="EVM";P.COSMOS="COSMOS";P.RADIX="RADIX"})(QN||={});var EA;((b)=>{b.approve="approve";b.claim="claim";b.deposit="deposit";b.donate="donate";b.lending="lending";b.lp_action="lp_action";b.native_contract_call="native_contract_call";b.native_send="native_send";b.stake="stake";b.streaming_swap="streaming_swap";b.swap="swap";b.thorname_action="thorname_action";b.token_contract_call="token_contract_call";b.token_transfer="token_transfer";b.unknown="unknown";b.unstake="unstake"})(EA||={});var QA;((U)=>{U.swap="swap";U.aggregation="aggregation";U.addLiquidity="addLiquidity";U.withdrawLiquidity="withdrawLiquidity";U.addSavers="addSavers";U.withdrawSavers="withdrawSavers";U.borrow="borrow";U.repay="repay";U.name="name";U.donate="donate";U.claim="claim";U.stake="stake";U.unstake="unstake"})(QA||={});var xA;((O)=>{O.unknown="unknown";O.not_started="not_started";O.pending="pending";O.swapping="swapping";O.completed="completed";O.refunded="refunded";O.failed="failed"})(xA||={});var wA;((w)=>{w.not_started="not_started";w.starting="starting";w.broadcasted="broadcasted";w.mempool="mempool";w.inbound="inbound";w.outbound="outbound";w.swapping="swapping";w.completed="completed";w.refunded="refunded";w.partially_refunded="partially_refunded";w.dropped="dropped";w.reverted="reverted";w.replaced="replaced";w.retries_exceeded="retries_exceeded";w.parsing_error="parsing_error"})(wA||={});var yL=$({address:B(R()),chain:L.enum(EN).optional(),chainId:L.enum(nN),coingeckoId:B(R()),decimals:UA.number(),extensions:B(L.looseObject({})),identifier:R(),logoURI:B(R()),name:B(R()),shortCode:B(R()),symbol:B(R()),ticker:R()}),oL=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"}),fL=L.object({forceUpdate:L.string().toLowerCase().transform((N)=>N==="true").pipe(L.boolean()).optional()}),CL=$({error:R(),message:R()}),NN=$({address:B(R()),chain:L.enum(EN),decimal:B(_()),isGasAsset:K(),isSynthetic:K(),symbol:R(),tax:B($({buy:_(),sell:_()})),ticker:R()}),bA=$({id:R(),market_cap:_(),name:R(),price_change_24h_usd:_(),price_change_percentage_24h_usd:_(),sparkline_in_7d:X(_()),timestamp:R(),total_volume:_()}).partial(),hL=$({cg:B(bA),identifier:R(),price_usd:_(),provider:R(),timestamp:_()}),zA=X($({cg:B(bA),identifier:R(),price_usd:_(),provider:R(),timestamp:_()}).partial()),dL=$({affiliate:B(R().describe("Affiliate thorname")),affiliateFee:B(_().describe("Affiliate fee in basis points").refine((N)=>N===Math.floor(N)&&N>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:B(K().describe("Allow smart contract as recipient")),allowSmartContractSender:B(K().describe("Allow smart contract as sender")),buyAsset:R().describe("Asset to buy"),cfBoost:B(K().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:B(R().describe("Address to send asset to")),disableSecurityChecks:B(K().describe("Disable security checks")),includeTx:B(K().describe("Set to true to include an transaction object (EVM only)")),providers:B(X(R().describe("List of providers to use").refine((N)=>J[N]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:B(R().describe("Referrer address (referral program)")),sellAmount:R().describe("Amount of asset to sell").refine((N)=>+N>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:R().describe("Asset to sell"),slippage:B(_().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:B(R().describe("Address to send asset from"))}).refine((N)=>N.sellAsset!==N.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),cL=$({metadata:K(),tokens:X($({identifier:R()}))}),JA=$({destinationAddress:R()}),XH=JA.extend({affiliateFees:X($({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()})}),ZA=$({channelId:R(),depositAddress:R()}),tA=JA.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()}),lL=DA.extend({depositAddress:R(),quote:DA,signature:R(),timestamp:R(),tx:SA()}),VA=$({buyAsset:R(),buyAssetAmount:R(),buyAssetAmountMaxSlippage:R(),deadline:R().optional(),depositAddress:R(),depositAmount:R(),depositAsset:R(),tx:SA()}),EH=$({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())}),QH=$({currentStage:R(),inboundConfirmation:_(),inboundObservation:_(),outboundDelay:_(),outboundObservation:_(),streamingSwap:_()}),xH=$({count:B(_()),interval:B(_()),quantity:B(_()),subSwapsMap:B(X(_()))}),wH=L.object({currentLegIndex:L.optional(L.number()),estimatedTimeToComplete:L.number(),estimates:L.optional(QH),providerDetails:L.optional(L.object({streamingDetails:L.optional(xH)}))}),bH=$({affiliate:B(NN),liquidity:B(NN),network:B(NN),protocol:B(NN),tax:B(NN)}),zH=$({affiliate:R(),bps:R(),isReferrer:K()}),JH=$({affiliate:B(R()),affiliateFees:B(X(zH)),broadcastedAt:B(_()),explorerUrl:B(R()),fees:B(bH),images:B($({chain:B(R()),from:B(R()),provider:B(R()),to:B(R())})),provider:B(L.enum(J)),providerAction:L.optional(L.enum(QA)),quoteId:B(R()),wallet:B(R())}),AN=L.object({block:L.number(),chainId:L.enum(nN),finalAddress:L.optional(L.string()),finalAsset:L.optional(NN),finalisedAt:L.number(),fromAddress:L.string(),fromAmount:L.string(),fromAsset:L.string(),hash:L.string(),meta:L.optional(JH),payload:L.optional(EH),status:L.enum(xA),toAddress:L.string(),toAmount:L.string(),toAsset:L.string(),trackingStatus:L.optional(L.enum(wA)),transient:L.optional(wH),type:L.enum(EA)}),WA=AN.extend({legs:L.array(AN)}),rL=AN.extend({legs:X(AN)}),iL=AN.extend({legs:X(AN)}),mN=X($({amount:R(),asset:R(),chain:R(),protocol:L.enum(J),type:L.enum(bN)})),pN=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")}),jA=$({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=X(KN([R(),_(),X(R()),$({from:R(),value:R()}).describe("Parameters to pass to the contract method")])),sL=$({approvalSpender:B(R().describe("Address of the spender to approve")),approvalToken:B(R().describe("Address of the token to approve spending of")),contractAddress:R().describe("Address of the contract to interact with"),contractMethod:R().describe("Name of the method to call"),contractParamNames:X(R().describe("Names of the parameters to pass to the contract method")),contractParams:ZH}),VH=$({typeUrl:R("/types.MsgDeposit"),value:$({coins:X($({amount:R(),asset:$({chain:R(),symbol:R(),synth:K(),ticker:R()})})),memo:R(),signer:R()})}),WH=$({typeUrl:R("/types.MsgSend"),value:$({amount:X($({amount:R(),denom:R()})),fromAddress:R(),toAddress:R()})}),jH=$({typeUrl:R(),value:WH.shape.value.or(VH.shape.value)}),vH=$({amount:X($({amount:R(),denom:R()})),gas:R()}),qA=$({accountNumber:_(),chainId:L.enum(nN),fee:vH,memo:R(),msgs:X(jH),sequence:_()}),qH=L.array(L.object({calldata:L.array(L.string()),contractAddress:L.string(),entrypoint:L.string()})),kA=L.array(L.object({address:L.string().describe("Destination address in friendly format"),amount:L.string().describe("Amount in nanotons"),payload:L.string().optional().describe("Base64 BOC of body cell"),stateInit:L.string().optional().describe("Base64 BOC of state init")})),kH=$({affiliate:R().describe("Affiliate address").optional(),affiliateFee:_().describe("Affiliate fee").optional(),buyAsset:R().describe("Asset to buy"),destinationAddress:R().describe("Destination address"),estimatedTime:pN.optional(),provider:L.enum(J),sellAsset:R().describe("Asset to sell"),slipPercentage:_().describe("Slippage as a percentage"),sourceAddress:R().describe("Source address")}),eL=kH.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),KH=$({asset:R().describe("Asset name"),image:R().describe("Asset image"),price:_().describe("Price in USD")}),mH=XH,KA=$({assets:B(X(KH)),maxStreamingQuantity:_().optional(),referrer:R().optional(),streamingInterval:_().optional(),tags:X(L.enum(XA))}),mA=KA.extend({affiliate:B(R()),affiliateFee:B(R()),approvalAddress:B(R().describe("Approval address for swap")),chainflip:mH.optional(),garden:tA.optional(),near:tA.optional(),priceImpact:B(_().describe("Price impact")),referrer:B(R()),txType:B(L.enum(QN))}),pA=X($({code:L.enum(wN),display:R(),tooltip:R().optional()})),pH=$({buyAmount:R().describe("Buy amount"),buyAmountMaxSlippage:R().describe("Buy amount max slippage"),buyAsset:R().describe("Asset to buy"),fees:B(mN),provider:L.enum(J),sellAmount:R().describe("Sell amount"),sellAsset:R().describe("Asset to sell")}),yH=$({buyAsset:R().describe("Asset to buy"),destinationAddress:B(R().describe("Destination address")),estimatedTime:B(pN),expectedBuyAmount:R().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:R().describe("Expected Buy amount max slippage"),expiration:B(R().describe("Expiration")),fees:mN,inboundAddress:B(R().describe("Inbound address")),legs:X(pH),memo:B(R().describe("Memo")),meta:mA,providers:X(L.enum(J)),routeId:R().describe("Route ID"),sellAmount:R().describe("Sell amount"),sellAsset:R().describe("Asset to sell"),sourceAddress:B(R().describe("Source address")),targetAddress:B(R().describe("Target address")),totalSlippageBps:_().describe("Total slippage in bps"),tx:B(KN([jA,qA,vA,qH,kA,R()])),txType:B(L.enum(QN)),warnings:pA}),yA=$({error:B(R().describe("Error message")),providerErrors:B(X($({errorCode:B(L.enum(LN)),message:B(R()),provider:L.enum(J).optional()}))),quoteId:R().describe("Quote ID"),routes:X(yH)}),oA=L.object({chainId:L.enum(nN),createdAt:L.date(),id:L.number(),unit:L.string(),value:L.string()}),oH=L.array(oA),fA=L.union([oA,oH]),aL=X($({chain:L.enum(EN),decimal:_(),identifier:R(),symbol:R(),ticker:R(),value:R()})),NR=L.union([L.object({amount:L.string(),spender:L.string(),tokenIdentifier:L.string(),userWalletAddress:L.string()}),L.object({amount:L.string(),chainId:L.enum(nN),spender:L.string(),tokenContractAddress:L.string(),userWalletAddress:L.string()}),L.object({routeId:L.string()})]),AR=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()}),fH=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:mN,provider:L.enum(J),sellAmount:L.string().describe("Sell amount"),sellAsset:L.string().describe("Asset to sell")}),CA=YA.extend({estimatedTime:L.optional(pN),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:pA}).omit({provider:!0}),CH=L.object({method:L.string(),payload:L.optional(L.unknown()),url:L.string()}),hH=CA.extend({meta:KA,nextActions:L.optional(L.array(CH))}),TR=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(L.object({errorCode:L.optional(L.enum(LN)),message:L.optional(L.string()),provider:L.enum(J).optional()}))),quoteId:L.string().describe("Quote ID"),routes:L.array(hH)}),HR=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')")}),dH=L.object({chain:L.enum(EN).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")}),PR=L.object({buyAssets:L.array(dH).describe("List of assets that can be swapped to"),sellAsset:L.string().describe("The input sell asset identifier")}),hA=CA.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:mA,sourceAddress:L.string().describe("Source address"),targetAddress:L.optional(L.string().describe("Target address")),tx:B(KN([jA,qA,vA,kA,R()])),txType:L.optional(L.enum(QN))}),cH=L.object({data:L.optional(L.record(L.string(),L.string().optional())),errorCode:L.enum(LN),message:L.string().optional(),provider:L.enum(J).optional()}),LR=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(cH)),quoteId:L.string().describe("Quote ID"),routes:L.array(hA)}),dA=hA.extend({approvalTx:fH.optional().describe("Optional approval transaction if ERC-20 approval is required before swap"),swapId:L.string().describe("The unique swap ID for tracking")});var W=G.extend({dynamicHeader:async()=>{let N=E.get("widgetId"),A=E.get("widgetKey");if(N&&A&&typeof window<"u"){let H=Math.floor(Date.now()/1000),P=window.location.origin;return{"X-Signature":await gA(A,N,P,H),"X-Timestamp":H.toString(),"x-widget-id":N}}let{swapKit:T}=E.get("apiKeys");return T?{"x-api-key":T}:{}}});async function iH(N){let A=await W.post(V("/track"),{json:N});try{let T=WA.safeParse(A);if(!T.success)throw new g("api_v2_invalid_response",T.error);return T.data}catch(T){return A}}async function sH(N){let{getQuote:A}=E.get("endpoints");if(A)return A(N);let H=E.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",P=await W.post(V(H),{json:N});if(P.error)throw new g("api_v2_server_error",{message:P.error});try{let F=yA.safeParse(P);if(!F.success)throw new g("api_v2_invalid_response",F.error);return F.data}catch{return P}}async function eH(N){let{getRouteWithTx:A}=E.get("endpoints");if(A)return A(N);let H=E.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",P=await W.post(V(H),{json:N});try{let F=dA.safeParse(P);if(!F.success)throw new g("api_v2_invalid_response",F.error);return F.data}catch(F){return console.error(new g("api_v2_invalid_response",F)),P}}async function aH({chain:N,address:A,scamFilter:T=!0}){let{getBalance:H}=E.get("endpoints");if(H)return H({address:A,chain:N});let P=V(`/balance?chain=${N}&address=${A}`),F=await W.get(P),I=Array.isArray(F)?F:[];return T?IP(I):I}function NP(N){let A=rH(N).with({routeId:BN.string,spender:BN.string},({routeId:T,spender:H})=>V(`/approve?routeId=${T}&sourceAddress=${H}`)).with({assetValue:BN.instanceOf(v),spender:BN.string,userWallet:BN.string},({spender:T,userWallet:H,assetValue:P})=>V(`/approve?tokenIdentifier=${P.toString()}&userWalletAddress=${H}&spender=${T}&amount=${P.getValue("string")}`)).exhaustive();return W.get(A)}function AP(){let N=V("/providers");return W.get(N)}function TP(N){let A=V(`/tokens?provider=${N}`);return W.get(A)}async function HP(N){let A=V("/price"),T=await W.post(A,{json:N});try{let H=zA.safeParse(T);if(!H.success)throw new g("api_v2_invalid_response",H.error);return H.data}catch(H){throw new g("api_v2_invalid_response",H)}}async function PP(){let N=V("/gas"),A=await W.get(N);try{let T=fA.safeParse(A);if(!T.success)throw new g("api_v2_invalid_response",T.error);return Array.isArray(T)?T:[T]}catch(T){throw new g("api_v2_invalid_response",T)}}async function LP(N){let{destinationAddress:A}=N;if(!A)throw new g("chainflip_broker_invalid_params");let T=E.get("integrations").chainflip?.brokerUrl||V("/chainflip/broker/channel"),H=await W.post(T,{json:N});try{let P=ZA.safeParse(H);if(!P.success)throw new g("api_v2_invalid_response",P.error);return P.data}catch(P){throw new g("api_v2_invalid_response",P)}}async function RP(N){let{destinationAddress:A}=N;if(!A)throw new g("chainflip_broker_invalid_params");let T=V("/near/channel"),H=await W.post(T,{json:N});try{let P=VA.safeParse(H);if(!P.success)throw new g("api_v2_invalid_response",P.error);return P.data}catch(P){throw new g("api_v2_invalid_response",P)}}function V(N){let{isDev:A,apiUrl:T,devApiUrl:H}=E.get("envs");return`${A?H:T}${N}`}function uP(N){let[A,T]=N.split(".");if(!lH.includes(A))return!0;let H=T.split("-"),P=H.length===1?void 0:H[H.length-1];return gN({chain:A,symbol:T})||!!P}var FP=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi");function IP(N){return N.filter((A)=>{return!FP.test(A.identifier)&&uP(A.identifier)})}async function nP(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 W.get(H);if(!Array.isArray(P))return{buyAssets:[],sellAsset:N.sellAsset};let F=[];for(let I of P)try{let O=v.from({asset:I});F.push({chain:O.chain,identifier:O.toString(),providers:[],symbol:O.symbol,ticker:O.ticker})}catch{}return{buyAssets:F,sellAsset:N.sellAsset}}var oN={};dN(oN,{getThorchainQueue:()=>GP,getTcyStakers:()=>SP,getTcyStaker:()=>UP,getTcyClaimers:()=>EP,getTcyClaimer:()=>XP,getTNSPreferredAsset:()=>tP,getTHORNodeTNSDetails:()=>cA,getRunePoolProviderInfo:()=>YP,getRunePoolInfo:()=>DP,getNodes:()=>MP,getMimirInfo:()=>_P,getLastBlock:()=>$P,getInboundAddresses:()=>gP});import{match as BP}from"ts-pattern";function q(N){let{isStagenet:A}=E.get("envs"),T=E.get("thornodeUrls");return`${BP({isStagenet:A,type:N}).with({type:"mayachain"},({isStagenet:P})=>P?T.MAYA_STAGENET:T.MAYA).with({type:"thorchain"},({isStagenet:P})=>P?T.THOR_STAGENET:T.THOR)}/${N}`}function OP(N){let A=N==="mayachain"?"mayaname":"thorname";return`${q(N)}/${A}`}function $P(N="thorchain"){return G.get(`${q(N)}/lastblock`)}function GP(N){return G.get(`${q(N)}/queue`)}function MP(N){return G.get(`${q(N)}/nodes`)}function _P(N){return G.get(`${q(N)}/mimir`)}function gP(N){return G.get(`${q(N)}/inbound_addresses`)}async function cA({type:N,name:A}){try{return await G.get(`${OP(N)}/${A}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:A,owner:"",preferred_asset:""}}}async function tP({type:N,tns:A}){let T=await cA({name:A,type:N});if(!T.preferred_asset||T.preferred_asset===".")return;return v.from({asset:T.preferred_asset,asyncTokenLookup:!0})}function DP(N){return G.get(`${q(N)}/runepool`)}function YP({type:N,thorAddress:A}){return G.get(`${q(N)}/rune_provider/${A}`)}function UP({type:N,address:A}){return G.get(`${q(N)}/tcy_staker/${A}`)}function SP(N){return G.get(`${q(N)}/tcy_stakers`)}function XP({type:N,address:A}){return G.get(`${q(N)}/tcy_claimer/${A}`)}function EP(N){return G.get(`${q(N)}/tcy_claimers`)}var UR={...yN,mayachainMidgard:_A,thorchainMidgard:MA,thornode:oN};
4
+ or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`});let{decimal:TN,identifier:S,tax:ON}=w||{decimal:b||k,identifier:M},$N=A?e(BigInt(P),A):e(P,TN);return t||j?oT(S,$N):vN({decimal:TN,identifier:S,tax:ON,value:$N})}static async loadStaticAssets(N){let{loadTokenLists:A}=await import("@swapkit/tokens"),T=await A(N);for(let{tokens:H}of Object.values(T))for(let P of H){let{identifier:F}=P,{chain:I,symbol:O}=f(F),{address:M}=uN(O,I),{baseDecimal:Y}=IN(I),x=y.includes(I)?F:F.toUpperCase(),t="decimals"in P&&P.decimals!==void 0?P.decimals:Y,j="logoURI"in P&&P.logoURI?P.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${F.toLowerCase()}.png`,U={decimal:t,identifier:F,logoURI:j,tax:"tax"in P?P.tax:void 0};if(i.set(x,U),M){let k=y.includes(I)?`${I}:${M}`:`${I}:${M.toUpperCase()}`;UN.set(k,F)}}return!0}static setStaticAssets(N){i.clear(),UN.clear();for(let[A,T]of N.entries()){let{identifier:H}=T,{chain:P,symbol:F}=f(H),{address:I}=uN(F,P),{baseDecimal:O}=IN(P),M=T.chain??P,Y=T.address??I,x=y.includes(M)?H:H.toUpperCase(),t=T.decimals??T.decimal??O,j=T.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${H.toLowerCase()}.png`,U={decimal:t,identifier:x,logoURI:j,tax:T.tax};if(i.set(x,U),Y){let k=y.includes(M)?`${M}:${Y}`:`${M}:${Y.toUpperCase()}`;UN.set(k,H)}}return!0}static get staticAssets(){return i}}function bL(N){let A=v.from({chain:N});return qN(N).with(Q.Bitcoin,Q.Litecoin,Q.BitcoinCash,Q.Dash,()=>A.set(0.00010001)).with(Q.Dogecoin,()=>A.set(1.00000001)).with(Q.Avalanche,Q.Ethereum,Q.Arbitrum,Q.BinanceSmartChain,()=>A.set(0.00000001)).with(Q.THORChain,Q.Maya,()=>A.set(0)).with(Q.Cosmos,Q.Kujira,()=>A.set(0.000001)).otherwise(()=>A.set(0.00000001))}async function BA({chain:N,address:A,ticker:T}){let P=y.includes(N)?`${N}:${A||T}`:`${N}:${A||T}`.toUpperCase(),F=pT(P);if(F)return F;if(!A){let{baseDecimal:M}=IN(N);return{decimals:M,identifier:`${N}.${T||"UNKNOWN"}`}}let I=await LA({address:A,chain:N}),O=`${N}.${I.ticker||T||"UNKNOWN"}-${A}`;return c({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&&yT(P,{decimals:I.decimals,identifier:O}),{decimals:I.decimals,identifier:O}}function vN({identifier:N,decimal:A,value:T,tax:H}){return uA(N),new v({decimal:A,identifier:N,tax:H,value:e(T,A)})}function oT(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 g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});return new v({decimal:8,identifier:`${T||Q.THORChain}.${F}${P}${I}`,value:e(A,8)})}async function fT({address:N,chain:A,fromBaseDecimal:T,parsedValue:H}){let{decimals:P,identifier:F}=await BA({address:N,chain:A}),I=T?e(BigInt(H),T):H;return vN({decimal:P,identifier:F,value:I})}function e(N,A){return typeof N==="bigint"?h({bigIntDecimal:A,decimal:A,value:N}):N}function CT(N){let A=qN(N).when((T)=>("chain"in T)&&T.chain!==void 0,({chain:T})=>T).otherwise((T)=>{let H=f(T.asset);return H.synth?Q.THORChain:H.chain});if(!kT.includes(A.toUpperCase())){let T="asset"in N?N.asset:A;throw new g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:T,message:`Unsupported chain "${A}" - use the AssetValue constructor directly`}})}}function hT(N){if(CT(N),"chain"in N){let{chain:P,address:F}=N;if(F){let I=y.includes(P)?`${P}:${F}`:`${P}:${F.toUpperCase()}`,O=UN.get(I);if(O)return O;return null}return P}let{chain:A,symbol:T}=f(N.asset);return WN({chain:A,symbol:T})==="Native"?A:N.asset}function dT(N,A,T){let H=N.split("."),P=H[0]?.toUpperCase(),F=kN.includes(P),I=T?"~":"/",[O,M=""]=F?H.slice(1).join(".").split(I):N.split(I);if(!(O&&M))throw new g({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});let{ticker:Y,address:x}=OA({chain:O,symbol:M}),t=`${O}${I}${M}`;return{address:x,chain:P,isGasAsset:!1,isSynthetic:A,isTradeAsset:T,symbol:t,ticker:Y}}function cT(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&&KT.includes(T)&&IA(P)?IA(P):P}catch{I=P}let O=I?`${F}-${I}`:H;return{address:I,chain:T,isGasAsset:gN({chain:T,symbol:H}),isSynthetic:!1,isTradeAsset:!1,symbol:O,ticker:F}}function nA(N){let A=N.slice(0,14),T=A.includes("/"),H=A.includes("~");if(T||H)return dT(N,T,H);return cT(N)}function OA({symbol:N,chain:A}){let{ticker:T,address:H}=uN(N,A);return{address:H&&!y.includes(A)?H.toLowerCase():H,ticker:T}}class SN extends p{eq(N){return this.eqValue(N)}static fromBigInt(N,A){return new SN({decimal:A,value:h({bigIntDecimal:A,decimal:A,value:N})})}}function $A(N=!0){return N?"https://midgard.thorchain.network":"https://midgard.mayachain.info"}function rT(N=!0){let A=$A(N);return N?`${A}/v2/thorname`:`${A}/v2/mayaname`}function iT(N){return function(T){let H=T?`?status=${T}`:"";return G.get(`${N}/v2/pools${H}`)}}function sT(N){return function(T){return G.get(`${N}/v2/pool/${T}`)}}function eT(N){return function(T,H){let P=H?`?period=${H}`:"";return G.get(`${N}/v2/pool/${T}/stats${P}`)}}function aT(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 NH(N){return function(){return G.get(`${N}/v2/network`)}}function AH(N){return function(){return G.get(`${N}/v2/health`)}}function TH(N){return function(){return G.get(`${N}/v2/nodes`)}}function HH(N){return function(T){return G.get(`${N}/v2/node/${T}`)}}function PH(N){return function(){return G.get(`${N}/v2/mimir/votes`)}}function LH(N){return function(){return G.get(`${N}/v2/mimir`)}}function RH(N){return function(){return G.get(`${N}/v2/constants`)}}function uH(N){return function(){return G.get(`${N}/v2/stats`)}}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/earnings${P}`)}}function IH(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 nH(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 BH(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 OH(N){return function(T){let H=BH(T);return G.get(`${N}/v2/actions${H}`)}}function $H(N){return function(T){return G.get(`${N}/v2/member/${T}`)}}function GH(N){return function(T){let H=T?`/${T}`:"";return G.get(`${N}/v2/members${H}`)}}function MH(N){return function(T,H){let P=H?`&asset=${H}`:"";return G.get(`${N}/v2/saver/${T}${P?`?${P.substring(1)}`:""}`)}}function _H(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 DH(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 YH(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 UH(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 a({asset:N,value:A}){return v.from({asset:N,fromBaseDecimal:lT(XN.THORChain).baseDecimal,value:A})}function SH({liquidityPositionGetter:N,isThorchain:A}){return async function(H){let P=await N(H),F=A?"rune":"cacao";return P.pools.map((I)=>({[`${F}Pending`]:a({asset:"THOR.RUNE",value:I.runePending}),[`${F}RegisteredAddress`]:I.runeAddress,[`${F}Withdrawn`]:a({asset:"THOR.RUNE",value:I.runeWithdrawn}),[F]:a({asset:"THOR.RUNE",value:I.runeAdded}),asset:a({asset:I.pool,value:I.assetAdded}),assetPending:a({asset:I.pool,value:I.assetPending}),assetRegisteredAddress:I.assetAddress,assetWithdrawn:a({asset:I.pool,value:I.assetWithdrawn}),dateFirstAdded:I.dateFirstAdded,dateLastAdded:I.dateLastAdded,poolShare:new SN(I.liquidityUnits).div(I.pool)}))}}function GA(N){let A=N===XN.THORChain,T=$A(A),H=rT(A),P=$H(T);return{getActions:OH(T),getBalance:tH(T),getConstants:RH(T),getEarningsHistory:FH(T),getHealth:AH(T),getLiquidityPosition:SH({isThorchain:A,liquidityPositionGetter:P}),getLiquidityPositionRaw:P,getMembers:GH(T),getMimir:LH(T),getMimirVotes:PH(T),getNameDetails:DH(H),getNamesByAddress:YH(H),getNamesByOwner:UH(H),getNetworkInfo:NH(T),getNode:HH(T),getNodes:TH(T),getPool:sT(T),getPoolDepthHistory:aT(T),getPoolStats:eT(T),getPools:iT(T),getSaverDetails:MH(T),getSavers:_H(T),getSaversHistory:gH(T),getStats:uH(T),getSwapHistory:IH(T),getTVLHistory:nH(T)}}var MA=GA(XN.THORChain),_A=GA(XN.Maya);var yN={};dN(yN,{getTrackerDetails:()=>iH,getTokenListProviders:()=>AP,getTokenList:()=>TP,getTokenApproval:()=>NP,getSwapTo:()=>nP,getSwapQuote:()=>sH,getRouteWithTx:()=>eH,getPrice:()=>HP,getNearDepositChannel:()=>RP,getGasRate:()=>PP,getChainflipDepositChannel:()=>LP,getChainBalance:()=>aH,SKRequestClient:()=>W});import{EVMChains as lH}from"@swapkit/types";import{match as rH,P as BN}from"ts-pattern";async function gA(N,A,T,H){let P=`${A}:${T}:${H}`,F=new TextEncoder,I=await crypto.subtle.importKey("raw",F.encode(N),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),O=await crypto.subtle.sign("HMAC",I,F.encode(P));return Array.from(new Uint8Array(O)).map((M)=>M.toString(16).padStart(2,"0")).join("")}import{Chain as EN,ChainId as nN}from"@swapkit/types";import{array as X,boolean as K,coerce as UA,number as _,object as $,optional as B,string as R,union as KN,unknown as SA,z as L}from"zod/v4";var XA;((H)=>{H.CHEAPEST="CHEAPEST";H.FASTEST="FASTEST";H.RECOMMENDED="RECOMMENDED"})(XA||={});var QN;((P)=>{P.PSBT="PSBT";P.EVM="EVM";P.COSMOS="COSMOS";P.RADIX="RADIX"})(QN||={});var EA;((b)=>{b.approve="approve";b.claim="claim";b.deposit="deposit";b.donate="donate";b.lending="lending";b.lp_action="lp_action";b.native_contract_call="native_contract_call";b.native_send="native_send";b.stake="stake";b.streaming_swap="streaming_swap";b.swap="swap";b.thorname_action="thorname_action";b.token_contract_call="token_contract_call";b.token_transfer="token_transfer";b.unknown="unknown";b.unstake="unstake"})(EA||={});var QA;((U)=>{U.swap="swap";U.aggregation="aggregation";U.addLiquidity="addLiquidity";U.withdrawLiquidity="withdrawLiquidity";U.addSavers="addSavers";U.withdrawSavers="withdrawSavers";U.borrow="borrow";U.repay="repay";U.name="name";U.donate="donate";U.claim="claim";U.stake="stake";U.unstake="unstake"})(QA||={});var xA;((O)=>{O.unknown="unknown";O.not_started="not_started";O.pending="pending";O.swapping="swapping";O.completed="completed";O.refunded="refunded";O.failed="failed"})(xA||={});var wA;((w)=>{w.not_started="not_started";w.starting="starting";w.broadcasted="broadcasted";w.mempool="mempool";w.inbound="inbound";w.outbound="outbound";w.swapping="swapping";w.completed="completed";w.refunded="refunded";w.partially_refunded="partially_refunded";w.dropped="dropped";w.reverted="reverted";w.replaced="replaced";w.retries_exceeded="retries_exceeded";w.parsing_error="parsing_error"})(wA||={});var yL=$({address:B(R()),chain:L.enum(EN).optional(),chainId:L.enum(nN),coingeckoId:B(R()),decimals:UA.number(),extensions:B(L.looseObject({})),identifier:R(),logoURI:B(R()),name:B(R()),shortCode:B(R()),symbol:B(R()),ticker:R()}),oL=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"}),fL=L.object({forceUpdate:L.string().toLowerCase().transform((N)=>N==="true").pipe(L.boolean()).optional()}),CL=$({error:R(),message:R()}),NN=$({address:B(R()),chain:L.enum(EN),decimal:B(_()),isGasAsset:K(),isSynthetic:K(),symbol:R(),tax:B($({buy:_(),sell:_()})),ticker:R()}),bA=$({id:R(),market_cap:_(),name:R(),price_change_24h_usd:_(),price_change_percentage_24h_usd:_(),sparkline_in_7d:X(_()),timestamp:R(),total_volume:_()}).partial(),hL=$({cg:B(bA),identifier:R(),price_usd:_(),provider:R(),timestamp:_()}),zA=X($({cg:B(bA),identifier:R(),price_usd:_(),provider:R(),timestamp:_()}).partial()),dL=$({affiliate:B(R().describe("Affiliate thorname")),affiliateFee:B(_().describe("Affiliate fee in basis points").refine((N)=>N===Math.floor(N)&&N>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:B(K().describe("Allow smart contract as recipient")),allowSmartContractSender:B(K().describe("Allow smart contract as sender")),buyAsset:R().describe("Asset to buy"),cfBoost:B(K().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:B(R().describe("Address to send asset to")),disableSecurityChecks:B(K().describe("Disable security checks")),includeTx:B(K().describe("Set to true to include an transaction object (EVM only)")),providers:B(X(R().describe("List of providers to use").refine((N)=>J[N]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:B(R().describe("Referrer address (referral program)")),sellAmount:R().describe("Amount of asset to sell").refine((N)=>+N>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:R().describe("Asset to sell"),slippage:B(_().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:B(R().describe("Address to send asset from"))}).refine((N)=>N.sellAsset!==N.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),cL=$({metadata:K(),tokens:X($({identifier:R()}))}),JA=$({destinationAddress:R()}),XH=JA.extend({affiliateFees:X($({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()})}),ZA=$({channelId:R(),depositAddress:R()}),tA=JA.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()}),lL=DA.extend({depositAddress:R(),quote:DA,signature:R(),timestamp:R(),tx:SA()}),VA=$({buyAsset:R(),buyAssetAmount:R(),buyAssetAmountMaxSlippage:R(),deadline:R().optional(),depositAddress:R(),depositAmount:R(),depositAsset:R(),tx:SA()}),EH=$({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())}),QH=$({currentStage:R(),inboundConfirmation:_(),inboundObservation:_(),outboundDelay:_(),outboundObservation:_(),streamingSwap:_()}),xH=$({count:B(_()),interval:B(_()),quantity:B(_()),subSwapsMap:B(X(_()))}),wH=L.object({currentLegIndex:L.optional(L.number()),estimatedTimeToComplete:L.number(),estimates:L.optional(QH),providerDetails:L.optional(L.object({streamingDetails:L.optional(xH)}))}),bH=$({affiliate:B(NN),liquidity:B(NN),network:B(NN),protocol:B(NN),tax:B(NN)}),zH=$({affiliate:R(),bps:R(),isReferrer:K()}),JH=$({affiliate:B(R()),affiliateFees:B(X(zH)),broadcastedAt:B(_()),explorerUrl:B(R()),fees:B(bH),images:B($({chain:B(R()),from:B(R()),provider:B(R()),to:B(R())})),provider:B(L.enum(J)),providerAction:L.optional(L.enum(QA)),quoteId:B(R()),wallet:B(R())}),AN=L.object({block:L.number(),chainId:L.enum(nN),finalAddress:L.optional(L.string()),finalAsset:L.optional(NN),finalisedAt:L.number(),fromAddress:L.string(),fromAmount:L.string(),fromAsset:L.string(),hash:L.string(),meta:L.optional(JH),payload:L.optional(EH),status:L.enum(xA),toAddress:L.string(),toAmount:L.string(),toAsset:L.string(),trackingStatus:L.optional(L.enum(wA)),transient:L.optional(wH),type:L.enum(EA)}),WA=AN.extend({legs:L.array(AN)}),rL=AN.extend({legs:X(AN)}),iL=AN.extend({legs:X(AN)}),mN=X($({amount:R(),asset:R(),chain:R(),protocol:L.enum(J),type:L.enum(bN)})),pN=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")}),jA=$({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=X(KN([R(),_(),X(R()),$({from:R(),value:R()}).describe("Parameters to pass to the contract method")])),sL=$({approvalSpender:B(R().describe("Address of the spender to approve")),approvalToken:B(R().describe("Address of the token to approve spending of")),contractAddress:R().describe("Address of the contract to interact with"),contractMethod:R().describe("Name of the method to call"),contractParamNames:X(R().describe("Names of the parameters to pass to the contract method")),contractParams:ZH}),VH=$({typeUrl:R("/types.MsgDeposit"),value:$({coins:X($({amount:R(),asset:$({chain:R(),symbol:R(),synth:K(),ticker:R()})})),memo:R(),signer:R()})}),WH=$({typeUrl:R("/types.MsgSend"),value:$({amount:X($({amount:R(),denom:R()})),fromAddress:R(),toAddress:R()})}),jH=$({typeUrl:R(),value:WH.shape.value.or(VH.shape.value)}),vH=$({amount:X($({amount:R(),denom:R()})),gas:R()}),qA=$({accountNumber:_(),chainId:L.enum(nN),fee:vH,memo:R(),msgs:X(jH),sequence:_()}),qH=L.array(L.object({calldata:L.array(L.string()),contractAddress:L.string(),entrypoint:L.string()})),kA=L.array(L.object({address:L.string().describe("Destination address in friendly format"),amount:L.string().describe("Amount in nanotons"),payload:L.string().optional().describe("Base64 BOC of body cell"),stateInit:L.string().optional().describe("Base64 BOC of state init")})),kH=$({affiliate:R().describe("Affiliate address").optional(),affiliateFee:_().describe("Affiliate fee").optional(),buyAsset:R().describe("Asset to buy"),destinationAddress:R().describe("Destination address"),estimatedTime:pN.optional(),provider:L.enum(J),sellAsset:R().describe("Asset to sell"),slipPercentage:_().describe("Slippage as a percentage"),sourceAddress:R().describe("Source address")}),eL=kH.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),KH=$({asset:R().describe("Asset name"),image:R().describe("Asset image"),price:_().describe("Price in USD")}),mH=XH,KA=$({assets:B(X(KH)),maxStreamingQuantity:_().optional(),referrer:R().optional(),streamingInterval:_().optional(),tags:X(L.enum(XA))}),mA=KA.extend({affiliate:B(R()),affiliateFee:B(R()),approvalAddress:B(R().describe("Approval address for swap")),chainflip:mH.optional(),garden:tA.optional(),near:tA.optional(),priceImpact:B(_().describe("Price impact")),referrer:B(R()),txType:B(L.enum(QN))}),pA=X($({code:L.enum(wN),display:R(),tooltip:R().optional()})),pH=$({buyAmount:R().describe("Buy amount"),buyAmountMaxSlippage:R().describe("Buy amount max slippage"),buyAsset:R().describe("Asset to buy"),fees:B(mN),provider:L.enum(J),sellAmount:R().describe("Sell amount"),sellAsset:R().describe("Asset to sell")}),yH=$({buyAsset:R().describe("Asset to buy"),destinationAddress:B(R().describe("Destination address")),estimatedTime:B(pN),expectedBuyAmount:R().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:R().describe("Expected Buy amount max slippage"),expiration:B(R().describe("Expiration")),fees:mN,inboundAddress:B(R().describe("Inbound address")),legs:X(pH),memo:B(R().describe("Memo")),meta:mA,providers:X(L.enum(J)),routeId:R().describe("Route ID"),sellAmount:R().describe("Sell amount"),sellAsset:R().describe("Asset to sell"),sourceAddress:B(R().describe("Source address")),targetAddress:B(R().describe("Target address")),totalSlippageBps:_().describe("Total slippage in bps"),tx:B(KN([jA,qA,vA,qH,kA,R()])),txType:B(L.enum(QN)),warnings:pA}),yA=$({error:B(R().describe("Error message")),providerErrors:B(X($({errorCode:B(L.enum(LN)),message:B(R()),provider:L.enum(J).optional()}))),quoteId:R().describe("Quote ID"),routes:X(yH)}),oA=L.object({chainId:L.enum(nN),createdAt:L.date(),id:L.number(),unit:L.string(),value:L.string()}),oH=L.array(oA),fA=L.union([oA,oH]),aL=X($({chain:L.enum(EN),decimal:_(),identifier:R(),symbol:R(),ticker:R(),value:R()})),NR=L.union([L.object({amount:L.string(),spender:L.string(),tokenIdentifier:L.string(),userWalletAddress:L.string()}),L.object({amount:L.string(),chainId:L.enum(nN),spender:L.string(),tokenContractAddress:L.string(),userWalletAddress:L.string()}),L.object({routeId:L.string()})]),AR=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()}),fH=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:mN,provider:L.enum(J),sellAmount:L.string().describe("Sell amount"),sellAsset:L.string().describe("Asset to sell")}),CA=YA.extend({estimatedTime:L.optional(pN),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:pA}).omit({provider:!0}),CH=L.object({method:L.string(),payload:L.optional(L.unknown()),url:L.string()}),hH=CA.extend({meta:KA,nextActions:L.optional(L.array(CH))}),TR=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(L.object({errorCode:L.optional(L.enum(LN)),message:L.optional(L.string()),provider:L.enum(J).optional()}))),quoteId:L.string().describe("Quote ID"),routes:L.array(hH)}),HR=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')")}),dH=L.object({chain:L.enum(EN).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")}),PR=L.object({buyAssets:L.array(dH).describe("List of assets that can be swapped to"),sellAsset:L.string().describe("The input sell asset identifier")}),hA=CA.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:mA,sourceAddress:L.string().describe("Source address"),targetAddress:L.optional(L.string().describe("Target address")),tx:B(KN([jA,qA,vA,kA,R()])),txType:L.optional(L.enum(QN))}),cH=L.object({data:L.optional(L.record(L.string(),L.string().optional())),errorCode:L.enum(LN),message:L.string().optional(),provider:L.enum(J).optional()}),LR=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(cH)),quoteId:L.string().describe("Quote ID"),routes:L.array(hA)}),dA=hA.extend({approvalTx:fH.optional().describe("Optional approval transaction if ERC-20 approval is required before swap"),swapId:L.string().describe("The unique swap ID for tracking")});var W=G.extend({dynamicHeader:async()=>{let N=E.get("widgetId"),A=E.get("widgetKey");if(N&&A&&typeof window<"u"){let H=Math.floor(Date.now()/1000),P=window.location.origin,F=await gA(A,N,P,H);return{Origin:P,"X-Signature":F,"X-Timestamp":H.toString(),"x-widget-id":N}}let{swapKit:T}=E.get("apiKeys");return T?{"x-api-key":T}:{}}});async function iH(N){let A=await W.post(V("/track"),{json:N});try{let T=WA.safeParse(A);if(!T.success)throw new g("api_v2_invalid_response",T.error);return T.data}catch(T){return A}}async function sH(N){let{getQuote:A}=E.get("endpoints");if(A)return A(N);let H=E.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",P=await W.post(V(H),{json:N});if(P.error)throw new g("api_v2_server_error",{message:P.error});try{let F=yA.safeParse(P);if(!F.success)throw new g("api_v2_invalid_response",F.error);return F.data}catch{return P}}async function eH(N){let{getRouteWithTx:A}=E.get("endpoints");if(A)return A(N);let H=E.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",P=await W.post(V(H),{json:N});try{let F=dA.safeParse(P);if(!F.success)throw new g("api_v2_invalid_response",F.error);return F.data}catch(F){return console.error(new g("api_v2_invalid_response",F)),P}}async function aH({chain:N,address:A,scamFilter:T=!0}){let{getBalance:H}=E.get("endpoints");if(H)return H({address:A,chain:N});let P=V(`/balance?chain=${N}&address=${A}`),F=await W.get(P),I=Array.isArray(F)?F:[];return T?IP(I):I}function NP(N){let A=rH(N).with({routeId:BN.string,spender:BN.string},({routeId:T,spender:H})=>V(`/approve?routeId=${T}&sourceAddress=${H}`)).with({assetValue:BN.instanceOf(v),spender:BN.string,userWallet:BN.string},({spender:T,userWallet:H,assetValue:P})=>V(`/approve?tokenIdentifier=${P.toString()}&userWalletAddress=${H}&spender=${T}&amount=${P.getValue("string")}`)).exhaustive();return W.get(A)}function AP(){let N=V("/providers");return W.get(N)}function TP(N){let A=V(`/tokens?provider=${N}`);return W.get(A)}async function HP(N){let A=V("/price"),T=await W.post(A,{json:N});try{let H=zA.safeParse(T);if(!H.success)throw new g("api_v2_invalid_response",H.error);return H.data}catch(H){throw new g("api_v2_invalid_response",H)}}async function PP(){let N=V("/gas"),A=await W.get(N);try{let T=fA.safeParse(A);if(!T.success)throw new g("api_v2_invalid_response",T.error);return Array.isArray(T)?T:[T]}catch(T){throw new g("api_v2_invalid_response",T)}}async function LP(N){let{destinationAddress:A}=N;if(!A)throw new g("chainflip_broker_invalid_params");let T=E.get("integrations").chainflip?.brokerUrl||V("/chainflip/broker/channel"),H=await W.post(T,{json:N});try{let P=ZA.safeParse(H);if(!P.success)throw new g("api_v2_invalid_response",P.error);return P.data}catch(P){throw new g("api_v2_invalid_response",P)}}async function RP(N){let{destinationAddress:A}=N;if(!A)throw new g("chainflip_broker_invalid_params");let T=V("/near/channel"),H=await W.post(T,{json:N});try{let P=VA.safeParse(H);if(!P.success)throw new g("api_v2_invalid_response",P.error);return P.data}catch(P){throw new g("api_v2_invalid_response",P)}}function V(N){let{isDev:A,apiUrl:T,devApiUrl:H}=E.get("envs");return`${A?H:T}${N}`}function uP(N){let[A,T]=N.split(".");if(!lH.includes(A))return!0;let H=T.split("-"),P=H.length===1?void 0:H[H.length-1];return gN({chain:A,symbol:T})||!!P}var FP=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi");function IP(N){return N.filter((A)=>{return!FP.test(A.identifier)&&uP(A.identifier)})}async function nP(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 W.get(H);if(!Array.isArray(P))return{buyAssets:[],sellAsset:N.sellAsset};let F=[];for(let I of P)try{let O=v.from({asset:I});F.push({chain:O.chain,identifier:O.toString(),providers:[],symbol:O.symbol,ticker:O.ticker})}catch{}return{buyAssets:F,sellAsset:N.sellAsset}}var oN={};dN(oN,{getThorchainQueue:()=>GP,getTcyStakers:()=>SP,getTcyStaker:()=>UP,getTcyClaimers:()=>EP,getTcyClaimer:()=>XP,getTNSPreferredAsset:()=>tP,getTHORNodeTNSDetails:()=>cA,getRunePoolProviderInfo:()=>YP,getRunePoolInfo:()=>DP,getNodes:()=>MP,getMimirInfo:()=>_P,getLastBlock:()=>$P,getInboundAddresses:()=>gP});import{match as BP}from"ts-pattern";function q(N){let{isStagenet:A}=E.get("envs"),T=E.get("thornodeUrls");return`${BP({isStagenet:A,type:N}).with({type:"mayachain"},({isStagenet:P})=>P?T.MAYA_STAGENET:T.MAYA).otherwise(({isStagenet:P})=>P?T.THOR_STAGENET:T.THOR)}/${N??"thorchain"}`}function OP(N){let A=N==="mayachain"?"mayaname":"thorname";return`${q(N)}/${A}`}function $P(N="thorchain"){return G.get(`${q(N)}/lastblock`)}function GP(N){return G.get(`${q(N)}/queue`)}function MP(N){return G.get(`${q(N)}/nodes`)}function _P(N){return G.get(`${q(N)}/mimir`)}function gP(N){return G.get(`${q(N)}/inbound_addresses`)}async function cA({type:N,name:A}){try{return await G.get(`${OP(N)}/${A}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:A,owner:"",preferred_asset:""}}}async function tP({type:N,tns:A}){let T=await cA({name:A,type:N});if(!T.preferred_asset||T.preferred_asset===".")return;return v.from({asset:T.preferred_asset,asyncTokenLookup:!0})}function DP(N){return G.get(`${q(N)}/runepool`)}function YP({type:N,thorAddress:A}){return G.get(`${q(N)}/rune_provider/${A}`)}function UP({type:N,address:A}){return G.get(`${q(N)}/tcy_staker/${A}`)}function SP(N){return G.get(`${q(N)}/tcy_stakers`)}function XP({type:N,address:A}){return G.get(`${q(N)}/tcy_claimer/${A}`)}function EP(N){return G.get(`${q(N)}/tcy_claimers`)}var UR={...yN,mayachainMidgard:_A,thorchainMidgard:MA,thornode:oN};
5
5
  export{wP as a,LN as b,wN as c,J as d,bN as e,NT as f,AT as g,TT as h,zN as i,HT as j,Z as k,E as l,g as m,G as n,lP as o,rP as p,iP as q,sP as r,c as s,VN as t,ET as u,l as v,PL as w,nL as x,LA as y,gN as z,tN as A,WN as B,f as C,uN as D,BL as E,OL as F,uA as G,_L as H,h as I,p as J,v as K,bL as L,SN as M,gA as N,XA as O,QN as P,EA as Q,QA as R,xA as S,wA as T,yL as U,oL as V,fL as W,CL as X,NN as Y,bA as Z,hL as _,zA as $,dL as aa,cL as ba,JA as ca,XH as da,ZA as ea,tA as fa,lL as ga,VA as ha,WA as ia,rL as ja,iL as ka,mN as la,pN as ma,jA as na,vA as oa,ZH as pa,sL as qa,qA as ra,qH as sa,kA as ta,kH as ua,eL as va,KH as wa,mH as xa,KA as ya,mA as za,pA as Aa,yH as Ba,yA as Ca,oA as Da,fA as Ea,NR as Fa,AR as Ga,fH as Ha,TR as Ia,HR as Ja,dH as Ka,PR as La,hA as Ma,cH as Na,LR as Oa,dA as Pa,UR as Qa};
@@ -1,4 +1,4 @@
1
1
  var jP={};w(jP,{TxnType:()=>mN,TxnStatus:()=>yN,TronTransactionSchema:()=>iN,TransactionSchema:()=>pH,TransactionDTOSchema:()=>yH,TrackingStatus:()=>oN,TrackingRequestSchema:()=>xH,TrackingRequestQuerySchema:()=>wH,TrackerResponseSchema:()=>lN,TokenSchema:()=>QH,TokenDetailsMetadataSchema:()=>zH,TONTransactionSchema:()=>eN,SwapToResponseSchema:()=>TP,SwapToRequestSchema:()=>AP,SwapToAssetSchema:()=>hA,SwapRouteV2ResponseSchema:()=>RA,SwapKitApi:()=>WP,StarknetTransactionSchema:()=>KA,RouteQuoteWarningSchema:()=>AA,RouteQuoteTxType:()=>nN,RouteQuoteProviderErrorSchema:()=>dA,RouteQuoteMetadataV2Schema:()=>NA,RouteQuoteMetadataSchema:()=>aN,RouteQuoteMetadataAssetSchema:()=>pA,RouteLegWithoutAddressesSchema:()=>cH,RouteLegSchema:()=>mA,QuoteV3ResponseSchema:()=>NP,QuoteV2ResponseSchema:()=>HP,QuoteRouteV2Response:()=>LA,QuoteResponseSchema:()=>TA,QuoteResponseRouteItem:()=>oA,QuoteRequestSchema:()=>JH,ProviderAction:()=>pN,PriorityLabel:()=>KN,PriceResponseSchema:()=>CN,PriceRequestSchema:()=>ZH,NearSwapResponseSchema:()=>cN,NearDepositChannelResultSchema:()=>VH,NearDepositChannelParamsSchema:()=>kN,GasSchema:()=>HA,GasResponseSchema:()=>PA,FeesSchema:()=>QN,EstimatedTimeSchema:()=>xN,EVMTransactionSchema:()=>rN,EVMTransactionDetailsSchema:()=>oH,EVMTransactionDetailsParamsSchema:()=>kA,DepositChannelResponseSchema:()=>dN,DepositChannelParamsSchema:()=>hN,CosmosTransactionSchema:()=>sN,CoinGeckoMetadataSchema:()=>fN,ChainflipMetadataSchema:()=>yA,BrokerDepositChannelParamsSchema:()=>qA,AssetValueSchema:()=>d,ApproveResponseSchema:()=>sH,ApproveRequestParams:()=>iH,ApprovalTransactionSchema:()=>fA,ApiV2ErrorSchema:()=>bH});module.exports=VP(jP);var h=require("@swapkit/types");var lT={};w(lT,{getMinAmountByChain:()=>yT,AssetValue:()=>z});var G=require("@swapkit/types"),WN=require("ethers"),EN=require("ts-pattern");var ZT={};w(ZT,{parseSymbolForAddress:()=>i,isGasAsset:()=>LN,getTokenLogoURI:()=>zT,getCommonAssetInfo:()=>RN,getAssetType:()=>UN,findAssetBy:()=>JT,fetchTokenInfo:()=>JN,assetFromString:()=>K,CommonAssetStrings:()=>UT});var I=require("@swapkit/types"),r=require("ts-pattern");var nT={};w(nT,{RequestClient:()=>B});var AT={};w(AT,{swapKitConfigStore:()=>b,SKConfig:()=>U});var S=require("@swapkit/types"),_A=require("zustand/vanilla");var eA={};w(eA,{WarningCodeEnum:()=>MN,WalletOption:()=>gN,ProviderName:()=>x,NetworkDerivationPath:()=>sA,MemoType:()=>GA,LedgerErrorCode:()=>MA,FeeTypeEnum:()=>_N,FeeOption:()=>OA,ErrorCode:()=>l,ApproveMode:()=>$A});var GN=require("@swapkit/types"),sA=GN.AllChains.reduce((A,T)=>{return A[T]=GN.getChainConfig(T).networkDerivationPath,A},{});var l;((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"})(l||={});var MN;((H)=>{H.highSlippage="highSlippage";H.highPriceImpact="highPriceImpact"})(MN||={});var x;((Y)=>{Y.CHAINFLIP="CHAINFLIP";Y.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";Y.JUPITER="JUPITER";Y.MAYACHAIN="MAYACHAIN";Y.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";Y.ONEINCH="ONEINCH";Y.PANCAKESWAP="PANCAKESWAP";Y.SUSHISWAP_V2="SUSHISWAP_V2";Y.THORCHAIN="THORCHAIN";Y.THORCHAIN_STREAMING="THORCHAIN_STREAMING";Y.TRADERJOE_V2="TRADERJOE_V2";Y.UNISWAP_V2="UNISWAP_V2";Y.UNISWAP_V3="UNISWAP_V3";Y.NEAR="NEAR";Y.GARDEN="GARDEN";Y.OKX="OKX";Y.HARBOR="HARBOR";Y.FLASHNET="FLASHNET"})(x||={});var _N;((O)=>{O.LIQUIDITY="liquidity";O.NETWORK="network";O.INBOUND="inbound";O.OUTBOUND="outbound";O.AFFILIATE="affiliate";O.TAX="tax";O.PRIORITY="priority";O.SERVICE="service"})(_N||={});var OA;((P)=>{P.Average="average";P.Fast="fast";P.Fastest="fastest"})(OA||={});var $A;((H)=>{H.Approve="approve";H.CheckOnly="checkOnly"})($A||={});var GA;((M)=>{M.NAME_REGISTER="~";M.BOND="BOND";M.DEPOSIT="+";M.LEAVE="LEAVE";M.UNBOND="UNBOND";M.WITHDRAW="-";M.RUNEPOOL_DEPOSIT="POOL+";M.RUNEPOOL_WITHDRAW="POOL-";M.CLAIM_TCY="tcy";M.STAKE_TCY="tcy+";M.UNSTAKE_TCY="tcy-"})(GA||={});var gN;((_)=>{_.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"})(gN||={});var MA;((P)=>{P[P.NoError=36864]="NoError";P[P.LockedDevice=21781]="LockedDevice";P[P.TC_NotFound=65535]="TC_NotFound"})(MA||={});var aA=S.AllChains.reduce((A,T)=>{if(!A.THOR_STAGENET)A[S.StagenetChain.Maya]=S.StagenetMAYAConfig.rpcUrls,A[S.StagenetChain.THORChain]=S.StagenetTHORConfig.rpcUrls;return A[T]=S.getChainConfig(T).rpcUrls,A},{}),NT={[S.Chain.THORChain]:S.THORConfig.nodeUrl,[S.Chain.Maya]:S.MAYAConfig.nodeUrl,[S.StagenetChain.THORChain]:S.StagenetTHORConfig.nodeUrl,[S.StagenetChain.Maya]:S.StagenetMAYAConfig.nodeUrl},gA={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:S.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:aA,thornodeUrls:NT,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(gN),widgetId:"",widgetKey:""},b=_A.createStore((A)=>({...gA,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},thornodeUrls:{...H.thornodeUrls,...T?.thornodeUrls},v3SwapFlow:{...H.v3SwapFlow,...T?.v3SwapFlow},wallets:H.wallets.concat(T?.wallets||[]),widgetId:T?.widgetId||H.widgetId,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}})),setThornodeUrl:(T,H)=>A((P)=>({thornodeUrls:{...P.thornodeUrls,[T]:H}})),setWidgetId:(T)=>A({widgetId:T}),setWidgetKey:(T)=>A({widgetKey:T})})),U={get:(A)=>b.getState()[A],getState:b.getState,reinitialize:()=>b.setState(gA),set:(A)=>b.getState().setConfig(A),setApiKey:(A,T)=>b.getState().setApiKey(A,T),setEndpoint:(A,T)=>b.getState().setEndpoint(A,T),setEnv:(A,T)=>b.getState().setEnv(A,T),setFeeMultipliers:(A)=>b.getState().setFeeMultipliers(A),setIntegrationConfig:(A,T)=>b.getState().setIntegrationConfig(A,T),setRequestOptions:(A)=>b.getState().setRequestOptions(A),setRpcUrl:(A,T)=>b.getState().setRpcUrl(A,T),setThornodeUrl:(A,T)=>b.getState().setThornodeUrl(A,T),setWidgetId:(A)=>b.getState().setWidgetId(A),setWidgetKey:(A)=>b.getState().setWidgetKey(A)};var HT={};w(HT,{SwapKitError:()=>$});var TT={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 bN(A){return JSON.stringify(A,(T,H)=>typeof H==="bigint"?H.toString():H)}class $ extends Error{static ErrorCode=TT;errorKey;info;constructor(A,T){let H=typeof A==="string",P=H?A:A.errorKey,L=H?void 0:A.info,u=`${P}${L?`: ${bN(L)}`:""}`;super(u);if(Object.setPrototypeOf(this,$.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})`:""}`:bN(T);console.error(`SwapKitError [${P}]: ${F}`)}else if(L)console.error(`SwapKitError [${P}]: ${bN(L)}`)}}var PT=(A)=>new Promise((T)=>setTimeout(T,A)),LT=(A,{baseDelay:T,backoffMultiplier:H,maxDelay:P})=>Math.min(T*H**A,P);function RT(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 uT=async(A,T)=>{let H=await fetch(A,T),P;try{P=await H.json()}catch{if(!H.ok)throw new $({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 $({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 $({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 tN(A,T={}){return async function(P,L={}){let{searchParams:u,json:F,body:n,headers:O,dynamicHeader:g,retry:X,timeoutMs:M,abortController:V,onError:D,onSuccess:j,responseHandler:E,...Q}={...T,...L},HN=U.get("requestOptions"),Y={...HN.retry,...X},BN=!!F||P.endsWith(".json"),ON=IT(P,u),IA=g?await g():{},PN=FT(BN,{...O,...IA}),c=BN?JSON.stringify(F):n,wN;for(let $N=0;$N<=Y.maxRetries;$N++){let nA=V||new AbortController,BA=setTimeout(()=>nA.abort(),M||HN.timeoutMs);try{let q=await uT(ON,{...Q,body:c,headers:PN,method:A,signal:nA.signal});return clearTimeout(BA),j?.(q)||E?.(q)||q}catch(q){clearTimeout(BA),wN=q;let iA=q?.cause?.status;if($N>=Y.maxRetries||!RT(q,iA))return D?D(q):Promise.reject(q);await PT(LT($N,Y))}}return D?D(wN):Promise.reject(wN)}}function FT(A,T){return{...T,...A&&{"Content-Type":"application/json"}}}function IT(A,T){let H=new URL(A);if(T)H.search=new URLSearchParams(T).toString();return H.toString()}var B={extend:(A)=>({extend:(T)=>B.extend({...A,...T}),get:tN("GET",A),post:tN("POST",A)}),get:tN("GET"),post:tN("POST")};var YT={};w(YT,{initializeRPCUrlsWithFallback:()=>DT,getRPCUrlSync:()=>YA,getRPCUrl:()=>f,_rpcCache:()=>YN});var t=require("@swapkit/types"),zN=require("ts-pattern");var MT={};w(MT,{wrapWithThrow:()=>$T,warnOnce:()=>o,getTHORNameCost:()=>BT,getMAYANameCost:()=>OT,getChainIdentifier:()=>GT});var DN=require("@swapkit/types");function BT(A){if(A<0)throw new $({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:A}});return 10+A}function OT(A){if(A<0)throw new $({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:A}});return Math.round((10+A*1.0512)*10000000000)/10000000000}function $T(A,T){try{return A()}catch(H){if(T)throw new $(T,H);return}}function GT(A){switch(A){case DN.Chain.THORChain:return`${A}.RUNE`;case DN.Chain.Cosmos:return`${A}.ATOM`;case DN.Chain.BinanceSmartChain:return`${A}`;default:return`${A}.${A}`}}var tA=new Set;function o({condition:A,id:T,warning:H}){if(A){if(tA.has(T))return;console.warn(H),tA.add(T)}}function _T(A){return zN.match(A).with(...t.EVMChains,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...t.UTXOChains,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...t.CosmosChains,...t.StagenetChains,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(t.Chain.Polkadot,t.Chain.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(t.Chain.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(t.Chain.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(t.Chain.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(t.Chain.Aptos,t.Chain.Tron,t.Chain.Radix,t.Chain.Stellar,()=>"").with(t.Chain.HyperCore,()=>({type:"meta"})).with(t.Chain.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(t.Chain.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(t.Chain.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new $("helpers_chain_not_supported",{chain:A})})}function gT(A){return zN.match(A).with(t.Chain.Aptos,()=>"/-/healthy").with(t.Chain.HyperCore,()=>"/info").with(t.Chain.Radix,()=>"/status/network-configuration").with(t.Chain.Stellar,()=>"").with(t.Chain.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function DA(A,T){try{let H=T.startsWith("wss")?T.replace("wss","https"):T;return(await fetch(`${H}${gT(A)}`,{body:JSON.stringify(_T(A)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var YN=new Map,tT=120000;function YA(A){let[T=""]=U.get("rpcUrls")[A];if(!T)throw o({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 $("helpers_chain_no_public_or_set_rpc_url",{chain:A});let H=YN.get(A);if(H&&Date.now()-H.timestamp<tT)return H.url;return YN.set(A,{timestamp:Date.now(),url:T}),T}async function f(A){let T=YA(A),[,...H]=U.get("rpcUrls")[A];if(await DA(A,T))return T;for(let L of H)if(await DA(A,L))return YN.set(A,{timestamp:Date.now(),url:L}),L;throw new $("helpers_chain_rpc_connection_failed",{chain:A,fallbackUrls:H,primaryRpcUrl:T})}function DT(A){o({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 UT=[`${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 ST(A){let{baseDecimal:T}=I.getChainConfig(I.Chain.Radix);try{let H=await f(I.Chain.Radix),{manager:P}=await B.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 f(I.Chain.Radix);return(await B.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 EA({chain:A,address:T,methodHex:H,id:P}){let L=await f(A);return B.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 QT(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 xT({chain:A,address:T}){let{baseDecimal:H}=I.getChainConfig(A),P=T.toLowerCase();if(T===""||!P.startsWith("0x"))return H;let L=await EA({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 QT(L.result,H)}async function wT({chain:A,address:T}){let H=T.toLowerCase();if(H===""||!H.startsWith("0x"))return;let P=await EA({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 UA({rpcUrl:A,contractAddress:T,functionSelector:H}){return(await B.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 SA(A){let T=A.match(/.{2}/g)?.map((H)=>Number.parseInt(H,16))??[];return new TextDecoder().decode(new Uint8Array(T))}function bT(A){return r.match(A).with(void 0,()=>{return}).when((T)=>T.length>=128,(T)=>{let H=Number.parseInt(T.slice(64,128),16);return SA(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 SA(H);return}).otherwise(()=>{return})}function JN({chain:A,address:T}){let{baseDecimal:H}=I.getChainConfig(A),P={decimals:H,ticker:void 0};return r.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([wT({address:T,chain:A}),xT({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 f(I.Chain.Tron),[u,F]=await Promise.all([UA({contractAddress:T,functionSelector:"symbol()",rpcUrl:L}),UA({contractAddress:T,functionSelector:"decimals()",rpcUrl:L})]),n=bT(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 f(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"}),O=JSON.parse(Buffer.from(n.result).toString());return{decimals:O?.decimals||H,ticker:O?.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),ST(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 LN({chain:A,symbol:T}){return r.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}`===RN(A).identifier).otherwise(()=>T===A)}var RN=(A)=>{let{baseDecimal:T}=I.getChainConfig(A);return r.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 UN({chain:A,symbol:T}){if(T.includes("/"))return"Synth";if(T.includes("~"))return"Trade";return r.match(A).with(I.Chain.Radix,()=>T===I.Chain.Radix||`${A}.${T}`===RN(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 K=(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 i(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}=K(u.identifier);if(F!==A.chain)continue;let{address:O}=i(n,F);if(O?.toLowerCase()===L)return u.identifier}return}var WT={};w(WT,{validateTNS:()=>VT,validateIdentifier:()=>ZN});var QA=["TERRA",...U.get("chains")];function ZN(A=""){let T=A.toUpperCase(),[H]=T.split(".");if(QA.includes(H))return!0;let[P]=T.split("/");if(QA.includes(P))return!0;throw new $({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={};w(kT,{formatBigIntToSafeValue:()=>m,BigIntArithmetics:()=>k});var FN=require("ts-pattern"),s=8,jT=10;function m({value:A,bigIntDecimal:T=s,decimal:H=s}){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 g=Number.parseInt(n[T-1]||"0",10);n=`${n.substring(0,T-1)}${g+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:m({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=VN(A),H=typeof A==="object";this.decimal=H?A.decimal:void 0,this.decimalMultiplier=H&&"decimalMultiplier"in A?A.decimalMultiplier:C(Math.max(xA(SN(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=uN(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 FN.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||s),P=qT(this.bigIntValue,H);return FN.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=VN(A),P=SN(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),O=P.length-F.length;return`0.${n.padStart(O+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 g=BigInt(L.slice(0,A).padEnd(A,"0"))+1n,X=10n**BigInt(A);if(g>=X)return`${F}${BigInt(P)+1n}.${"0".repeat(A)}`;return`${F}${P}.${g.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",[O="0",g=""]=F.split("."),X=O.replace(/\B(?=(\d{3})+(?!\d))/g,L),M=g&&Number.parseInt(g,10)>0,V=M?`${X}${P}${g}`:X,j=V.length<100&&u&&M?V.replace(/\.?0*$/,""):V;return n?`${j}${A}`:`${A}${j}`}formatBigIntToSafeValue(A,T){let H=T||this.decimal||s,P=Math.max(H,uN(this.decimalMultiplier));return m({bigIntDecimal:H,decimal:P,value:A})}#A(A,...T){let H=this.#T(this,...T),P=uN(this.decimalMultiplier),u=Math.max(H,P)+jT,F=C(u),n=T.reduce((g,X)=>{let M=this.getBigIntValue(X,u);return FN.match(A).with("add",()=>g+M).with("sub",()=>g-M).with("mul",()=>g*M/F).with("div",()=>{if(M===0n)throw RangeError("Division by zero");return g*F/M}).otherwise(()=>g)},this.bigIntValue*F/this.decimalMultiplier),O=m({bigIntDecimal:u,decimal:u,value:n});return new this.constructor({decimal:this.decimal,decimalMultiplier:C(u),identifier:this.toString(),value:O})}#N(A,...T){let H=this.#T(this,...T),P=this.getBigIntValue(T[0]||"0",H),L=this.getBigIntValue(this,H);return FN.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=SN(A)||"0";this.bigIntValue=this.#H(T)}#T(...A){let T=A.map((H)=>{return typeof H==="object"?H.decimal||uN(H.decimalMultiplier):xA(SN(H))}).filter(Boolean);return Math.max(...T,s)}#H(A,T){let H=T?C(T):this.decimalMultiplier,P=uN(H),[L="",u=""]=A.split(".");return BigInt(`${L}${u.padEnd(P,"0")}`)}}var vT=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function SN(A){let H=`${typeof A==="number"?vT.format(A):VN(A)}`.replaceAll(",",".").split(".");return H.length>1?`${H.slice(0,-1).join("")}.${H.at(-1)}`:H[0]||"0"}function xA(A){let T=A.split(".")[1]?.length||0;return Math.max(T,s)}function VN(A){return typeof A==="object"?"getValue"in A?A.getValue("string"):A.value:A}function qT(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 uN(A){return Math.log10(Number.parseFloat(A.toString()))}var p=[G.Chain.HyperCore,G.Chain.Near,G.Chain.Ripple,G.Chain.Solana,G.Chain.Sui,G.Chain.Ton,G.Chain.Tron],vN=[G.Chain.THORChain,G.Chain.Maya],e=new Map,XN=new Map,a=new Map,KT=3600000;function mT(A){let T=a.get(A);if(T?.timestamp&&Date.now()-T.timestamp>KT){a.delete(A);return}return T}function pT(A,T){if(a.size>1000){let H=a.keys().next().value;if(H)a.delete(H)}a.set(A,{...T,timestamp:Date.now()})}class z 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=wA(u||`${P}.${L}`);this.type=UN(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 e.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 $({errorKey:"helpers_invalid_asset_url",info:{urlAsset:A}});let P=A.slice(0,H),L=A.slice(H+1),u=EN.match({chain:P,rest:L}).when(({rest:F})=>F.includes(".."),({chain:F,rest:n})=>`${F}.${n.replace(/\.\./g,"~")}`).when(({chain:F,rest:n})=>vN.includes(F)&&n.includes("."),({chain:F,rest:n})=>`${F}.${n.replace(/\./g,"/")}`).otherwise(({chain:F,rest:n})=>`${F}.${n.replace(/__/g,".")}`);return z.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="address"in P&&"chain"in P,F=hT(P);if(F===null&&H&&u){let{chain:PN,address:c}=P;return fT({address:c,chain:PN,fromBaseDecimal:T,parsedValue:L})}let n=u&&!F?`${P.chain}.UNKNOWN-${P.address}`:F,{identifier:O,decimal:g}=RN(n),{chain:X,isSynthetic:M,isTradeAsset:V,address:D}=wA(O),{baseDecimal:j}=G.getChainConfig(X),E=e.get(p.includes(X)?O:O.toUpperCase());if(!E&&H&&!M&&!V)return(async()=>{let{ticker:PN}=K(O),c=await bA({address:D,chain:X,ticker:PN});return jN({decimal:c.decimals,identifier:c.identifier,value:T?NN(BigInt(L),T):L})})();let Q=E?.decimal||g;o({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 ${j} decimal as fallback).
2
2
  This can result in incorrect calculations and mess with amount sent on transactions.
3
3
  You can load static assets by installing @swapkit/tokens package and calling AssetValue.loadStaticAssets()
4
- or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`});let{decimal:HN,identifier:Y,tax:BN}=E||{decimal:Q||j,identifier:O},ON=T?NN(BigInt(L),T):NN(L,HN);return M||V?oT(Y,ON):jN({decimal:HN,identifier:Y,tax:BN,value:ON})}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}=K(u),{address:O}=i(n,F),{baseDecimal:g}=G.getChainConfig(F),X=p.includes(F)?u:u.toUpperCase(),M="decimals"in L&&L.decimals!==void 0?L.decimals:g,V="logoURI"in L&&L.logoURI?L.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${u.toLowerCase()}.png`,D={decimal:M,identifier:u,logoURI:V,tax:"tax"in L?L.tax:void 0};if(e.set(X,D),O){let j=p.includes(F)?`${F}:${O}`:`${F}:${O.toUpperCase()}`;XN.set(j,u)}}return!0}static setStaticAssets(A){e.clear(),XN.clear();for(let[T,H]of A.entries()){let{identifier:P}=H,{chain:L,symbol:u}=K(P),{address:F}=i(u,L),{baseDecimal:n}=G.getChainConfig(L),O=H.chain??L,g=H.address??F,X=p.includes(O)?P:P.toUpperCase(),M=H.decimals??H.decimal??n,V=H.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${P.toLowerCase()}.png`,D={decimal:M,identifier:X,logoURI:V,tax:H.tax};if(e.set(X,D),g){let j=p.includes(O)?`${O}:${g}`:`${O}:${g.toUpperCase()}`;XN.set(j,P)}}return!0}static get staticAssets(){return e}}function yT(A){let T=z.from({chain:A});return EN.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 bA({chain:A,address:T,ticker:H}){let L=p.includes(A)?`${A}:${T||H}`:`${A}:${T||H}`.toUpperCase(),u=mT(L);if(u)return u;if(!T){let{baseDecimal:O}=G.getChainConfig(A);return{decimals:O,identifier:`${A}.${H||"UNKNOWN"}`}}let F=await JN({address:T,chain:A}),n=`${A}.${F.ticker||H||"UNKNOWN"}-${T}`;return o({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&&pT(L,{decimals:F.decimals,identifier:n}),{decimals:F.decimals,identifier:n}}function jN({identifier:A,decimal:T,value:H,tax:P}){return ZN(A),new z({decimal:T,identifier:A,tax:P,value:NN(H,T)})}function oT(A,T=0){let H=A.includes(".")?A.split(".")?.[0]?.toUpperCase():void 0,P=H?vN.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 $({errorKey:"helpers_invalid_asset_identifier",info:{identifier:A}});return new z({decimal:8,identifier:`${H||G.Chain.THORChain}.${u}${L}${F}`,value:NN(T,8)})}async function fT({address:A,chain:T,fromBaseDecimal:H,parsedValue:P}){let{decimals:L,identifier:u}=await bA({address:A,chain:T}),F=H?NN(BigInt(P),H):P;return jN({decimal:L,identifier:u,value:F})}function NN(A,T){return typeof A==="bigint"?m({bigIntDecimal:T,decimal:T,value:A}):A}function CT(A){let T=EN.match(A).when((H)=>("chain"in H)&&H.chain!==void 0,({chain:H})=>H).otherwise((H)=>{let P=K(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 $({errorKey:"helpers_invalid_asset_identifier",info:{identifier:H,message:`Unsupported chain "${T}" - use the AssetValue constructor directly`}})}}function hT(A){if(CT(A),"chain"in A){let{chain:L,address:u}=A;if(u){let F=p.includes(L)?`${L}:${u}`:`${L}:${u.toUpperCase()}`,n=XN.get(F);if(n)return n;return null}return L}let{chain:T,symbol:H}=K(A.asset);return UN({chain:T,symbol:H})==="Native"?T:A.asset}function dT(A,T,H){let P=A.split("."),L=P[0]?.toUpperCase(),u=vN.includes(L),F=H?"~":"/",[n,O=""]=u?P.slice(1).join(".").split(F):A.split(F);if(!(n&&O))throw new $({errorKey:"helpers_invalid_asset_identifier",info:{identifier:A}});let{ticker:g,address:X}=zA({chain:n,symbol:O}),M=`${n}${F}${O}`;return{address:X,chain:L,isGasAsset:!1,isSynthetic:T,isTradeAsset:H,symbol:M,ticker:g}}function cT(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}=zA({chain:H,symbol:P}),F;try{F=L&&G.EVMChains.includes(H)&&WN.getAddress(L)?WN.getAddress(L):L}catch{F=L}let n=F?`${u}-${F}`:P;return{address:F,chain:H,isGasAsset:LN({chain:H,symbol:P}),isSynthetic:!1,isTradeAsset:!1,symbol:n,ticker:u}}function wA(A){let T=A.slice(0,14),H=T.includes("/"),P=T.includes("~");if(H||P)return dT(A,H,P);return cT(A)}function zA({symbol:A,chain:T}){let{ticker:H,address:P}=i(A,T);return{address:P&&!p.includes(T)?P.toLowerCase():P,ticker:H}}var rT={};w(rT,{SwapKitNumber:()=>IN});class IN extends k{eq(A){return this.eqValue(A)}static fromBigInt(A,T){return new IN({decimal:T,value:m({bigIntDecimal:T,decimal:T,value:A})})}}function JA(A=!0){return A?"https://midgard.thorchain.network":"https://midgard.mayachain.info"}function iT(A=!0){let T=JA(A);return A?`${T}/v2/thorname`:`${T}/v2/mayaname`}function sT(A){return function(H){let P=H?`?status=${H}`:"";return B.get(`${A}/v2/pools${P}`)}}function eT(A){return function(H){return B.get(`${A}/v2/pool/${H}`)}}function aT(A){return function(H,P){let L=P?`?period=${P}`:"";return B.get(`${A}/v2/pool/${H}/stats${L}`)}}function NH(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 B.get(`${A}/v2/history/depths/${H}${u}`)}}function AH(A){return function(){return B.get(`${A}/v2/network`)}}function TH(A){return function(){return B.get(`${A}/v2/health`)}}function HH(A){return function(){return B.get(`${A}/v2/nodes`)}}function PH(A){return function(H){return B.get(`${A}/v2/node/${H}`)}}function LH(A){return function(){return B.get(`${A}/v2/mimir/votes`)}}function RH(A){return function(){return B.get(`${A}/v2/mimir`)}}function uH(A){return function(){return B.get(`${A}/v2/constants`)}}function FH(A){return function(){return B.get(`${A}/v2/stats`)}}function IH(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 B.get(`${A}/v2/history/earnings${L}`)}}function nH(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 B.get(`${A}/v2/history${F}${u}`)}}function BH(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 B.get(`${A}/v2/history/tvl${L}`)}}function OH(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 $H(A){return function(H){let P=OH(H);return B.get(`${A}/v2/actions${P}`)}}function GH(A){return function(H){return B.get(`${A}/v2/member/${H}`)}}function MH(A){return function(H){let P=H?`/${H}`:"";return B.get(`${A}/v2/members${P}`)}}function _H(A){return function(H,P){let L=P?`&asset=${P}`:"";return B.get(`${A}/v2/saver/${H}${L?`?${L.substring(1)}`:""}`)}}function gH(A){return function(H){return B.get(`${A}/v2/savers/${H}`)}}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()}`:"",F=H?`/savers/${H}`:"/savers";return B.get(`${A}/v2/history${F}${u}`)}}function DH(A){return function(H){return B.get(`${A}/v2/balance/${H}`)}}function YH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return;throw L};return await B.get(`${A}/lookup/${H}`,{onError:P,retry:{maxRetries:1}})}}function UH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return[];throw L};return await B.get(`${A}/rlookup/${H}`,{onError:P,retry:{maxRetries:1}})}}function SH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return[];throw L};return await B.get(`${A}/owner/${H}`,{onError:P,retry:{maxRetries:1}})}}function AN({asset:A,value:T}){return z.from({asset:A,fromBaseDecimal:h.getChainConfig(h.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`]:AN({asset:"THOR.RUNE",value:F.runePending}),[`${u}RegisteredAddress`]:F.runeAddress,[`${u}Withdrawn`]:AN({asset:"THOR.RUNE",value:F.runeWithdrawn}),[u]:AN({asset:"THOR.RUNE",value:F.runeAdded}),asset:AN({asset:F.pool,value:F.assetAdded}),assetPending:AN({asset:F.pool,value:F.assetPending}),assetRegisteredAddress:F.assetAddress,assetWithdrawn:AN({asset:F.pool,value:F.assetWithdrawn}),dateFirstAdded:F.dateFirstAdded,dateLastAdded:F.dateLastAdded,poolShare:new IN(F.liquidityUnits).div(F.pool)}))}}function ZA(A){let T=A===h.Chain.THORChain,H=JA(T),P=iT(T),L=GH(H);return{getActions:$H(H),getBalance:DH(H),getConstants:uH(H),getEarningsHistory:IH(H),getHealth:TH(H),getLiquidityPosition:XH({isThorchain:T,liquidityPositionGetter:L}),getLiquidityPositionRaw:L,getMembers:MH(H),getMimir:RH(H),getMimirVotes:LH(H),getNameDetails:YH(P),getNamesByAddress:UH(P),getNamesByOwner:SH(P),getNetworkInfo:AH(H),getNode:PH(H),getNodes:HH(H),getPool:eT(H),getPoolDepthHistory:NH(H),getPoolStats:aT(H),getPools:sT(H),getSaverDetails:_H(H),getSavers:gH(H),getSaversHistory:tH(H),getStats:FH(H),getSwapHistory:nH(H),getTVLHistory:BH(H)}}var VA=ZA(h.Chain.THORChain),WA=ZA(h.Chain.Maya);var uA={};w(uA,{getTrackerDetails:()=>PP,getTokenListProviders:()=>IP,getTokenList:()=>nP,getTokenApproval:()=>FP,getSwapTo:()=>tP,getSwapQuote:()=>LP,getRouteWithTx:()=>RP,getPrice:()=>BP,getNearDepositChannel:()=>GP,getGasRate:()=>OP,getChainflipDepositChannel:()=>$P,getChainBalance:()=>uP,SKRequestClient:()=>Z});var cA=require("@swapkit/types"),y=require("ts-pattern");var EH={};w(EH,{signWidgetRequest:()=>qN});async function qN(A,T,H,P){let L=`${T}:${H}:${P}`,u=new TextEncoder,F=await crypto.subtle.importKey("raw",u.encode(A),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",F,u.encode(L));return Array.from(new Uint8Array(n)).map((O)=>O.toString(16).padStart(2,"0")).join("")}var v=require("@swapkit/types"),N=require("zod/v4");var KN;((P)=>{P.CHEAPEST="CHEAPEST";P.FASTEST="FASTEST";P.RECOMMENDED="RECOMMENDED"})(KN||={});var nN;((L)=>{L.PSBT="PSBT";L.EVM="EVM";L.COSMOS="COSMOS";L.RADIX="RADIX"})(nN||={});var mN;((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"})(mN||={});var pN;((D)=>{D.swap="swap";D.aggregation="aggregation";D.addLiquidity="addLiquidity";D.withdrawLiquidity="withdrawLiquidity";D.addSavers="addSavers";D.withdrawSavers="withdrawSavers";D.borrow="borrow";D.repay="repay";D.name="name";D.donate="donate";D.claim="claim";D.stake="stake";D.unstake="unstake"})(pN||={});var yN;((n)=>{n.unknown="unknown";n.not_started="not_started";n.pending="pending";n.swapping="swapping";n.completed="completed";n.refunded="refunded";n.failed="failed"})(yN||={});var oN;((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"})(oN||={});var QH=N.object({address:N.optional(N.string()),chain:N.z.enum(v.Chain).optional(),chainId:N.z.enum(v.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()}),xH=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"}),wH=N.z.object({forceUpdate:N.z.string().toLowerCase().transform((A)=>A==="true").pipe(N.z.boolean()).optional()}),bH=N.object({error:N.string(),message:N.string()}),d=N.object({address:N.optional(N.string()),chain:N.z.enum(v.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()}),fN=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(fN),identifier:N.string(),price_usd:N.number(),provider:N.string(),timestamp:N.number()}),CN=N.array(N.object({cg:N.optional(fN),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)=>x[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"]}),ZH=N.object({metadata:N.boolean(),tokens:N.array(N.object({identifier:N.string()}))}),hN=N.object({destinationAddress:N.string()}),qA=hN.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()})}),dN=N.object({channelId:N.string(),depositAddress:N.string()}),kN=hN.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()}),jA=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=jA.extend({depositAddress:N.string(),quote:jA,signature:N.string(),timestamp:N.string(),tx:N.unknown()}),cN=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())}),jH=N.object({currentStage:N.string(),inboundConfirmation:N.number(),inboundObservation:N.number(),outboundDelay:N.number(),outboundObservation:N.number(),streamingSwap:N.number()}),vH=N.object({count:N.optional(N.number()),interval:N.optional(N.number()),quantity:N.optional(N.number()),subSwapsMap:N.optional(N.array(N.number()))}),qH=N.z.object({currentLegIndex:N.z.optional(N.z.number()),estimatedTimeToComplete:N.z.number(),estimates:N.z.optional(jH),providerDetails:N.z.optional(N.z.object({streamingDetails:N.z.optional(vH)}))}),kH=N.object({affiliate:N.optional(d),liquidity:N.optional(d),network:N.optional(d),protocol:N.optional(d),tax:N.optional(d)}),KH=N.object({affiliate:N.string(),bps:N.string(),isReferrer:N.boolean()}),mH=N.object({affiliate:N.optional(N.string()),affiliateFees:N.optional(N.array(KH)),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(x)),providerAction:N.z.optional(N.z.enum(pN)),quoteId:N.optional(N.string()),wallet:N.optional(N.string())}),TN=N.z.object({block:N.z.number(),chainId:N.z.enum(v.ChainId),finalAddress:N.z.optional(N.z.string()),finalAsset:N.z.optional(d),finalisedAt:N.z.number(),fromAddress:N.z.string(),fromAmount:N.z.string(),fromAsset:N.z.string(),hash:N.z.string(),meta:N.z.optional(mH),payload:N.z.optional(WH),status:N.z.enum(yN),toAddress:N.z.string(),toAmount:N.z.string(),toAsset:N.z.string(),trackingStatus:N.z.optional(N.z.enum(oN)),transient:N.z.optional(qH),type:N.z.enum(mN)}),lN=TN.extend({legs:N.z.array(TN)}),pH=TN.extend({legs:N.array(TN)}),yH=TN.extend({legs:N.array(TN)}),QN=N.array(N.object({amount:N.string(),asset:N.string(),chain:N.string(),protocol:N.z.enum(x),type:N.z.enum(_N)})),xN=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")}),rN=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")}),iN=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()}),kA=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")])),oH=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:kA}),fH=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()})}),CH=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()})}),hH=N.object({typeUrl:N.string(),value:CH.shape.value.or(fH.shape.value)}),dH=N.object({amount:N.array(N.object({amount:N.string(),denom:N.string()})),gas:N.string()}),sN=N.object({accountNumber:N.number(),chainId:N.z.enum(v.ChainId),fee:dH,memo:N.string(),msgs:N.array(hH),sequence:N.number()}),KA=N.z.array(N.z.object({calldata:N.z.array(N.z.string()),contractAddress:N.z.string(),entrypoint:N.z.string()})),eN=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")})),mA=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:xN.optional(),provider:N.z.enum(x),sellAsset:N.string().describe("Asset to sell"),slipPercentage:N.number().describe("Slippage as a percentage"),sourceAddress:N.string().describe("Source address")}),cH=mA.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),pA=N.object({asset:N.string().describe("Asset name"),image:N.string().describe("Asset image"),price:N.number().describe("Price in USD")}),yA=qA,aN=N.object({assets:N.optional(N.array(pA)),maxStreamingQuantity:N.number().optional(),referrer:N.string().optional(),streamingInterval:N.number().optional(),tags:N.array(N.z.enum(KN))}),NA=aN.extend({affiliate:N.optional(N.string()),affiliateFee:N.optional(N.string()),approvalAddress:N.optional(N.string().describe("Approval address for swap")),chainflip:yA.optional(),garden:kN.optional(),near:kN.optional(),priceImpact:N.optional(N.number().describe("Price impact")),referrer:N.optional(N.string()),txType:N.optional(N.z.enum(nN))}),AA=N.array(N.object({code:N.z.enum(MN),display:N.string(),tooltip:N.string().optional()})),lH=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(QN),provider:N.z.enum(x),sellAmount:N.string().describe("Sell amount"),sellAsset:N.string().describe("Asset to sell")}),oA=N.object({buyAsset:N.string().describe("Asset to buy"),destinationAddress:N.optional(N.string().describe("Destination address")),estimatedTime:N.optional(xN),expectedBuyAmount:N.string().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:N.string().describe("Expected Buy amount max slippage"),expiration:N.optional(N.string().describe("Expiration")),fees:QN,inboundAddress:N.optional(N.string().describe("Inbound address")),legs:N.array(lH),memo:N.optional(N.string().describe("Memo")),meta:NA,providers:N.array(N.z.enum(x)),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([rN,sN,iN,KA,eN,N.string()])),txType:N.optional(N.z.enum(nN)),warnings:AA}),TA=N.object({error:N.optional(N.string().describe("Error message")),providerErrors:N.optional(N.array(N.object({errorCode:N.optional(N.z.enum(l)),message:N.optional(N.string()),provider:N.z.enum(x).optional()}))),quoteId:N.string().describe("Quote ID"),routes:N.array(oA)}),HA=N.z.object({chainId:N.z.enum(v.ChainId),createdAt:N.z.date(),id:N.z.number(),unit:N.z.string(),value:N.z.string()}),rH=N.z.array(HA),PA=N.z.union([HA,rH]),OL=N.array(N.object({chain:N.z.enum(v.Chain),decimal:N.number(),identifier:N.string(),symbol:N.string(),ticker:N.string(),value:N.string()})),iH=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(v.ChainId),spender:N.z.string(),tokenContractAddress:N.z.string(),userWalletAddress:N.z.string()}),N.z.object({routeId:N.z.string()})]),sH=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()}),fA=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)")}),vA=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:QN,provider:N.z.enum(x),sellAmount:N.z.string().describe("Sell amount"),sellAsset:N.z.string().describe("Asset to sell")}),CA=vA.extend({estimatedTime:N.z.optional(xN),expiration:N.z.optional(N.z.string().describe("Expiration")),legs:N.z.array(vA),providers:N.z.array(N.z.enum(x)),routeId:N.z.string().describe("Route ID"),totalSlippageBps:N.z.number().describe("Total slippage in bps"),warnings:AA}).omit({provider:!0}),eH=N.z.object({method:N.z.string(),payload:N.z.optional(N.z.unknown()),url:N.z.string()}),aH=CA.extend({meta:aN,nextActions:N.z.optional(N.z.array(eH))}),NP=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(l)),message:N.z.optional(N.z.string()),provider:N.z.enum(x).optional()}))),quoteId:N.z.string().describe("Quote ID"),routes:N.z.array(aH)}),AP=N.z.object({providers:N.z.array(N.z.enum(x)).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')")}),hA=N.z.object({chain:N.z.enum(v.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(x)).describe("Providers that support this trading pair"),symbol:N.z.string().describe("Asset symbol"),ticker:N.z.string().describe("Asset ticker")}),TP=N.z.object({buyAssets:N.z.array(hA).describe("List of assets that can be swapped to"),sellAsset:N.z.string().describe("The input sell asset identifier")}),LA=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:NA,sourceAddress:N.z.string().describe("Source address"),targetAddress:N.z.optional(N.z.string().describe("Target address")),tx:N.optional(N.union([rN,sN,iN,eN,N.string()])),txType:N.z.optional(N.z.enum(nN))}),dA=N.z.object({data:N.z.optional(N.z.record(N.z.string(),N.z.string().optional())),errorCode:N.z.enum(l),message:N.z.string().optional(),provider:N.z.enum(x).optional()}),HP=N.z.object({error:N.z.optional(N.z.string().describe("Error message")),providerErrors:N.z.optional(N.z.array(dA)),quoteId:N.z.string().describe("Quote ID"),routes:N.z.array(LA)}),RA=LA.extend({approvalTx:fA.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 Z=B.extend({dynamicHeader:async()=>{let A=U.get("widgetId"),T=U.get("widgetKey");if(A&&T&&typeof window<"u"){let P=Math.floor(Date.now()/1000),L=window.location.origin;return{"X-Signature":await qN(T,A,L,P),"X-Timestamp":P.toString(),"x-widget-id":A}}let{swapKit:H}=U.get("apiKeys");return H?{"x-api-key":H}:{}}});async function PP(A){let T=await Z.post(J("/track"),{json:A});try{let H=lN.safeParse(T);if(!H.success)throw new $("api_v2_invalid_response",H.error);return H.data}catch(H){return T}}async function LP(A){let{getQuote:T}=U.get("endpoints");if(T)return T(A);let P=U.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",L=await Z.post(J(P),{json:A});if(L.error)throw new $("api_v2_server_error",{message:L.error});try{let u=TA.safeParse(L);if(!u.success)throw new $("api_v2_invalid_response",u.error);return u.data}catch{return L}}async function RP(A){let{getRouteWithTx:T}=U.get("endpoints");if(T)return T(A);let P=U.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",L=await Z.post(J(P),{json:A});try{let u=RA.safeParse(L);if(!u.success)throw new $("api_v2_invalid_response",u.error);return u.data}catch(u){return console.error(new $("api_v2_invalid_response",u)),L}}async function uP({chain:A,address:T,scamFilter:H=!0}){let{getBalance:P}=U.get("endpoints");if(P)return P({address:T,chain:A});let L=J(`/balance?chain=${A}&address=${T}`),u=await Z.get(L),F=Array.isArray(u)?u:[];return H?gP(F):F}function FP(A){let T=y.match(A).with({routeId:y.P.string,spender:y.P.string},({routeId:H,spender:P})=>J(`/approve?routeId=${H}&sourceAddress=${P}`)).with({assetValue:y.P.instanceOf(z),spender:y.P.string,userWallet:y.P.string},({spender:H,userWallet:P,assetValue:L})=>J(`/approve?tokenIdentifier=${L.toString()}&userWalletAddress=${P}&spender=${H}&amount=${L.getValue("string")}`)).exhaustive();return Z.get(T)}function IP(){let A=J("/providers");return Z.get(A)}function nP(A){let T=J(`/tokens?provider=${A}`);return Z.get(T)}async function BP(A){let T=J("/price"),H=await Z.post(T,{json:A});try{let P=CN.safeParse(H);if(!P.success)throw new $("api_v2_invalid_response",P.error);return P.data}catch(P){throw new $("api_v2_invalid_response",P)}}async function OP(){let A=J("/gas"),T=await Z.get(A);try{let H=PA.safeParse(T);if(!H.success)throw new $("api_v2_invalid_response",H.error);return Array.isArray(H)?H:[H]}catch(H){throw new $("api_v2_invalid_response",H)}}async function $P(A){let{destinationAddress:T}=A;if(!T)throw new $("chainflip_broker_invalid_params");let H=U.get("integrations").chainflip?.brokerUrl||J("/chainflip/broker/channel"),P=await Z.post(H,{json:A});try{let L=dN.safeParse(P);if(!L.success)throw new $("api_v2_invalid_response",L.error);return L.data}catch(L){throw new $("api_v2_invalid_response",L)}}async function GP(A){let{destinationAddress:T}=A;if(!T)throw new $("chainflip_broker_invalid_params");let H=J("/near/channel"),P=await Z.post(H,{json:A});try{let L=cN.safeParse(P);if(!L.success)throw new $("api_v2_invalid_response",L.error);return L.data}catch(L){throw new $("api_v2_invalid_response",L)}}function J(A){let{isDev:T,apiUrl:H,devApiUrl:P}=U.get("envs");return`${T?P:H}${A}`}function MP(A){let[T,H]=A.split(".");if(!cA.EVMChains.includes(T))return!0;let P=H.split("-"),L=P.length===1?void 0:P[P.length-1];return LN({chain:T,symbol:H})||!!L}var _P=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi");function gP(A){return A.filter((T)=>{return!_P.test(T.identifier)&&MP(T.identifier)})}async function tP(A){let{getSwapTo:T}=U.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=J(`/swapTo?${H.toString()}`),L=await Z.get(P);if(!Array.isArray(L))return{buyAssets:[],sellAsset:A.sellAsset};let u=[];for(let F of L)try{let n=z.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 FA={};w(FA,{getThorchainQueue:()=>UP,getTcyStakers:()=>zP,getTcyStaker:()=>bP,getTcyClaimers:()=>ZP,getTcyClaimer:()=>JP,getTNSPreferredAsset:()=>QP,getTHORNodeTNSDetails:()=>rA,getRunePoolProviderInfo:()=>wP,getRunePoolInfo:()=>xP,getNodes:()=>SP,getMimirInfo:()=>XP,getLastBlock:()=>YP,getInboundAddresses:()=>EP});var lA=require("ts-pattern");function W(A){let{isStagenet:T}=U.get("envs"),H=U.get("thornodeUrls");return`${lA.match({isStagenet:T,type:A}).with({type:"mayachain"},({isStagenet:L})=>L?H.MAYA_STAGENET:H.MAYA).with({type:"thorchain"},({isStagenet:L})=>L?H.THOR_STAGENET:H.THOR)}/${A}`}function DP(A){let T=A==="mayachain"?"mayaname":"thorname";return`${W(A)}/${T}`}function YP(A="thorchain"){return B.get(`${W(A)}/lastblock`)}function UP(A){return B.get(`${W(A)}/queue`)}function SP(A){return B.get(`${W(A)}/nodes`)}function XP(A){return B.get(`${W(A)}/mimir`)}function EP(A){return B.get(`${W(A)}/inbound_addresses`)}async function rA({type:A,name:T}){try{return await B.get(`${DP(A)}/${T}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:T,owner:"",preferred_asset:""}}}async function QP({type:A,tns:T}){let H=await rA({name:T,type:A});if(!H.preferred_asset||H.preferred_asset===".")return;return z.from({asset:H.preferred_asset,asyncTokenLookup:!0})}function xP(A){return B.get(`${W(A)}/runepool`)}function wP({type:A,thorAddress:T}){return B.get(`${W(A)}/rune_provider/${T}`)}function bP({type:A,address:T}){return B.get(`${W(A)}/tcy_staker/${T}`)}function zP(A){return B.get(`${W(A)}/tcy_stakers`)}function JP({type:A,address:T}){return B.get(`${W(A)}/tcy_claimer/${T}`)}function ZP(A){return B.get(`${W(A)}/tcy_claimers`)}var WP={...uA,mayachainMidgard:WA,thorchainMidgard:VA,thornode:FA};
4
+ or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`});let{decimal:HN,identifier:Y,tax:BN}=E||{decimal:Q||j,identifier:O},ON=T?NN(BigInt(L),T):NN(L,HN);return M||V?oT(Y,ON):jN({decimal:HN,identifier:Y,tax:BN,value:ON})}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}=K(u),{address:O}=i(n,F),{baseDecimal:g}=G.getChainConfig(F),X=p.includes(F)?u:u.toUpperCase(),M="decimals"in L&&L.decimals!==void 0?L.decimals:g,V="logoURI"in L&&L.logoURI?L.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${u.toLowerCase()}.png`,D={decimal:M,identifier:u,logoURI:V,tax:"tax"in L?L.tax:void 0};if(e.set(X,D),O){let j=p.includes(F)?`${F}:${O}`:`${F}:${O.toUpperCase()}`;XN.set(j,u)}}return!0}static setStaticAssets(A){e.clear(),XN.clear();for(let[T,H]of A.entries()){let{identifier:P}=H,{chain:L,symbol:u}=K(P),{address:F}=i(u,L),{baseDecimal:n}=G.getChainConfig(L),O=H.chain??L,g=H.address??F,X=p.includes(O)?P:P.toUpperCase(),M=H.decimals??H.decimal??n,V=H.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${P.toLowerCase()}.png`,D={decimal:M,identifier:X,logoURI:V,tax:H.tax};if(e.set(X,D),g){let j=p.includes(O)?`${O}:${g}`:`${O}:${g.toUpperCase()}`;XN.set(j,P)}}return!0}static get staticAssets(){return e}}function yT(A){let T=z.from({chain:A});return EN.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 bA({chain:A,address:T,ticker:H}){let L=p.includes(A)?`${A}:${T||H}`:`${A}:${T||H}`.toUpperCase(),u=mT(L);if(u)return u;if(!T){let{baseDecimal:O}=G.getChainConfig(A);return{decimals:O,identifier:`${A}.${H||"UNKNOWN"}`}}let F=await JN({address:T,chain:A}),n=`${A}.${F.ticker||H||"UNKNOWN"}-${T}`;return o({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&&pT(L,{decimals:F.decimals,identifier:n}),{decimals:F.decimals,identifier:n}}function jN({identifier:A,decimal:T,value:H,tax:P}){return ZN(A),new z({decimal:T,identifier:A,tax:P,value:NN(H,T)})}function oT(A,T=0){let H=A.includes(".")?A.split(".")?.[0]?.toUpperCase():void 0,P=H?vN.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 $({errorKey:"helpers_invalid_asset_identifier",info:{identifier:A}});return new z({decimal:8,identifier:`${H||G.Chain.THORChain}.${u}${L}${F}`,value:NN(T,8)})}async function fT({address:A,chain:T,fromBaseDecimal:H,parsedValue:P}){let{decimals:L,identifier:u}=await bA({address:A,chain:T}),F=H?NN(BigInt(P),H):P;return jN({decimal:L,identifier:u,value:F})}function NN(A,T){return typeof A==="bigint"?m({bigIntDecimal:T,decimal:T,value:A}):A}function CT(A){let T=EN.match(A).when((H)=>("chain"in H)&&H.chain!==void 0,({chain:H})=>H).otherwise((H)=>{let P=K(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 $({errorKey:"helpers_invalid_asset_identifier",info:{identifier:H,message:`Unsupported chain "${T}" - use the AssetValue constructor directly`}})}}function hT(A){if(CT(A),"chain"in A){let{chain:L,address:u}=A;if(u){let F=p.includes(L)?`${L}:${u}`:`${L}:${u.toUpperCase()}`,n=XN.get(F);if(n)return n;return null}return L}let{chain:T,symbol:H}=K(A.asset);return UN({chain:T,symbol:H})==="Native"?T:A.asset}function dT(A,T,H){let P=A.split("."),L=P[0]?.toUpperCase(),u=vN.includes(L),F=H?"~":"/",[n,O=""]=u?P.slice(1).join(".").split(F):A.split(F);if(!(n&&O))throw new $({errorKey:"helpers_invalid_asset_identifier",info:{identifier:A}});let{ticker:g,address:X}=zA({chain:n,symbol:O}),M=`${n}${F}${O}`;return{address:X,chain:L,isGasAsset:!1,isSynthetic:T,isTradeAsset:H,symbol:M,ticker:g}}function cT(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}=zA({chain:H,symbol:P}),F;try{F=L&&G.EVMChains.includes(H)&&WN.getAddress(L)?WN.getAddress(L):L}catch{F=L}let n=F?`${u}-${F}`:P;return{address:F,chain:H,isGasAsset:LN({chain:H,symbol:P}),isSynthetic:!1,isTradeAsset:!1,symbol:n,ticker:u}}function wA(A){let T=A.slice(0,14),H=T.includes("/"),P=T.includes("~");if(H||P)return dT(A,H,P);return cT(A)}function zA({symbol:A,chain:T}){let{ticker:H,address:P}=i(A,T);return{address:P&&!p.includes(T)?P.toLowerCase():P,ticker:H}}var rT={};w(rT,{SwapKitNumber:()=>IN});class IN extends k{eq(A){return this.eqValue(A)}static fromBigInt(A,T){return new IN({decimal:T,value:m({bigIntDecimal:T,decimal:T,value:A})})}}function JA(A=!0){return A?"https://midgard.thorchain.network":"https://midgard.mayachain.info"}function iT(A=!0){let T=JA(A);return A?`${T}/v2/thorname`:`${T}/v2/mayaname`}function sT(A){return function(H){let P=H?`?status=${H}`:"";return B.get(`${A}/v2/pools${P}`)}}function eT(A){return function(H){return B.get(`${A}/v2/pool/${H}`)}}function aT(A){return function(H,P){let L=P?`?period=${P}`:"";return B.get(`${A}/v2/pool/${H}/stats${L}`)}}function NH(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 B.get(`${A}/v2/history/depths/${H}${u}`)}}function AH(A){return function(){return B.get(`${A}/v2/network`)}}function TH(A){return function(){return B.get(`${A}/v2/health`)}}function HH(A){return function(){return B.get(`${A}/v2/nodes`)}}function PH(A){return function(H){return B.get(`${A}/v2/node/${H}`)}}function LH(A){return function(){return B.get(`${A}/v2/mimir/votes`)}}function RH(A){return function(){return B.get(`${A}/v2/mimir`)}}function uH(A){return function(){return B.get(`${A}/v2/constants`)}}function FH(A){return function(){return B.get(`${A}/v2/stats`)}}function IH(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 B.get(`${A}/v2/history/earnings${L}`)}}function nH(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 B.get(`${A}/v2/history${F}${u}`)}}function BH(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 B.get(`${A}/v2/history/tvl${L}`)}}function OH(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 $H(A){return function(H){let P=OH(H);return B.get(`${A}/v2/actions${P}`)}}function GH(A){return function(H){return B.get(`${A}/v2/member/${H}`)}}function MH(A){return function(H){let P=H?`/${H}`:"";return B.get(`${A}/v2/members${P}`)}}function _H(A){return function(H,P){let L=P?`&asset=${P}`:"";return B.get(`${A}/v2/saver/${H}${L?`?${L.substring(1)}`:""}`)}}function gH(A){return function(H){return B.get(`${A}/v2/savers/${H}`)}}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()}`:"",F=H?`/savers/${H}`:"/savers";return B.get(`${A}/v2/history${F}${u}`)}}function DH(A){return function(H){return B.get(`${A}/v2/balance/${H}`)}}function YH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return;throw L};return await B.get(`${A}/lookup/${H}`,{onError:P,retry:{maxRetries:1}})}}function UH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return[];throw L};return await B.get(`${A}/rlookup/${H}`,{onError:P,retry:{maxRetries:1}})}}function SH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return[];throw L};return await B.get(`${A}/owner/${H}`,{onError:P,retry:{maxRetries:1}})}}function AN({asset:A,value:T}){return z.from({asset:A,fromBaseDecimal:h.getChainConfig(h.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`]:AN({asset:"THOR.RUNE",value:F.runePending}),[`${u}RegisteredAddress`]:F.runeAddress,[`${u}Withdrawn`]:AN({asset:"THOR.RUNE",value:F.runeWithdrawn}),[u]:AN({asset:"THOR.RUNE",value:F.runeAdded}),asset:AN({asset:F.pool,value:F.assetAdded}),assetPending:AN({asset:F.pool,value:F.assetPending}),assetRegisteredAddress:F.assetAddress,assetWithdrawn:AN({asset:F.pool,value:F.assetWithdrawn}),dateFirstAdded:F.dateFirstAdded,dateLastAdded:F.dateLastAdded,poolShare:new IN(F.liquidityUnits).div(F.pool)}))}}function ZA(A){let T=A===h.Chain.THORChain,H=JA(T),P=iT(T),L=GH(H);return{getActions:$H(H),getBalance:DH(H),getConstants:uH(H),getEarningsHistory:IH(H),getHealth:TH(H),getLiquidityPosition:XH({isThorchain:T,liquidityPositionGetter:L}),getLiquidityPositionRaw:L,getMembers:MH(H),getMimir:RH(H),getMimirVotes:LH(H),getNameDetails:YH(P),getNamesByAddress:UH(P),getNamesByOwner:SH(P),getNetworkInfo:AH(H),getNode:PH(H),getNodes:HH(H),getPool:eT(H),getPoolDepthHistory:NH(H),getPoolStats:aT(H),getPools:sT(H),getSaverDetails:_H(H),getSavers:gH(H),getSaversHistory:tH(H),getStats:FH(H),getSwapHistory:nH(H),getTVLHistory:BH(H)}}var VA=ZA(h.Chain.THORChain),WA=ZA(h.Chain.Maya);var uA={};w(uA,{getTrackerDetails:()=>PP,getTokenListProviders:()=>IP,getTokenList:()=>nP,getTokenApproval:()=>FP,getSwapTo:()=>tP,getSwapQuote:()=>LP,getRouteWithTx:()=>RP,getPrice:()=>BP,getNearDepositChannel:()=>GP,getGasRate:()=>OP,getChainflipDepositChannel:()=>$P,getChainBalance:()=>uP,SKRequestClient:()=>Z});var cA=require("@swapkit/types"),y=require("ts-pattern");var EH={};w(EH,{signWidgetRequest:()=>qN});async function qN(A,T,H,P){let L=`${T}:${H}:${P}`,u=new TextEncoder,F=await crypto.subtle.importKey("raw",u.encode(A),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",F,u.encode(L));return Array.from(new Uint8Array(n)).map((O)=>O.toString(16).padStart(2,"0")).join("")}var v=require("@swapkit/types"),N=require("zod/v4");var KN;((P)=>{P.CHEAPEST="CHEAPEST";P.FASTEST="FASTEST";P.RECOMMENDED="RECOMMENDED"})(KN||={});var nN;((L)=>{L.PSBT="PSBT";L.EVM="EVM";L.COSMOS="COSMOS";L.RADIX="RADIX"})(nN||={});var mN;((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"})(mN||={});var pN;((D)=>{D.swap="swap";D.aggregation="aggregation";D.addLiquidity="addLiquidity";D.withdrawLiquidity="withdrawLiquidity";D.addSavers="addSavers";D.withdrawSavers="withdrawSavers";D.borrow="borrow";D.repay="repay";D.name="name";D.donate="donate";D.claim="claim";D.stake="stake";D.unstake="unstake"})(pN||={});var yN;((n)=>{n.unknown="unknown";n.not_started="not_started";n.pending="pending";n.swapping="swapping";n.completed="completed";n.refunded="refunded";n.failed="failed"})(yN||={});var oN;((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"})(oN||={});var QH=N.object({address:N.optional(N.string()),chain:N.z.enum(v.Chain).optional(),chainId:N.z.enum(v.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()}),xH=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"}),wH=N.z.object({forceUpdate:N.z.string().toLowerCase().transform((A)=>A==="true").pipe(N.z.boolean()).optional()}),bH=N.object({error:N.string(),message:N.string()}),d=N.object({address:N.optional(N.string()),chain:N.z.enum(v.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()}),fN=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(fN),identifier:N.string(),price_usd:N.number(),provider:N.string(),timestamp:N.number()}),CN=N.array(N.object({cg:N.optional(fN),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)=>x[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"]}),ZH=N.object({metadata:N.boolean(),tokens:N.array(N.object({identifier:N.string()}))}),hN=N.object({destinationAddress:N.string()}),qA=hN.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()})}),dN=N.object({channelId:N.string(),depositAddress:N.string()}),kN=hN.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()}),jA=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=jA.extend({depositAddress:N.string(),quote:jA,signature:N.string(),timestamp:N.string(),tx:N.unknown()}),cN=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())}),jH=N.object({currentStage:N.string(),inboundConfirmation:N.number(),inboundObservation:N.number(),outboundDelay:N.number(),outboundObservation:N.number(),streamingSwap:N.number()}),vH=N.object({count:N.optional(N.number()),interval:N.optional(N.number()),quantity:N.optional(N.number()),subSwapsMap:N.optional(N.array(N.number()))}),qH=N.z.object({currentLegIndex:N.z.optional(N.z.number()),estimatedTimeToComplete:N.z.number(),estimates:N.z.optional(jH),providerDetails:N.z.optional(N.z.object({streamingDetails:N.z.optional(vH)}))}),kH=N.object({affiliate:N.optional(d),liquidity:N.optional(d),network:N.optional(d),protocol:N.optional(d),tax:N.optional(d)}),KH=N.object({affiliate:N.string(),bps:N.string(),isReferrer:N.boolean()}),mH=N.object({affiliate:N.optional(N.string()),affiliateFees:N.optional(N.array(KH)),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(x)),providerAction:N.z.optional(N.z.enum(pN)),quoteId:N.optional(N.string()),wallet:N.optional(N.string())}),TN=N.z.object({block:N.z.number(),chainId:N.z.enum(v.ChainId),finalAddress:N.z.optional(N.z.string()),finalAsset:N.z.optional(d),finalisedAt:N.z.number(),fromAddress:N.z.string(),fromAmount:N.z.string(),fromAsset:N.z.string(),hash:N.z.string(),meta:N.z.optional(mH),payload:N.z.optional(WH),status:N.z.enum(yN),toAddress:N.z.string(),toAmount:N.z.string(),toAsset:N.z.string(),trackingStatus:N.z.optional(N.z.enum(oN)),transient:N.z.optional(qH),type:N.z.enum(mN)}),lN=TN.extend({legs:N.z.array(TN)}),pH=TN.extend({legs:N.array(TN)}),yH=TN.extend({legs:N.array(TN)}),QN=N.array(N.object({amount:N.string(),asset:N.string(),chain:N.string(),protocol:N.z.enum(x),type:N.z.enum(_N)})),xN=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")}),rN=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")}),iN=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()}),kA=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")])),oH=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:kA}),fH=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()})}),CH=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()})}),hH=N.object({typeUrl:N.string(),value:CH.shape.value.or(fH.shape.value)}),dH=N.object({amount:N.array(N.object({amount:N.string(),denom:N.string()})),gas:N.string()}),sN=N.object({accountNumber:N.number(),chainId:N.z.enum(v.ChainId),fee:dH,memo:N.string(),msgs:N.array(hH),sequence:N.number()}),KA=N.z.array(N.z.object({calldata:N.z.array(N.z.string()),contractAddress:N.z.string(),entrypoint:N.z.string()})),eN=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")})),mA=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:xN.optional(),provider:N.z.enum(x),sellAsset:N.string().describe("Asset to sell"),slipPercentage:N.number().describe("Slippage as a percentage"),sourceAddress:N.string().describe("Source address")}),cH=mA.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),pA=N.object({asset:N.string().describe("Asset name"),image:N.string().describe("Asset image"),price:N.number().describe("Price in USD")}),yA=qA,aN=N.object({assets:N.optional(N.array(pA)),maxStreamingQuantity:N.number().optional(),referrer:N.string().optional(),streamingInterval:N.number().optional(),tags:N.array(N.z.enum(KN))}),NA=aN.extend({affiliate:N.optional(N.string()),affiliateFee:N.optional(N.string()),approvalAddress:N.optional(N.string().describe("Approval address for swap")),chainflip:yA.optional(),garden:kN.optional(),near:kN.optional(),priceImpact:N.optional(N.number().describe("Price impact")),referrer:N.optional(N.string()),txType:N.optional(N.z.enum(nN))}),AA=N.array(N.object({code:N.z.enum(MN),display:N.string(),tooltip:N.string().optional()})),lH=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(QN),provider:N.z.enum(x),sellAmount:N.string().describe("Sell amount"),sellAsset:N.string().describe("Asset to sell")}),oA=N.object({buyAsset:N.string().describe("Asset to buy"),destinationAddress:N.optional(N.string().describe("Destination address")),estimatedTime:N.optional(xN),expectedBuyAmount:N.string().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:N.string().describe("Expected Buy amount max slippage"),expiration:N.optional(N.string().describe("Expiration")),fees:QN,inboundAddress:N.optional(N.string().describe("Inbound address")),legs:N.array(lH),memo:N.optional(N.string().describe("Memo")),meta:NA,providers:N.array(N.z.enum(x)),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([rN,sN,iN,KA,eN,N.string()])),txType:N.optional(N.z.enum(nN)),warnings:AA}),TA=N.object({error:N.optional(N.string().describe("Error message")),providerErrors:N.optional(N.array(N.object({errorCode:N.optional(N.z.enum(l)),message:N.optional(N.string()),provider:N.z.enum(x).optional()}))),quoteId:N.string().describe("Quote ID"),routes:N.array(oA)}),HA=N.z.object({chainId:N.z.enum(v.ChainId),createdAt:N.z.date(),id:N.z.number(),unit:N.z.string(),value:N.z.string()}),rH=N.z.array(HA),PA=N.z.union([HA,rH]),OL=N.array(N.object({chain:N.z.enum(v.Chain),decimal:N.number(),identifier:N.string(),symbol:N.string(),ticker:N.string(),value:N.string()})),iH=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(v.ChainId),spender:N.z.string(),tokenContractAddress:N.z.string(),userWalletAddress:N.z.string()}),N.z.object({routeId:N.z.string()})]),sH=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()}),fA=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)")}),vA=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:QN,provider:N.z.enum(x),sellAmount:N.z.string().describe("Sell amount"),sellAsset:N.z.string().describe("Asset to sell")}),CA=vA.extend({estimatedTime:N.z.optional(xN),expiration:N.z.optional(N.z.string().describe("Expiration")),legs:N.z.array(vA),providers:N.z.array(N.z.enum(x)),routeId:N.z.string().describe("Route ID"),totalSlippageBps:N.z.number().describe("Total slippage in bps"),warnings:AA}).omit({provider:!0}),eH=N.z.object({method:N.z.string(),payload:N.z.optional(N.z.unknown()),url:N.z.string()}),aH=CA.extend({meta:aN,nextActions:N.z.optional(N.z.array(eH))}),NP=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(l)),message:N.z.optional(N.z.string()),provider:N.z.enum(x).optional()}))),quoteId:N.z.string().describe("Quote ID"),routes:N.z.array(aH)}),AP=N.z.object({providers:N.z.array(N.z.enum(x)).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')")}),hA=N.z.object({chain:N.z.enum(v.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(x)).describe("Providers that support this trading pair"),symbol:N.z.string().describe("Asset symbol"),ticker:N.z.string().describe("Asset ticker")}),TP=N.z.object({buyAssets:N.z.array(hA).describe("List of assets that can be swapped to"),sellAsset:N.z.string().describe("The input sell asset identifier")}),LA=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:NA,sourceAddress:N.z.string().describe("Source address"),targetAddress:N.z.optional(N.z.string().describe("Target address")),tx:N.optional(N.union([rN,sN,iN,eN,N.string()])),txType:N.z.optional(N.z.enum(nN))}),dA=N.z.object({data:N.z.optional(N.z.record(N.z.string(),N.z.string().optional())),errorCode:N.z.enum(l),message:N.z.string().optional(),provider:N.z.enum(x).optional()}),HP=N.z.object({error:N.z.optional(N.z.string().describe("Error message")),providerErrors:N.z.optional(N.z.array(dA)),quoteId:N.z.string().describe("Quote ID"),routes:N.z.array(LA)}),RA=LA.extend({approvalTx:fA.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 Z=B.extend({dynamicHeader:async()=>{let A=U.get("widgetId"),T=U.get("widgetKey");if(A&&T&&typeof window<"u"){let P=Math.floor(Date.now()/1000),L=window.location.origin,u=await qN(T,A,L,P);return{Origin:L,"X-Signature":u,"X-Timestamp":P.toString(),"x-widget-id":A}}let{swapKit:H}=U.get("apiKeys");return H?{"x-api-key":H}:{}}});async function PP(A){let T=await Z.post(J("/track"),{json:A});try{let H=lN.safeParse(T);if(!H.success)throw new $("api_v2_invalid_response",H.error);return H.data}catch(H){return T}}async function LP(A){let{getQuote:T}=U.get("endpoints");if(T)return T(A);let P=U.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",L=await Z.post(J(P),{json:A});if(L.error)throw new $("api_v2_server_error",{message:L.error});try{let u=TA.safeParse(L);if(!u.success)throw new $("api_v2_invalid_response",u.error);return u.data}catch{return L}}async function RP(A){let{getRouteWithTx:T}=U.get("endpoints");if(T)return T(A);let P=U.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",L=await Z.post(J(P),{json:A});try{let u=RA.safeParse(L);if(!u.success)throw new $("api_v2_invalid_response",u.error);return u.data}catch(u){return console.error(new $("api_v2_invalid_response",u)),L}}async function uP({chain:A,address:T,scamFilter:H=!0}){let{getBalance:P}=U.get("endpoints");if(P)return P({address:T,chain:A});let L=J(`/balance?chain=${A}&address=${T}`),u=await Z.get(L),F=Array.isArray(u)?u:[];return H?gP(F):F}function FP(A){let T=y.match(A).with({routeId:y.P.string,spender:y.P.string},({routeId:H,spender:P})=>J(`/approve?routeId=${H}&sourceAddress=${P}`)).with({assetValue:y.P.instanceOf(z),spender:y.P.string,userWallet:y.P.string},({spender:H,userWallet:P,assetValue:L})=>J(`/approve?tokenIdentifier=${L.toString()}&userWalletAddress=${P}&spender=${H}&amount=${L.getValue("string")}`)).exhaustive();return Z.get(T)}function IP(){let A=J("/providers");return Z.get(A)}function nP(A){let T=J(`/tokens?provider=${A}`);return Z.get(T)}async function BP(A){let T=J("/price"),H=await Z.post(T,{json:A});try{let P=CN.safeParse(H);if(!P.success)throw new $("api_v2_invalid_response",P.error);return P.data}catch(P){throw new $("api_v2_invalid_response",P)}}async function OP(){let A=J("/gas"),T=await Z.get(A);try{let H=PA.safeParse(T);if(!H.success)throw new $("api_v2_invalid_response",H.error);return Array.isArray(H)?H:[H]}catch(H){throw new $("api_v2_invalid_response",H)}}async function $P(A){let{destinationAddress:T}=A;if(!T)throw new $("chainflip_broker_invalid_params");let H=U.get("integrations").chainflip?.brokerUrl||J("/chainflip/broker/channel"),P=await Z.post(H,{json:A});try{let L=dN.safeParse(P);if(!L.success)throw new $("api_v2_invalid_response",L.error);return L.data}catch(L){throw new $("api_v2_invalid_response",L)}}async function GP(A){let{destinationAddress:T}=A;if(!T)throw new $("chainflip_broker_invalid_params");let H=J("/near/channel"),P=await Z.post(H,{json:A});try{let L=cN.safeParse(P);if(!L.success)throw new $("api_v2_invalid_response",L.error);return L.data}catch(L){throw new $("api_v2_invalid_response",L)}}function J(A){let{isDev:T,apiUrl:H,devApiUrl:P}=U.get("envs");return`${T?P:H}${A}`}function MP(A){let[T,H]=A.split(".");if(!cA.EVMChains.includes(T))return!0;let P=H.split("-"),L=P.length===1?void 0:P[P.length-1];return LN({chain:T,symbol:H})||!!L}var _P=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi");function gP(A){return A.filter((T)=>{return!_P.test(T.identifier)&&MP(T.identifier)})}async function tP(A){let{getSwapTo:T}=U.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=J(`/swapTo?${H.toString()}`),L=await Z.get(P);if(!Array.isArray(L))return{buyAssets:[],sellAsset:A.sellAsset};let u=[];for(let F of L)try{let n=z.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 FA={};w(FA,{getThorchainQueue:()=>UP,getTcyStakers:()=>zP,getTcyStaker:()=>bP,getTcyClaimers:()=>ZP,getTcyClaimer:()=>JP,getTNSPreferredAsset:()=>QP,getTHORNodeTNSDetails:()=>rA,getRunePoolProviderInfo:()=>wP,getRunePoolInfo:()=>xP,getNodes:()=>SP,getMimirInfo:()=>XP,getLastBlock:()=>YP,getInboundAddresses:()=>EP});var lA=require("ts-pattern");function W(A){let{isStagenet:T}=U.get("envs"),H=U.get("thornodeUrls");return`${lA.match({isStagenet:T,type:A}).with({type:"mayachain"},({isStagenet:L})=>L?H.MAYA_STAGENET:H.MAYA).otherwise(({isStagenet:L})=>L?H.THOR_STAGENET:H.THOR)}/${A??"thorchain"}`}function DP(A){let T=A==="mayachain"?"mayaname":"thorname";return`${W(A)}/${T}`}function YP(A="thorchain"){return B.get(`${W(A)}/lastblock`)}function UP(A){return B.get(`${W(A)}/queue`)}function SP(A){return B.get(`${W(A)}/nodes`)}function XP(A){return B.get(`${W(A)}/mimir`)}function EP(A){return B.get(`${W(A)}/inbound_addresses`)}async function rA({type:A,name:T}){try{return await B.get(`${DP(A)}/${T}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:T,owner:"",preferred_asset:""}}}async function QP({type:A,tns:T}){let H=await rA({name:T,type:A});if(!H.preferred_asset||H.preferred_asset===".")return;return z.from({asset:H.preferred_asset,asyncTokenLookup:!0})}function xP(A){return B.get(`${W(A)}/runepool`)}function wP({type:A,thorAddress:T}){return B.get(`${W(A)}/rune_provider/${T}`)}function bP({type:A,address:T}){return B.get(`${W(A)}/tcy_staker/${T}`)}function zP(A){return B.get(`${W(A)}/tcy_stakers`)}function JP({type:A,address:T}){return B.get(`${W(A)}/tcy_claimer/${T}`)}function ZP(A){return B.get(`${W(A)}/tcy_claimers`)}var WP={...uA,mayachainMidgard:WA,thorchainMidgard:VA,thornode:FA};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{$ as Zg,A as hf,Aa as hg,B as of,Ba as og,C as uf,Ca as ug,D as sf,Da as sg,E as df,Ea as dg,F as lf,Fa as lg,G as nf,Ga as ng,H as pf,Ha as pg,I as tf,Ia as ig,J as af,Ja as tg,K as ef,Ka as ag,L as $g,La as eg,M as P,Ma as $R,N as fg,Na as fR,O as gg,Oa as gR,P as Rg,Pa as RR,Q as Bg,Qa as BR,R as xg,S as Mg,T as Yg,U as Gg,V as zg,W as Jg,X as Lg,Y as Pg,Z as Qg,_ as Xg,a as X,aa as _g,b as Ef,ba as Vg,c as If,ca as Cg,d as Tf,da as Wg,e as Sf,ea as jg,f as b,fa as Fg,g as qf,ga as Hg,h as i,ha as Eg,i as e,ia as Ig,j as Nf,ja as Tg,k as Kf,ka as Sg,l as E,la as qg,m as _,ma as Ng,n as Af,na as Kg,o as Of,oa as Ag,p as Uf,pa as Og,q as Df,qa as Ug,r as yf,ra as Dg,s as N,sa as yg,t as kf,ta as kg,u as bf,ua as bg,v as mf,va as mg,w as vf,wa as vg,x as wf,xa as wg,y as cf,ya as cg,z as rf,za as rg}from"./chunk-x05xsas4.js";export*from"@swapkit/tokens";export*from"@swapkit/types";var m={average:1,fast:1.5,fastest:2};function I($="average"){let f=E.get("feeMultipliers");if(f&&f[$]!==void 0)return f[$];return m[$]}function v($="average"){let f=I($),g=10n,R=BigInt(Math.round(f*10));return{denominator:g,numerator:R}}function Y$($,f="average"){let{numerator:g,denominator:R}=v(f);return $*g/R}function G$($,f="average",g=!1){let R=I(f),B=$*R;return g?Math.floor(B):B}import{Chain as T,EVMChains as w}from"@swapkit/types";function j($,f){if("index"in f)return[...$.slice(0,$.length-1),f.index];if("change"in f){let[g,R,B,,x]=$;return[g,R,B,f.change,x]}if("account"in f){let[g,R,,B,x]=$;return[g,R,f.account,B,x]}return $}function c([$,f,g,R,B],{allHardened:x}={}){let Y=x?"'":"",G=typeof B!=="number";if(typeof R!=="number")return`m/${$}'/${f}'/${g}'`;return`m/${$}'/${f}'/${g}'/${R}${Y}${G?"":`/${B}${Y}`}`}function P$({chain:$,index:f,addressIndex:g=0,type:R}){if(w.includes($)){if(R&&["legacy","account"].includes(R))return[44,60,0,f];if(R==="ledgerLive")return[44,60,f,0,g];return j(X[$],{index:f})}if($===T.Solana){if(R==="account")return[44,501,0,f];return j(X[$],{index:f})}let B=$===T.Litecoin?2:0;switch(R){case"nativeSegwitMiddleAccount":return[84,B,f,0,g];case"segwit":return[49,B,0,0,f];case"legacy":return[44,B,0,0,f];default:return j(X[$],{index:f})}}function Q$($){let[f,g,R]=$.split("/").map((B)=>Number.parseInt(B,10));switch(g){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var X$=Object.keys(X).reduce(($,f)=>{return $[f]=c(X[f]),$},{});import{Chain as J,CosmosChains as r,EVMChains as h,getChainConfig as S,SubstrateChains as o,UTXOChains as u}from"@swapkit/types";import{match as q}from"ts-pattern";function C$({chain:$,txHash:f}){let{explorerUrl:g}=S($);return q($).with(...r,J.Solana,()=>`${g}/tx/${f.startsWith("0x")?f.slice(2):f}`).with(...h,...o,()=>`${g}/tx/${f.startsWith("0x")?f:`0x${f}`}`).with(...u,J.Radix,J.Tron,()=>`${g}/transaction/${f.toLowerCase()}`).with(J.Near,()=>`${g}/txns/${f}`).with(J.Ripple,()=>`${g}/transactions/${f}`).with(J.Sui,()=>`${g}/txblock/${f}`).with(J.Cardano,J.HyperCore,J.Ton,()=>`${g}/tx/${f}`).otherwise(()=>"")}function W$({chain:$,address:f}){let{explorerUrl:g}=S($);return q($).with(J.Solana,J.Sui,J.Radix,()=>`${g}/account/${f}`).otherwise(()=>`${g}/address/${f}`)}import{Chain as s,getChainConfig as d}from"@swapkit/types";function l({liquidityUnits:$,poolUnits:f,runeDepth:g}){let R=z($),B=z(f),x=z(g),Y=R.mul(x),G=B.mul(B).mul(2),M=B.mul(R).mul(2),L=R.mul(R),Q=B.mul(B).mul(B);return Y.mul(G.sub(M).add(L)).div(Q)}function n({liquidityUnits:$,poolUnits:f,assetDepth:g}){let R=z($),B=z(f),x=z(g),Y=R.mul(x),G=B.mul(B).mul(2),M=B.mul(R).mul(2),L=R.mul(R),Q=Y.mul(G.sub(M).add(L)),Z=B.mul(B).mul(B);return Q.div(Z)}function E$({percent:$,runeDepth:f,liquidityUnits:g,poolUnits:R}){return l({liquidityUnits:g,poolUnits:R,runeDepth:f}).mul($)}function I$({percent:$,assetDepth:f,liquidityUnits:g,poolUnits:R}){return n({assetDepth:f,liquidityUnits:g,poolUnits:R}).mul($)}function z($){return P.fromBigInt(BigInt($),d(s.THORChain).baseDecimal)}function p({liquidityUnits:$,poolUnits:f,runeDepth:g,assetDepth:R}){return{assetAmount:z(R).mul($).div(f),runeAmount:z(g).mul($).div(f)}}function T$({liquidityUnits:$,poolUnits:f,runeDepth:g,assetDepth:R,percent:B}){return Object.fromEntries(Object.entries(p({assetDepth:R,liquidityUnits:$,poolUnits:f,runeDepth:g})).map(([x,Y])=>[x,Y.mul(B)]))}function S$({runeDepth:$,poolUnits:f,assetDepth:g,liquidityUnits:R,runeAmount:B,assetAmount:x}){let Y=new P({decimal:8,value:$}),G=new P({decimal:8,value:g}),M=new P({decimal:8,value:f}),L=new P({decimal:8,value:B}),Q=new P({decimal:8,value:x}),Z=L.mul(G),F=Q.mul(Y),O=L.mul(Q),U=Y.mul(G),D=M.mul(Z.add(F.add(O.mul(2)))),y=Z.add(F.add(U.mul(2))),H=D.div(y),W=z(R).add(H);if(H.getBaseValue("number")===0)return W.div(M).getBaseValue("number");let k=M.add(W);return W.div(k).getBaseValue("number")}function q$({runeAmount:$,assetAmount:f,runeDepth:g,assetDepth:R}){if($==="0"||f==="0"||g==="0"||R==="0")return 0;let B=z(g),x=z(R),Y=z(f),G=z($),M=Y.mul(B).sub(x.mul(G)),L=x.mul(G).add(B.mul(x));return Math.abs(M.div(L).getBaseValue("number"))}import{Chain as V}from"@swapkit/types";import{match as t}from"ts-pattern";function U$({type:$,address:f}){return`${$}:${f}`}function D$({address:$,unbondAmount:f}){return`${"UNBOND"}:${$}:${f}`}function y$($){return C("POOL+",$)}function k$({chain:$,symbol:f,address:g,...R}){let B=a({chain:$,symbol:f}),x=g?`:${g}:`:":";return C(`${"+"}:${B}${x}`,R)}function b$({chain:$,symbol:f,ticker:g,basisPoints:R,targetAsset:B}){let x=$==="ETH"&&g!=="ETH"?`${g}-${f.slice(-3)}`:f,Y=B?`:${B}`:"";return`${"-"}:${$}.${x}:${R}${Y}`}function m$({basisPoints:$,...f}){return C(`${"POOL-"}:${$}`,f)}function v$({name:$,chain:f,address:g,owner:R}){let B=`${"~"}:${$}:${f}:${g}`,x=R?`:${R}`:"";return`${B}${x}`}function w$({name:$,chain:f,asset:g,payout:R,owner:B}){return`${"~"}:${$}:${f}:${R}:${B}:${g}`}function c$($,{address:f}){return`${$}:${f}`}function r$($,{unstakeBps:f,...g}){let R=f?`:${f}`:"",B=`${$}${R}`;return C(`${B}`,g)}function C($,{affiliateAddress:f,affiliateBasisPoints:g}={}){let R=`${$}${f?`:${f}:${g||0}`:""}`;return R.endsWith(":")?R.slice(0,-1):R}function a({chain:$,symbol:f}){return t($).with(V.Bitcoin,V.Dogecoin,V.Litecoin,()=>$.slice(0,1).toLowerCase()).with(V.BitcoinCash,()=>"c").otherwise(()=>`${$}.${f}`)}import{getChainConfig as K}from"@swapkit/types";function l$(){return typeof window.ethereum<"u"}function n$($){return $$().includes($)}function $$(){let $=window?.ethereum&&!window.ethereum?.isBraveWallet,f=window?.ctrl||window?.ethereum?.__XDEFI,g=window?.vultisig,R=window?.ethereum?.isBraveWallet,B=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(g)M.push("VULTISIG");if(R)M.push("BRAVE");if(B)M.push("TRUSTWALLET_WEB");if(x)M.push("COINBASE_WEB");if(B$())M.push("OKX_MOBILE");if(Y)M.push("BITGET");if(G)M.push("ONEKEY");return M}async function f$($,f,g){let R=K(f);try{await A({method:"wallet_switchEthereumChain",params:[{chainId:R.chainIdHex}],provider:$})}catch(B){if(!g)throw new _("helpers_failed_to_switch_network",{error:B,reason:"networkParams not provided"});await R$($,g)}}function p$({chains:$,supportedChains:f,walletType:g}){let R=$.filter((x)=>!x||f.includes(x));if(R.length===0)throw new _("wallet_chain_not_supported",{chain:$.join(", "),wallet:g});let B=$.filter((x)=>!f.includes(x));return N({condition:B.length>0,id:`wallet_chain_not_supported_${g}`,warning:`${g} wallet does not support the following chains: ${B.join(", ")}. These chains will be ignored.`}),R}function g$($,f,g){return async(...R)=>{let{chainIdHex:B}=K(g);if((await f.getNetwork()).chainId.toString()===B)return $(...R);try{await f$(f,g)}catch(x){throw new _({errorKey:"helpers_failed_to_switch_network",info:{error:x}})}return $(...R)}}function i$({toolbox:$,chain:f,provider:g=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=g$(M,g,f);return{...Y,[G]:L}},{});return{...$,...x}}function R$($,f){return A({method:"wallet_addEthereumChain",params:[f],provider:$})}function t$($){window.ethereum?.on("accountsChanged",()=>$()),window.ctrl?.ethereum.on("accountsChanged",()=>$())}function a$(){let{isTrust:$,isBraveWallet:f,__XDEFI:g,overrideIsMetaMask:R,selectedProvider:B}=window?.ethereum||{};if($)return"TRUSTWALLET_WEB";if(f)return"BRAVE";if(R&&B?.isCoinbaseWallet)return"COINBASE_WEB";if(g)return"CTRL";if(window?.$onekey?.ethereum)return"ONEKEY";return"METAMASK"}function e$(){let $=[];function f(R){if($.map((B)=>B.info.uuid).includes(R.detail.info.uuid))return;$.push(R.detail)}window.addEventListener("eip6963:announceProvider",f),window.dispatchEvent(new Event("eip6963:requestProvider"));function g(){window.removeEventListener("eip6963:announceProvider",f)}return{providers:$,removeEIP6963EventListener:g}}function B$(){let $=navigator.userAgent,f=/iphone|ipad|ipod|ios/i.test($),g=/android|XiaoMi|MiuiBrowser/i.test($),R=f||g,B=/OKApp/i.test($);return R&&B}function A({provider:$,params:f,method:g}){if(!$?.send)throw new _("helpers_not_found_provider");let R=f?Array.isArray(f)?f:[f]:[];return $.send(g,R)}export{Df as wrapWithThrow,g$ as wrapMethodWithNetworkSwitch,N as warnOnce,pf as validateTNS,nf as validateIdentifier,j as updateDerivationPath,f$ as switchEVMWalletNetwork,Kf as swapKitConfigStore,fg as signWidgetRequest,A as providerRequest,i$ as prepareNetworkSwitch,sf as parseSymbolForAddress,B$ as okxMobileEnabled,$$ as listWeb3EVMWallets,l$ as isWeb3Detected,rf as isGasAsset,n$ as isDetected,vf as initializeRPCUrlsWithFallback,Q$ as getWalletFormatFor,df as getTokenLogoURI,Of as getTHORNameCost,T$ as getSymmetricWithdraw,p as getSymmetricPoolShare,bf as getRPCUrlSync,mf as getRPCUrl,$g as getMinAmountByChain,b$ as getMemoForWithdraw,D$ as getMemoForUnbond,r$ as getMemoForTcyStake,c$ as getMemoForTcyClaim,m$ as getMemoForRunePoolWithdraw,y$ as getMemoForRunePoolDeposit,v$ as getMemoForNameRegister,w$ as getMemoForNamePreferredAssetRegister,U$ as getMemoForLeaveAndBond,k$ as getMemoForDeposit,Uf as getMAYANameCost,q$ as getLiquiditySlippage,v as getFeeMultiplierAsBigInt,I as getFeeMultiplier,C$ as getExplorerTxUrl,W$ as getExplorerAddressUrl,S$ as getEstimatedPoolShare,a$ as getETHDefaultWallet,e$ as getEIP6963Wallets,P$ as getDerivationPathFor,hf as getCommonAssetInfo,yf as getChainIdentifier,E$ as getAsymmetricRuneWithdrawAmount,l as getAsymmetricRuneShare,I$ as getAsymmetricAssetWithdrawAmount,n as getAsymmetricAssetShare,of as getAssetType,tf as formatBigIntToSafeValue,lf as findAssetBy,p$ as filterSupportedChains,cf as fetchTokenInfo,c as derivationPathToString,uf as assetFromString,Y$ as applyFeeMultiplierToBigInt,G$ as applyFeeMultiplier,R$ as addEVMWalletNetwork,t$ as addAccountsChangedCallback,kf as _rpcCache,If as WarningCodeEnum,e as WalletOption,Bg as TxnType,Mg as TxnStatus,Ag as TronTransactionSchema,Tg as TransactionSchema,Sg as TransactionDTOSchema,Yg as TrackingStatus,zg as TrackingRequestSchema,Jg as TrackingRequestQuerySchema,Ig as TrackerResponseSchema,Gg as TokenSchema,Xg as TokenDetailsMetadataSchema,kg as TONTransactionSchema,eg as SwapToResponseSchema,tg as SwapToRequestSchema,ag as SwapToAssetSchema,RR as SwapRouteV2ResponseSchema,P as SwapKitNumber,_ as SwapKitError,BR as SwapKitApi,yg as StarknetTransactionSchema,E as SKConfig,hg as RouteQuoteWarningSchema,Rg as RouteQuoteTxType,fR as RouteQuoteProviderErrorSchema,rg as RouteQuoteMetadataV2Schema,cg as RouteQuoteMetadataSchema,vg as RouteQuoteMetadataAssetSchema,mg as RouteLegWithoutAddressesSchema,bg as RouteLegSchema,Af as RequestClient,ig as QuoteV3ResponseSchema,gR as QuoteV2ResponseSchema,$R as QuoteRouteV2Response,ug as QuoteResponseSchema,og as QuoteResponseRouteItem,_g as QuoteRequestSchema,Tf as ProviderName,xg as ProviderAction,gg as PriorityLabel,Zg as PriceResponseSchema,Vg as PriceRequestSchema,X as NetworkDerivationPath,Eg as NearSwapResponseSchema,Hg as NearDepositChannelResultSchema,Fg as NearDepositChannelParamsSchema,i as MemoType,Nf as LedgerErrorCode,sg as GasSchema,dg as GasResponseSchema,qg as FeesSchema,Sf as FeeTypeEnum,b as FeeOption,Ng as EstimatedTimeSchema,Ef as ErrorCode,Kg as EVMTransactionSchema,Ug as EVMTransactionDetailsSchema,Og as EVMTransactionDetailsParamsSchema,X$ as DerivationPath,jg as DepositChannelResponseSchema,Cg as DepositChannelParamsSchema,m as DEFAULT_FEE_MULTIPLIERS,Dg as CosmosTransactionSchema,wf as CommonAssetStrings,Qg as CoinGeckoMetadataSchema,wg as ChainflipMetadataSchema,Wg as BrokerDepositChannelParamsSchema,af as BigIntArithmetics,Pg as AssetValueSchema,ef as AssetValue,ng as ApproveResponseSchema,lg as ApproveRequestParams,qf as ApproveMode,pg as ApprovalTransactionSchema,Lg as ApiV2ErrorSchema};
1
+ import{$ as Zg,A as hf,Aa as hg,B as of,Ba as og,C as uf,Ca as ug,D as sf,Da as sg,E as df,Ea as dg,F as lf,Fa as lg,G as nf,Ga as ng,H as pf,Ha as pg,I as tf,Ia as ig,J as af,Ja as tg,K as ef,Ka as ag,L as $g,La as eg,M as P,Ma as $R,N as fg,Na as fR,O as gg,Oa as gR,P as Rg,Pa as RR,Q as Bg,Qa as BR,R as xg,S as Mg,T as Yg,U as Gg,V as zg,W as Jg,X as Lg,Y as Pg,Z as Qg,_ as Xg,a as X,aa as _g,b as Ef,ba as Vg,c as If,ca as Cg,d as Tf,da as Wg,e as Sf,ea as jg,f as b,fa as Fg,g as qf,ga as Hg,h as i,ha as Eg,i as e,ia as Ig,j as Nf,ja as Tg,k as Kf,ka as Sg,l as E,la as qg,m as _,ma as Ng,n as Af,na as Kg,o as Of,oa as Ag,p as Uf,pa as Og,q as Df,qa as Ug,r as yf,ra as Dg,s as N,sa as yg,t as kf,ta as kg,u as bf,ua as bg,v as mf,va as mg,w as vf,wa as vg,x as wf,xa as wg,y as cf,ya as cg,z as rf,za as rg}from"./chunk-48as5x5v.js";export*from"@swapkit/tokens";export*from"@swapkit/types";var m={average:1,fast:1.5,fastest:2};function I($="average"){let f=E.get("feeMultipliers");if(f&&f[$]!==void 0)return f[$];return m[$]}function v($="average"){let f=I($),g=10n,R=BigInt(Math.round(f*10));return{denominator:g,numerator:R}}function Y$($,f="average"){let{numerator:g,denominator:R}=v(f);return $*g/R}function G$($,f="average",g=!1){let R=I(f),B=$*R;return g?Math.floor(B):B}import{Chain as T,EVMChains as w}from"@swapkit/types";function j($,f){if("index"in f)return[...$.slice(0,$.length-1),f.index];if("change"in f){let[g,R,B,,x]=$;return[g,R,B,f.change,x]}if("account"in f){let[g,R,,B,x]=$;return[g,R,f.account,B,x]}return $}function c([$,f,g,R,B],{allHardened:x}={}){let Y=x?"'":"",G=typeof B!=="number";if(typeof R!=="number")return`m/${$}'/${f}'/${g}'`;return`m/${$}'/${f}'/${g}'/${R}${Y}${G?"":`/${B}${Y}`}`}function P$({chain:$,index:f,addressIndex:g=0,type:R}){if(w.includes($)){if(R&&["legacy","account"].includes(R))return[44,60,0,f];if(R==="ledgerLive")return[44,60,f,0,g];return j(X[$],{index:f})}if($===T.Solana){if(R==="account")return[44,501,0,f];return j(X[$],{index:f})}let B=$===T.Litecoin?2:0;switch(R){case"nativeSegwitMiddleAccount":return[84,B,f,0,g];case"segwit":return[49,B,0,0,f];case"legacy":return[44,B,0,0,f];default:return j(X[$],{index:f})}}function Q$($){let[f,g,R]=$.split("/").map((B)=>Number.parseInt(B,10));switch(g){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var X$=Object.keys(X).reduce(($,f)=>{return $[f]=c(X[f]),$},{});import{Chain as J,CosmosChains as r,EVMChains as h,getChainConfig as S,SubstrateChains as o,UTXOChains as u}from"@swapkit/types";import{match as q}from"ts-pattern";function C$({chain:$,txHash:f}){let{explorerUrl:g}=S($);return q($).with(...r,J.Solana,()=>`${g}/tx/${f.startsWith("0x")?f.slice(2):f}`).with(...h,...o,()=>`${g}/tx/${f.startsWith("0x")?f:`0x${f}`}`).with(...u,J.Radix,J.Tron,()=>`${g}/transaction/${f.toLowerCase()}`).with(J.Near,()=>`${g}/txns/${f}`).with(J.Ripple,()=>`${g}/transactions/${f}`).with(J.Sui,()=>`${g}/txblock/${f}`).with(J.Cardano,J.HyperCore,J.Ton,()=>`${g}/tx/${f}`).otherwise(()=>"")}function W$({chain:$,address:f}){let{explorerUrl:g}=S($);return q($).with(J.Solana,J.Sui,J.Radix,()=>`${g}/account/${f}`).otherwise(()=>`${g}/address/${f}`)}import{Chain as s,getChainConfig as d}from"@swapkit/types";function l({liquidityUnits:$,poolUnits:f,runeDepth:g}){let R=z($),B=z(f),x=z(g),Y=R.mul(x),G=B.mul(B).mul(2),M=B.mul(R).mul(2),L=R.mul(R),Q=B.mul(B).mul(B);return Y.mul(G.sub(M).add(L)).div(Q)}function n({liquidityUnits:$,poolUnits:f,assetDepth:g}){let R=z($),B=z(f),x=z(g),Y=R.mul(x),G=B.mul(B).mul(2),M=B.mul(R).mul(2),L=R.mul(R),Q=Y.mul(G.sub(M).add(L)),Z=B.mul(B).mul(B);return Q.div(Z)}function E$({percent:$,runeDepth:f,liquidityUnits:g,poolUnits:R}){return l({liquidityUnits:g,poolUnits:R,runeDepth:f}).mul($)}function I$({percent:$,assetDepth:f,liquidityUnits:g,poolUnits:R}){return n({assetDepth:f,liquidityUnits:g,poolUnits:R}).mul($)}function z($){return P.fromBigInt(BigInt($),d(s.THORChain).baseDecimal)}function p({liquidityUnits:$,poolUnits:f,runeDepth:g,assetDepth:R}){return{assetAmount:z(R).mul($).div(f),runeAmount:z(g).mul($).div(f)}}function T$({liquidityUnits:$,poolUnits:f,runeDepth:g,assetDepth:R,percent:B}){return Object.fromEntries(Object.entries(p({assetDepth:R,liquidityUnits:$,poolUnits:f,runeDepth:g})).map(([x,Y])=>[x,Y.mul(B)]))}function S$({runeDepth:$,poolUnits:f,assetDepth:g,liquidityUnits:R,runeAmount:B,assetAmount:x}){let Y=new P({decimal:8,value:$}),G=new P({decimal:8,value:g}),M=new P({decimal:8,value:f}),L=new P({decimal:8,value:B}),Q=new P({decimal:8,value:x}),Z=L.mul(G),F=Q.mul(Y),O=L.mul(Q),U=Y.mul(G),D=M.mul(Z.add(F.add(O.mul(2)))),y=Z.add(F.add(U.mul(2))),H=D.div(y),W=z(R).add(H);if(H.getBaseValue("number")===0)return W.div(M).getBaseValue("number");let k=M.add(W);return W.div(k).getBaseValue("number")}function q$({runeAmount:$,assetAmount:f,runeDepth:g,assetDepth:R}){if($==="0"||f==="0"||g==="0"||R==="0")return 0;let B=z(g),x=z(R),Y=z(f),G=z($),M=Y.mul(B).sub(x.mul(G)),L=x.mul(G).add(B.mul(x));return Math.abs(M.div(L).getBaseValue("number"))}import{Chain as V}from"@swapkit/types";import{match as t}from"ts-pattern";function U$({type:$,address:f}){return`${$}:${f}`}function D$({address:$,unbondAmount:f}){return`${"UNBOND"}:${$}:${f}`}function y$($){return C("POOL+",$)}function k$({chain:$,symbol:f,address:g,...R}){let B=a({chain:$,symbol:f}),x=g?`:${g}:`:":";return C(`${"+"}:${B}${x}`,R)}function b$({chain:$,symbol:f,ticker:g,basisPoints:R,targetAsset:B}){let x=$==="ETH"&&g!=="ETH"?`${g}-${f.slice(-3)}`:f,Y=B?`:${B}`:"";return`${"-"}:${$}.${x}:${R}${Y}`}function m$({basisPoints:$,...f}){return C(`${"POOL-"}:${$}`,f)}function v$({name:$,chain:f,address:g,owner:R}){let B=`${"~"}:${$}:${f}:${g}`,x=R?`:${R}`:"";return`${B}${x}`}function w$({name:$,chain:f,asset:g,payout:R,owner:B}){return`${"~"}:${$}:${f}:${R}:${B}:${g}`}function c$($,{address:f}){return`${$}:${f}`}function r$($,{unstakeBps:f,...g}){let R=f?`:${f}`:"",B=`${$}${R}`;return C(`${B}`,g)}function C($,{affiliateAddress:f,affiliateBasisPoints:g}={}){let R=`${$}${f?`:${f}:${g||0}`:""}`;return R.endsWith(":")?R.slice(0,-1):R}function a({chain:$,symbol:f}){return t($).with(V.Bitcoin,V.Dogecoin,V.Litecoin,()=>$.slice(0,1).toLowerCase()).with(V.BitcoinCash,()=>"c").otherwise(()=>`${$}.${f}`)}import{getChainConfig as K}from"@swapkit/types";function l$(){return typeof window.ethereum<"u"}function n$($){return $$().includes($)}function $$(){let $=window?.ethereum&&!window.ethereum?.isBraveWallet,f=window?.ctrl||window?.ethereum?.__XDEFI,g=window?.vultisig,R=window?.ethereum?.isBraveWallet,B=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(g)M.push("VULTISIG");if(R)M.push("BRAVE");if(B)M.push("TRUSTWALLET_WEB");if(x)M.push("COINBASE_WEB");if(B$())M.push("OKX_MOBILE");if(Y)M.push("BITGET");if(G)M.push("ONEKEY");return M}async function f$($,f,g){let R=K(f);try{await A({method:"wallet_switchEthereumChain",params:[{chainId:R.chainIdHex}],provider:$})}catch(B){if(!g)throw new _("helpers_failed_to_switch_network",{error:B,reason:"networkParams not provided"});await R$($,g)}}function p$({chains:$,supportedChains:f,walletType:g}){let R=$.filter((x)=>!x||f.includes(x));if(R.length===0)throw new _("wallet_chain_not_supported",{chain:$.join(", "),wallet:g});let B=$.filter((x)=>!f.includes(x));return N({condition:B.length>0,id:`wallet_chain_not_supported_${g}`,warning:`${g} wallet does not support the following chains: ${B.join(", ")}. These chains will be ignored.`}),R}function g$($,f,g){return async(...R)=>{let{chainIdHex:B}=K(g);if((await f.getNetwork()).chainId.toString()===B)return $(...R);try{await f$(f,g)}catch(x){throw new _({errorKey:"helpers_failed_to_switch_network",info:{error:x}})}return $(...R)}}function i$({toolbox:$,chain:f,provider:g=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=g$(M,g,f);return{...Y,[G]:L}},{});return{...$,...x}}function R$($,f){return A({method:"wallet_addEthereumChain",params:[f],provider:$})}function t$($){window.ethereum?.on("accountsChanged",()=>$()),window.ctrl?.ethereum.on("accountsChanged",()=>$())}function a$(){let{isTrust:$,isBraveWallet:f,__XDEFI:g,overrideIsMetaMask:R,selectedProvider:B}=window?.ethereum||{};if($)return"TRUSTWALLET_WEB";if(f)return"BRAVE";if(R&&B?.isCoinbaseWallet)return"COINBASE_WEB";if(g)return"CTRL";if(window?.$onekey?.ethereum)return"ONEKEY";return"METAMASK"}function e$(){let $=[];function f(R){if($.map((B)=>B.info.uuid).includes(R.detail.info.uuid))return;$.push(R.detail)}window.addEventListener("eip6963:announceProvider",f),window.dispatchEvent(new Event("eip6963:requestProvider"));function g(){window.removeEventListener("eip6963:announceProvider",f)}return{providers:$,removeEIP6963EventListener:g}}function B$(){let $=navigator.userAgent,f=/iphone|ipad|ipod|ios/i.test($),g=/android|XiaoMi|MiuiBrowser/i.test($),R=f||g,B=/OKApp/i.test($);return R&&B}function A({provider:$,params:f,method:g}){if(!$?.send)throw new _("helpers_not_found_provider");let R=f?Array.isArray(f)?f:[f]:[];return $.send(g,R)}export{Df as wrapWithThrow,g$ as wrapMethodWithNetworkSwitch,N as warnOnce,pf as validateTNS,nf as validateIdentifier,j as updateDerivationPath,f$ as switchEVMWalletNetwork,Kf as swapKitConfigStore,fg as signWidgetRequest,A as providerRequest,i$ as prepareNetworkSwitch,sf as parseSymbolForAddress,B$ as okxMobileEnabled,$$ as listWeb3EVMWallets,l$ as isWeb3Detected,rf as isGasAsset,n$ as isDetected,vf as initializeRPCUrlsWithFallback,Q$ as getWalletFormatFor,df as getTokenLogoURI,Of as getTHORNameCost,T$ as getSymmetricWithdraw,p as getSymmetricPoolShare,bf as getRPCUrlSync,mf as getRPCUrl,$g as getMinAmountByChain,b$ as getMemoForWithdraw,D$ as getMemoForUnbond,r$ as getMemoForTcyStake,c$ as getMemoForTcyClaim,m$ as getMemoForRunePoolWithdraw,y$ as getMemoForRunePoolDeposit,v$ as getMemoForNameRegister,w$ as getMemoForNamePreferredAssetRegister,U$ as getMemoForLeaveAndBond,k$ as getMemoForDeposit,Uf as getMAYANameCost,q$ as getLiquiditySlippage,v as getFeeMultiplierAsBigInt,I as getFeeMultiplier,C$ as getExplorerTxUrl,W$ as getExplorerAddressUrl,S$ as getEstimatedPoolShare,a$ as getETHDefaultWallet,e$ as getEIP6963Wallets,P$ as getDerivationPathFor,hf as getCommonAssetInfo,yf as getChainIdentifier,E$ as getAsymmetricRuneWithdrawAmount,l as getAsymmetricRuneShare,I$ as getAsymmetricAssetWithdrawAmount,n as getAsymmetricAssetShare,of as getAssetType,tf as formatBigIntToSafeValue,lf as findAssetBy,p$ as filterSupportedChains,cf as fetchTokenInfo,c as derivationPathToString,uf as assetFromString,Y$ as applyFeeMultiplierToBigInt,G$ as applyFeeMultiplier,R$ as addEVMWalletNetwork,t$ as addAccountsChangedCallback,kf as _rpcCache,If as WarningCodeEnum,e as WalletOption,Bg as TxnType,Mg as TxnStatus,Ag as TronTransactionSchema,Tg as TransactionSchema,Sg as TransactionDTOSchema,Yg as TrackingStatus,zg as TrackingRequestSchema,Jg as TrackingRequestQuerySchema,Ig as TrackerResponseSchema,Gg as TokenSchema,Xg as TokenDetailsMetadataSchema,kg as TONTransactionSchema,eg as SwapToResponseSchema,tg as SwapToRequestSchema,ag as SwapToAssetSchema,RR as SwapRouteV2ResponseSchema,P as SwapKitNumber,_ as SwapKitError,BR as SwapKitApi,yg as StarknetTransactionSchema,E as SKConfig,hg as RouteQuoteWarningSchema,Rg as RouteQuoteTxType,fR as RouteQuoteProviderErrorSchema,rg as RouteQuoteMetadataV2Schema,cg as RouteQuoteMetadataSchema,vg as RouteQuoteMetadataAssetSchema,mg as RouteLegWithoutAddressesSchema,bg as RouteLegSchema,Af as RequestClient,ig as QuoteV3ResponseSchema,gR as QuoteV2ResponseSchema,$R as QuoteRouteV2Response,ug as QuoteResponseSchema,og as QuoteResponseRouteItem,_g as QuoteRequestSchema,Tf as ProviderName,xg as ProviderAction,gg as PriorityLabel,Zg as PriceResponseSchema,Vg as PriceRequestSchema,X as NetworkDerivationPath,Eg as NearSwapResponseSchema,Hg as NearDepositChannelResultSchema,Fg as NearDepositChannelParamsSchema,i as MemoType,Nf as LedgerErrorCode,sg as GasSchema,dg as GasResponseSchema,qg as FeesSchema,Sf as FeeTypeEnum,b as FeeOption,Ng as EstimatedTimeSchema,Ef as ErrorCode,Kg as EVMTransactionSchema,Ug as EVMTransactionDetailsSchema,Og as EVMTransactionDetailsParamsSchema,X$ as DerivationPath,jg as DepositChannelResponseSchema,Cg as DepositChannelParamsSchema,m as DEFAULT_FEE_MULTIPLIERS,Dg as CosmosTransactionSchema,wf as CommonAssetStrings,Qg as CoinGeckoMetadataSchema,wg as ChainflipMetadataSchema,Wg as BrokerDepositChannelParamsSchema,af as BigIntArithmetics,Pg as AssetValueSchema,ef as AssetValue,ng as ApproveResponseSchema,lg as ApproveRequestParams,qf as ApproveMode,pg as ApprovalTransactionSchema,Lg as ApiV2ErrorSchema};
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/api/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,QAAQ,MAAM,sBAAsB,CAAC;AAEjD,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AAEjC,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBACstH,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CADxpH,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/api/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,QAAQ,MAAM,sBAAsB,CAAC;AAEjD,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AAEjC,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBACsuH,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CADxqH,CAAC"}
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "zustand": "5.0.8"
12
12
  },
13
13
  "description": "SwapKit - Helpers",
14
- "devDependencies": { "@near-js/providers": "2.5.0", "@swapkit/toolboxes": "4.15.8", "ethers": "6.16.0" },
14
+ "devDependencies": { "@near-js/providers": "2.5.0", "@swapkit/toolboxes": "4.15.10", "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.13.5"
44
+ "version": "4.13.7"
45
45
  }