@swapkit/helpers 5.4.0 → 5.4.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # @swapkit/helpers
2
2
 
3
+ ## 5.4.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#404](https://github.com/swapkit/sdk/pull/404) [`ce7f02d`](https://github.com/swapkit/sdk/commit/ce7f02def2c25307c403b20f213a383834ab8bcc) Thanks [@towanTG](https://github.com/towanTG)! - Changes base url for token icons
8
+ - [#401](https://github.com/swapkit/sdk/pull/401) [`7f87112`](https://github.com/swapkit/sdk/commit/7f871121b2949d12de4e5809be7fb544f119dec8) Thanks [@ice-chillios](https://github.com/ice-chillios)! - `generatePhrase` now defaults to a 24-word (256-bit entropy) seed phrase, accepts every BIP39 length (12, 15, 18, 21 or 24 words) and throws `wallet_keystore_invalid_word_count` (21903, added to `@swapkit/helpers`) for anything else instead of silently using 256 bits. New `generateKeystore({ password, wordCount })` creates a phrase and its encrypted keystore in one call; `PhraseWordCount` is exported for wallet-creation UIs offering the choice.
9
+ - [#405](https://github.com/swapkit/sdk/pull/405) [`cbbfdcf`](https://github.com/swapkit/sdk/commit/cbbfdcfbf676855f5bff53547854a725b29f1a7b) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Add public Arc mainnet RPC (`https://rpc.mainnet.arc.io`) as the default `rpcUrls` entry for `Chain.Arc` (via @swapkit/types@1.2.1)
10
+ - [#399](https://github.com/swapkit/sdk/pull/399) [`70749e7`](https://github.com/swapkit/sdk/commit/70749e7899630daabc371a36c498f62b9da1c62f) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/tokens@5.0.8)
11
+
3
12
  ## 5.4.0
4
13
 
5
14
  ### Minor Changes
package/dist/api/index.js CHANGED
@@ -1 +1 @@
1
- import{$ as j,$a as ka,Aa as K,Ba as L,Ca as M,Da as N,Ea as O,Fa as P,Ga as Q,Ha as R,Ia as S,Ja as T,Ka as U,La as V,Ma as W,Na as X,Oa as Y,Pa as Z,Qa as _,Ra as aa,S as a,Sa as ba,T as b,Ta as ca,U as c,Ua as da,V as d,Va as ea,W as e,Wa as fa,X as f,Xa as ga,Y as g,Ya as ha,Z as h,Za as ia,_ as i,_a as ja,aa as k,ab as la,ba as l,bb as ma,ca as m,cb as na,da as n,db as oa,ea as o,fa as p,ga as q,ha as r,ia as s,ja as t,ka as u,la as v,ma as w,na as x,oa as y,pa as z,qa as A,ra as B,sa as C,ta as D,ua as E,va as F,wa as G,xa as H,ya as I,za as J}from"../chunk-jrfr92s5.js";export{j as ApiV2ErrorSchema,da as ApprovalTransactionSchema,ba as ApproveRequestParams,ca as ApproveResponseSchema,k as AssetValueSchema,r as BrokerDepositChannelParamsSchema,U as ChainflipMetadataSchema,l as CoinGeckoMetadataSchema,I as CosmosTransactionSchema,q as DepositChannelParamsSchema,s as DepositChannelResponseSchema,G as EVMTransactionDetailsParamsSchema,H as EVMTransactionDetailsSchema,E as EVMTransactionSchema,A as EstimatedTimeSchema,z as FeesSchema,aa as GasResponseSchema,_ as GasSchema,M as HYPERCORE_USDC_TOKEN_ID,N as HyperCoreEip712TypedDataSchema,O as HyperCoreSendAssetActionSchema,Q as HyperCoreSendAssetTransactionSchema,P as HyperCoreTypedDataTransactionSchema,t as NearDepositChannelParamsSchema,u as NearDepositChannelResultSchema,v as NearSwapResponseSchema,p as PriceRequestSchema,n as PriceResponseSchema,a as PriorityLabel,d as ProviderAction,o as QuoteRequestSchema,Y as QuoteResponseRouteItem,Z as QuoteResponseSchema,ka as QuoteRouteV2Response,ma as QuoteV2ResponseSchema,ga as QuoteV3ResponseSchema,R as RouteLegSchema,S as RouteLegWithoutAddressesSchema,T as RouteQuoteMetadataAssetSchema,V as RouteQuoteMetadataSchema,W as RouteQuoteMetadataV2Schema,la as RouteQuoteProviderErrorSchema,b as RouteQuoteTxType,X as RouteQuoteWarningSchema,J as StarknetTransactionSchema,ea as StellarApprovalTransactionSchema,fa as SwapApprovalTransactionSchema,oa as SwapKitApi,na as SwapRouteV2ResponseSchema,ia as SwapToAssetSchema,ha as SwapToRequestSchema,ja as SwapToResponseSchema,K as TONTransactionMessageSchema,L as TONTransactionSchema,m as TokenDetailsMetadataSchema,g as TokenSchema,w as TrackerResponseSchema,i as TrackingRequestQuerySchema,h as TrackingRequestSchema,f as TrackingStatus,y as TransactionDTOSchema,x as TransactionSchema,F as TronTransactionSchema,e as TxnStatus,c as TxnType,B as isTransactionValue,C as parseTransactionValue,D as toHexTransactionValue};
1
+ import{$ as j,$a as ka,Aa as K,Ba as L,Ca as M,Da as N,Ea as O,Fa as P,Ga as Q,Ha as R,Ia as S,Ja as T,Ka as U,La as V,Ma as W,Na as X,Oa as Y,Pa as Z,Qa as _,Ra as aa,S as a,Sa as ba,T as b,Ta as ca,U as c,Ua as da,V as d,Va as ea,W as e,Wa as fa,X as f,Xa as ga,Y as g,Ya as ha,Z as h,Za as ia,_ as i,_a as ja,aa as k,ab as la,ba as l,bb as ma,ca as m,cb as na,da as n,db as oa,ea as o,fa as p,ga as q,ha as r,ia as s,ja as t,ka as u,la as v,ma as w,na as x,oa as y,pa as z,qa as A,ra as B,sa as C,ta as D,ua as E,va as F,wa as G,xa as H,ya as I,za as J}from"../chunk-dna905ac.js";export{j as ApiV2ErrorSchema,da as ApprovalTransactionSchema,ba as ApproveRequestParams,ca as ApproveResponseSchema,k as AssetValueSchema,r as BrokerDepositChannelParamsSchema,U as ChainflipMetadataSchema,l as CoinGeckoMetadataSchema,I as CosmosTransactionSchema,q as DepositChannelParamsSchema,s as DepositChannelResponseSchema,G as EVMTransactionDetailsParamsSchema,H as EVMTransactionDetailsSchema,E as EVMTransactionSchema,A as EstimatedTimeSchema,z as FeesSchema,aa as GasResponseSchema,_ as GasSchema,M as HYPERCORE_USDC_TOKEN_ID,N as HyperCoreEip712TypedDataSchema,O as HyperCoreSendAssetActionSchema,Q as HyperCoreSendAssetTransactionSchema,P as HyperCoreTypedDataTransactionSchema,t as NearDepositChannelParamsSchema,u as NearDepositChannelResultSchema,v as NearSwapResponseSchema,p as PriceRequestSchema,n as PriceResponseSchema,a as PriorityLabel,d as ProviderAction,o as QuoteRequestSchema,Y as QuoteResponseRouteItem,Z as QuoteResponseSchema,ka as QuoteRouteV2Response,ma as QuoteV2ResponseSchema,ga as QuoteV3ResponseSchema,R as RouteLegSchema,S as RouteLegWithoutAddressesSchema,T as RouteQuoteMetadataAssetSchema,V as RouteQuoteMetadataSchema,W as RouteQuoteMetadataV2Schema,la as RouteQuoteProviderErrorSchema,b as RouteQuoteTxType,X as RouteQuoteWarningSchema,J as StarknetTransactionSchema,ea as StellarApprovalTransactionSchema,fa as SwapApprovalTransactionSchema,oa as SwapKitApi,na as SwapRouteV2ResponseSchema,ia as SwapToAssetSchema,ha as SwapToRequestSchema,ja as SwapToResponseSchema,K as TONTransactionMessageSchema,L as TONTransactionSchema,m as TokenDetailsMetadataSchema,g as TokenSchema,w as TrackerResponseSchema,i as TrackingRequestQuerySchema,h as TrackingRequestSchema,f as TrackingStatus,y as TransactionDTOSchema,x as TransactionSchema,F as TronTransactionSchema,e as TxnStatus,c as TxnType,B as isTransactionValue,C as parseTransactionValue,D as toHexTransactionValue};
@@ -0,0 +1,5 @@
1
+ var an=Object.defineProperty;var ln=(e)=>e;function cn(e,t){this[e]=ln.bind(null,t)}var ze=(e,t)=>{for(var n in t)an(e,n,{get:t[n],enumerable:!0,configurable:!0,set:cn.bind(t,n)})};var Qe=((e)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{Chain as ve,getChainConfig as or}from"@swapkit/types";import{AllChains as jn,Chain as v,EVMChains as Xn,getChainConfig as le}from"@swapkit/types";import{match as Ve}from"ts-pattern";import{Chain as d,EVMChains as Mn,getChainConfig as K,UTXOChains as Ln}from"@swapkit/types";import{match as oe}from"ts-pattern";import{AllChains as tt,Chain as et,getChainConfig as hn,MAYAConfig as fn,StagenetChain as me,StagenetMAYAConfig as nt,StagenetTHORConfig as rt,THORConfig as yn}from"@swapkit/types";import{createStore as bn}from"zustand/vanilla";import{AllChains as dn,getChainConfig as pn}from"@swapkit/types";var Qs=Object.freeze(Object.fromEntries(dn.map((e)=>[e,Object.freeze(pn(e).networkDerivationPath)])));var ie;((l)=>{l.unknownError="unknownError";l.test_error="test_error";l.providerDetailsError="providerDetailsError";l.blockHeaderNotFound="blockHeaderNotFound";l.blockHashNotFoundAtHeight="blockHashNotFoundAtHeight";l.blockHashNotFoundAtHash="blockHashNotFoundAtHash";l.txHashMissing="txHashMissing";l.assetValueMissingInfo="assetValueMissingInfo";l.invalidAsset="invalidAsset";l.blockIsRequired="blockIsRequired";l.currentBlockHeaderNotFound="currentBlockHeaderNotFound";l.failedToRetrieveBalance="failedToRetrieveBalance";l.failedToRetrieveBlock="failedToRetrieveBlock";l.failedToRetrieveFees="failedToRetrieveFees";l.notImplementedBCH="notImplementedBCH";l.notImplementedDoge="notImplementedDoge";l.noPoolsFound="noPoolsFound";l.noVaultsFound="noVaultsFound";l.noTxFound="noTxFound";l.noInputCoinFound="noInputCoinFound";l.noBlockDataFound="noBlockDataFound";l.multipleCosmosMessages="multipleCosmosMessages";l.heightOrHashNotProvided="heightOrHashNotProvided";l.unknownDenom="unknownDenom";l.invalidBlockHeight="invalidBlockHeight";l.timestampExtrinsicNoArgumentsForBlock="timestampExtrinsicNoArgumentsForBlock";l.timestampExtrinsicNoTimestampForBlock="timestampExtrinsicNoTimestampForBlock";l.noTimestampExtrinsicForHash="noTimestampExtrinsicForHash";l.timestampExtrinsicNoArgumentsForHash="timestampExtrinsicNoArgumentsForHash";l.txMemoUndefined="txMemoUndefined";l.txMemoIncorrect="txMemoIncorrect";l.txTypeNotFound="txTypeNotFound";l.txNoMessage="txNoMessage";l.txNotFound="txNotFound";l.txReceiptNotFound="txReceiptNotFound";l.txParsingError="txParsingError";l.txLogsParsingError="txLogsParsingError";l.blockNotFound="blockNotFound";l.balanceNotFound="balanceNotFound";l.configError="configError";l.synthSwapDisallowed="synthSwapDisallowed";l.providerQuoteTimeout="providerQuoteTimeout";l.noQuoteResponse="noQuoteResponse";l.noPoolAssetsFound="noPoolAssetsFound";l.noThorchainPools="noThorchainPools";l.noMayachainPools="noMayachainPools";l.noThorchainNetworkInfo="noThorchainNetworkInfo";l.invalidAffiliateFee="invalidAffiliateFee";l.invalidBuyAssetAddress="invalidBuyAssetAddress";l.invalidSellAssetAddress="invalidSellAssetAddress";l.invalidSourceAddress="invalidSourceAddress";l.invalidDestinationAddress="invalidDestinationAddress";l.sourceAddressIsSmartContract="sourceAddressIsSmartContract";l.destinationAddressIsSmartContract="destinationAddressIsSmartContract";l.invalidChainId="invalidChainId";l.unsupportedChainId="unsupportedChainId";l.unsupportedEVMChainId="unsupportedEVMChainId";l.unsupportedMethod="unsupportedMethod";l.unsupportedProvider="unsupportedProvider";l.invalidParamsForMethod="invalidParamsForMethod";l.unsupportedAdapter="unsupportedAdapter";l.noWhitelistTokens="noWhitelistTokens";l.failedFetchGasPrice="failedFetchGasPrice";l.failedToCreateDepositChannel="failedToCreateDepositChannel";l.noProviderDetailsFound="noProviderDetailsFound";l.noTokenListsFound="noTokenListsFound";l.tokenNotFound="tokenNotFound";l.tokenPriceNotFound="tokenPriceNotFound";l.tokenPriceFailedToUpdate="tokenPriceFailedToUpdate";l.swapAmountTooSmall="swapAmountTooSmall";l.legsArrayIsEmpty="legsArrayIsEmpty";l.failedToFetchQuoteForLeg="failedToFetchQuoteForLeg";l.noBlockHeaderFound="noBlockHeaderFound";l.failedToSimulateSwap="failedToSimulateSwap";l.addressScreeningFailed="addressScreeningFailed";l.noLiquidtyProvidersFound="noLiquidtyProvidersFound";l.insufficientLiquidity="insufficientLiquidity";l.noInboundDataFound="noInbounDataFound";l.noInboundAddressesFound="noInboundAddressesFound";l.noInboundAddressFoundForChain="noInboundAddressFoundForChain";l.noLastBlocksFound="noLastBlocksFound";l.noVersionFound="noVersionFound";l.noConstantsFound="noConstantsFound";l.noMimirsFound="noMimirsFound";l.noRoutesFound="noRoutesFound";l.quoteNotFound="quoteNotFound";l.ledgerSignFailed="ledgerSignFailed";l.ledgerWrongPayload="ledgerWrongPayload";l.ledgerFetchSwapFailed="ledgerFetchSwapFailed";l.failedToFetchTx="failedToFetchTx";l.failedBuildTransactionDetails="failedBuildTransactionDetails";l.noLegsForRoute="noLegsForRoute";l.noRouterAddressFound="noRouterAddressFound";l.noAggregatorAddressFound="noAggregatorAddressFound";l.noContractInstanceFound="noContractInstanceFound";l.noContractAddressFound="noContractAddressFound";l.invalidAffiliate="invalidAffiliate";l.thornameAffiliate="thornameAffiliate";l.providerNotfound="No provider found";l.noRecordFound="No Record found";l.slippageTooLow="Slippage too low";l.tradingHalted="tradingHalted";l.noWrappedGasAsset="noWrappedGasAsset";l.aggregatorAddressNotFound="aggregatorAddressNotFound";l.routerAddressNotFound="routerAddressNotFound";l.dummyAddressNotFound="dummyAddressNotFound";l.trackerError="trackerError";l.thorchainPoolUnavailable="thorchainPoolUnavailable";l.noOhlcvDataFound="noOhlcvDataFound";l.noTradingPairs="noTradingPairs";l.noLendingAvailability="noLendingAvailability";l.lendingRepayTooSmall="lendingRepayTooSmall";l.missingState="missingState";l.ledgerSwapNotFound="ledgerSwapNotFound";l.ledgerSwapNotReadyForTracking="ledgerSwapNotReadyForTracking";l.errorEstimatingGas="errorEstimatingGas";l.apiKeyInvalid="apiKeyInvalid";l.apiKeyFailedToUpdate="apiKeyFailedToUpdate";l.apiKeyExpired="apiKeyExpired";l.unauthorized="unauthorized";l.failedToCreateMemo="failedToCreateMemo";l.radixIncorrectInstructions="radixIncorrectInstructions";l.radixTxMissedParam="radixTxMissedParam";l.radixTxMissedAccount="radixTxMissedAccount";l.radixManifestParseError="radixManifestParseError";l.radixManifestBuildError="radixManifestBuildError";l.invalidAddressForChain="invalidAddressForChain";l.riskyAddress="riskyAddress";l.noRoutesToProcess="noRoutesToProcess";l.sellAssetAmountTooSmall="sellAssetAmountTooSmall";l.missingPrivateKey="missingPrivateKey";l.noMemoPriceProtection="noMemoPriceProtection"})(ie||={});var Pe;((r)=>{r.highSlippage="highSlippage";r.highPriceImpact="highPriceImpact";r.insufficientBalance="insufficientBalance"})(Pe||={});var E;((R)=>{R.CHAINFLIP="CHAINFLIP";R.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";R.JUPITER="JUPITER";R.MAYACHAIN="MAYACHAIN";R.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";R.ONEINCH="ONEINCH";R.PANCAKESWAP="PANCAKESWAP";R.SUSHISWAP_V2="SUSHISWAP_V2";R.THORCHAIN="THORCHAIN";R.THORCHAIN_STREAMING="THORCHAIN_STREAMING";R.TRADERJOE_V2="TRADERJOE_V2";R.UNISWAP_V2="UNISWAP_V2";R.UNISWAP_V3="UNISWAP_V3";R.NEAR="NEAR";R.GARDEN="GARDEN";R.OKX="OKX";R.HARBOR="HARBOR";R.FLASHNET="FLASHNET";R.MAYAN="MAYAN"})(E||={});var Ne;((_)=>{_.LIQUIDITY="liquidity";_.NETWORK="network";_.INBOUND="inbound";_.OUTBOUND="outbound";_.AFFILIATE="affiliate";_.TAX="tax";_.PRIORITY="priority";_.SERVICE="service"})(Ne||={});var un;((r)=>{r.Average="average";r.Fast="fast";r.Fastest="fastest"})(un||={});var gn;((n)=>{n.Approve="approve";n.CheckOnly="checkOnly"})(gn||={});var mn;((w)=>{w.NAME_REGISTER="~";w.BOND="BOND";w.DEPOSIT="+";w.LEAVE="LEAVE";w.UNBOND="UNBOND";w.WITHDRAW="-";w.RUNEPOOL_DEPOSIT="POOL+";w.RUNEPOOL_WITHDRAW="POOL-";w.CLAIM_TCY="tcy";w.STAKE_TCY="tcy+";w.UNSTAKE_TCY="tcy-"})(mn||={});var Je={core_estimated_max_spendable_chain_not_supported:10001,core_extend_error:10002,core_inbound_data_not_found:10003,core_approve_asset_address_or_from_not_found:10004,core_plugin_not_found:10005,core_plugin_swap_not_found:10006,core_approve_asset_target_invalid:10007,core_explorer_unsupported_chain:10008,core_verify_message_not_supported:10009,core_chain_halted:10010,core_wallet_connection_not_found:10101,core_wallet_ctrl_not_installed:10102,core_wallet_evmwallet_not_installed:10103,core_wallet_walletconnect_not_installed:10104,core_wallet_keystore_not_installed:10105,core_wallet_ledger_not_installed:10106,core_wallet_trezor_not_installed:10107,core_wallet_keplr_not_installed:10108,core_wallet_okx_not_installed:10109,core_wallet_keepkey_not_installed:10110,core_wallet_talisman_not_installed:10111,core_wallet_not_keypair_wallet:10112,core_wallet_sign_message_not_supported:10113,core_wallet_connection_failed:10114,core_wallet_create_not_supported:10115,core_wallet_sign_typed_data_not_supported:10116,core_swap_invalid_params:10201,core_swap_route_not_complete:10202,core_swap_asset_not_recognized:10203,core_swap_contract_not_found:10204,core_swap_route_transaction_not_found:10205,core_swap_contract_not_supported:10206,core_swap_transaction_error:10207,core_swap_quote_mode_not_supported:10208,core_transaction_deposit_error:10301,core_transaction_create_liquidity_base_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_base_address:10306,core_transaction_add_liquidity_base_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_invalid_sender_address:10313,core_transaction_deposit_server_error:10314,core_transaction_user_rejected:10315,core_transaction_failed:10316,core_transaction_invalid_recipient_address:10317,wallet_connection_rejected_by_user:20001,wallet_missing_api_key:20002,wallet_chain_not_supported:20003,wallet_missing_params:20004,wallet_provider_not_found:20005,wallet_failed_to_add_or_switch_network:20006,wallet_ledger_connection_error:20101,wallet_ledger_connection_claimed:20102,wallet_ledger_get_address_error:20103,wallet_ledger_device_not_found:20104,wallet_ledger_device_locked:20105,wallet_ledger_transport_error:20106,wallet_ledger_public_key_error:20107,wallet_ledger_derivation_path_error:20108,wallet_ledger_signing_error:20109,wallet_ledger_app_not_open:20110,wallet_ledger_invalid_response:20111,wallet_ledger_method_not_supported:20112,wallet_ledger_invalid_params:20113,wallet_ledger_invalid_signature:20114,wallet_ledger_no_provider:20115,wallet_ledger_pubkey_not_found:20116,wallet_ledger_transport_not_defined:20117,wallet_ledger_webusb_not_supported:20118,wallet_ledger_chain_not_supported:20119,wallet_ledger_invalid_asset:20120,wallet_ledger_invalid_account:20121,wallet_ledger_address_not_found:20122,wallet_ledger_failed_to_get_address:20123,wallet_ledger_webhid_not_supported:20124,wallet_phantom_not_found:20201,wallet_ctrl_not_found:20301,wallet_ctrl_send_transaction_no_address:20302,wallet_ctrl_contract_address_not_provided:20303,wallet_ctrl_asset_not_defined:20304,wallet_walletconnect_project_id_not_specified:20401,wallet_walletconnect_connection_not_established:20402,wallet_walletconnect_namespace_not_supported:20403,wallet_walletconnect_chain_not_supported:20404,wallet_walletconnect_invalid_method:20405,wallet_walletconnect_method_not_supported:20406,wallet_trezor_failed_to_sign_transaction:20501,wallet_trezor_derivation_path_not_supported:20502,wallet_trezor_failed_to_get_address:20503,wallet_trezor_transport_error:20504,wallet_trezor_method_not_supported:20505,wallet_trezor_failed_to_get_public_key:20506,wallet_talisman_not_enabled:20601,wallet_talisman_not_found:20602,wallet_polkadot_not_found:20701,wallet_radix_not_found:20801,wallet_radix_transaction_failed:20802,wallet_radix_invalid_manifest:20803,wallet_radix_method_not_supported:20804,wallet_radix_no_account:20805,wallet_keepkey_not_found:20901,wallet_keepkey_asset_not_defined:20902,wallet_keepkey_contract_address_not_provided:20903,wallet_keepkey_send_transaction_no_address:20904,wallet_keepkey_derivation_path_error:20905,wallet_keepkey_signing_error:20906,wallet_keepkey_transport_error:20907,wallet_keepkey_unsupported_chain:20908,wallet_keepkey_invalid_response:20909,wallet_keepkey_chain_not_supported:20910,wallet_keepkey_signer_not_found:20911,wallet_keepkey_no_accounts:20912,wallet_keepkey_method_not_supported:20913,wallet_keepkey_invalid_params:20914,wallet_keepkey_config_not_found:20915,wallet_keepkey_no_provider:20916,wallet_keepkey_account_not_found:20917,wallet_keepkey_failed_to_get_public_key:20918,wallet_bitkeep_not_found:21001,wallet_bitkeep_failed_to_switch_network:21002,wallet_bitkeep_no_accounts:21003,wallet_passkeys_sign_transaction_error:21101,wallet_passkeys_not_found:21102,wallet_passkeys_no_address:21103,wallet_passkeys_request_canceled:21104,wallet_passkeys_signature_canceled:21105,wallet_passkeys_failed_to_switch_network:21106,wallet_passkeys_chain_not_supported:21107,wallet_passkeys_instance_missing:21108,wallet_onekey_not_found:21201,wallet_onekey_sign_transaction_error:21202,wallet_okx_not_found:21301,wallet_okx_chain_not_supported:21302,wallet_okx_failed_to_switch_network:21303,wallet_okx_no_accounts:21304,wallet_keplr_not_found:21401,wallet_keplr_chain_not_supported:21402,wallet_keplr_signer_not_found:21403,wallet_keplr_no_accounts:21404,wallet_cosmostation_not_found:21501,wallet_cosmostation_chain_not_supported:21502,wallet_cosmostation_evm_provider_not_found:21503,wallet_cosmostation_keplr_provider_not_found:21504,wallet_cosmostation_no_accounts:21505,wallet_cosmostation_no_evm_accounts:21506,wallet_cosmostation_no_evm_address:21507,wallet_cosmostation_signer_not_found:21508,wallet_passkey_not_supported:21601,wallet_passkey_connection_failed:21602,wallet_coinbase_not_found:21701,wallet_coinbase_chain_not_supported:21702,wallet_coinbase_method_not_supported:21703,wallet_coinbase_no_accounts:21704,wallet_evm_extensions_failed_to_switch_network:21801,wallet_evm_extensions_no_provider:21802,wallet_evm_extensions_not_found:21803,wallet_keystore_invalid_password:21901,wallet_keystore_unsupported_version:21902,wallet_keystore_invalid_word_count:21903,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_evm_nonce_conflict:50218,toolbox_evm_tx_already_known:50219,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_utxo_unsupported_script_type:50315,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_hypercore_payload_mismatch:51002,toolbox_hypercore_insufficient_balance:51003,toolbox_hypercore_destination_sanctioned:51004,toolbox_hypercore_transfer_hash_not_found:51005,toolbox_hypercore_pre_transfer_check_failed:51006,toolbox_cardano_sign_transaction_failed:50901,toolbox_near_no_signer:90601,toolbox_near_invalid_address:90602,toolbox_near_invalid_amount:90603,toolbox_near_transfer_failed:90604,toolbox_near_access_key_error:90605,toolbox_near_no_rpc_url:90606,toolbox_near_empty_batch:90607,toolbox_near_balance_failed:90608,toolbox_near_invalid_name:90609,toolbox_near_missing_contract_address:90610,toolbox_near_no_account:90611,toolbox_near_invalid_gas_params:90612,toolbox_near_no_public_key_found:90613,toolbox_near_sign_transaction_failed:90614,toolbox_sui_address_required:90701,toolbox_sui_keypair_required:90702,toolbox_sui_balance_error:90703,toolbox_sui_transaction_creation_error:90704,toolbox_sui_signing_error:90705,toolbox_sui_broadcast_error:90706,toolbox_sui_no_signer:90707,toolbox_sui_no_sender:90708,toolbox_sui_missing_coin_type:90709,toolbox_sui_no_coins_found:90710,toolbox_sui_insufficient_balance:90711,toolbox_starknet_no_signer:90801,toolbox_starknet_invalid_address:90802,toolbox_starknet_fee_estimation_failed:90803,toolbox_starknet_account_not_deployed:90804,toolbox_starknet_transaction_failed:90805,toolbox_ton_no_signer:90901,toolbox_ton_invalid_address:90902,toolbox_ton_missing_jetton_address:90903,toolbox_ton_jetton_transfer_failed:90904,toolbox_ton_transaction_failed:90905,toolbox_aptos_address_required:91001,toolbox_aptos_keypair_required:91002,toolbox_aptos_balance_error:91003,toolbox_aptos_transaction_creation_error:91004,toolbox_aptos_signing_error:91005,toolbox_aptos_broadcast_error:91006,toolbox_aptos_no_signer:91007,toolbox_aptos_no_sender:91008,toolbox_aptos_missing_asset_type:91009,toolbox_aptos_insufficient_balance:91010,toolbox_stellar_no_signer:91101,toolbox_stellar_broadcast_error:91102,toolbox_stellar_invalid_address:91103,toolbox_stellar_account_not_found:91104,toolbox_stellar_transaction_failed:91105,toolbox_stellar_balance_error:91106,toolbox_stellar_trustline_asset_invalid:91112,toolbox_aleo_no_signer:91201,toolbox_aleo_invalid_address:91202,toolbox_aleo_balance_error:91203,toolbox_aleo_fee_estimation_failed:91204,toolbox_aleo_broadcast_error:91205,toolbox_aleo_transaction_failed:91206,toolbox_aleo_wasm_init_failed:91207,toolbox_aleo_unsupported_token:91208,toolbox_aleo_token_transfer_rejected:91209,toolbox_aleo_insufficient_fee_balance:91210,toolbox_aleo_no_unspent_records:91211,toolbox_aleo_conflicting_signers:91212,toolbox_aleo_no_rpc_urls:91213,toolbox_not_supported:59901,toolbox_fee_estimation_failed:59902,toolbox_sweep_amount_too_low:59903,toolbox_derivation_slot_unsupported:59904,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,plugin_swapkit_stellar_destination_wallet_not_found:43003,plugin_swapkit_unsupported_tx_type:43004,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 ke(e){return JSON.stringify(e,(t,n)=>typeof n==="bigint"?n.toString():n)}class b extends Error{static ErrorCode=Je;errorKey;info;constructor(e,t){let n=typeof e==="string",r=n?e:e.errorKey,s=n?void 0:e.info,a=`${r}${s?`: ${ke(s)}`:""}`;super(a);if(Object.setPrototypeOf(this,b.prototype),this.name="SwapKitError",this.errorKey=r,this.info=s,this.cause=t,t){let c=t instanceof Error?`${t.message}${t.cause?` (${t.cause})`:""}`:ke(t);console.error(`SwapKitError [${r}]: ${c}`)}else if(s)console.error(`SwapKitError [${r}]: ${ke(s)}`)}}function ti(e){let t=Je;for(let[n,r]of Object.entries(e)){if(Object.hasOwn(t,n)){if(t[n]===r)continue;throw new b({errorKey:"helpers_invalid_params",info:{code:r,existingCode:t[n],key:n}})}let s=Object.keys(t).find((a)=>t[a]===r);if(s)throw new b({errorKey:"helpers_invalid_params",info:{code:r,existingKey:s,key:n}});t[n]=r}}var ge={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",PASSKEY_WALLET:"PASSKEY_WALLET",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",WALLET_SELECTOR:"WALLET_SELECTOR",WALLETCONNECT:"WALLETCONNECT",XAMAN:"XAMAN"},Oe=new Set;function Ze(e){return Oe.add(e),()=>Oe.delete(e)}function si(e,t){let n=ge;if(Object.hasOwn(n,e)){if(n[e]===t)return;throw new b({errorKey:"helpers_invalid_params",info:{existingValue:n[e],key:e,value:t}})}n[e]=t;for(let r of Oe)r(t)}var _n;((r)=>{r[r.NoError=36864]="NoError";r[r.LockedDevice=21781]="LockedDevice";r[r.TC_NotFound=65535]="TC_NotFound"})(_n||={});var An=tt.reduce((e,t)=>{if(!e.THOR_STAGENET)e[me.Maya]=nt.rpcUrls,e[me.THORChain]=rt.rpcUrls;return e[t]=hn(t).rpcUrls,e},{}),Sn={[et.THORChain]:yn.nodeUrl,[et.Maya]:fn.nodeUrl,[me.THORChain]:rt.nodeUrl,[me.Maya]:nt.nodeUrl},st={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:tt,endpoints:{},envs:{apiUrl:"https://api.swapkit.dev",devApiUrl:"https://dev-api.swapkit.dev",isDev:!1,isStagenet:!1},feeMultipliers:void 0,integrations:{radix:{applicationName:"Swapkit Playground",applicationVersion:"0.0.1",dAppDefinitionAddress:"account_rdx128r289p58222hcvev7frs6kue76pl7pdcnw8725aw658v0zggkh9ws",network:{dashboardBase:"https://dashboard.radixdlt.com",networkId:1,networkName:"mainnet"}}},localMode:{enabled:!1,quoteUrl:"http://localhost:3000",swapUrl:"http://localhost:3001"},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:An,thornodeUrls:Sn,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(ge),widgetId:"",widgetKey:""},P=bn((e)=>({...st,setApiKey:(t,n)=>e((r)=>({apiKeys:{...r.apiKeys,[t]:n}})),setConfig:(t)=>e((n)=>({apiKeys:{...n.apiKeys,...t?.apiKeys},chains:n.chains.concat(t?.chains||[]),endpoints:{...n.endpoints,...t?.endpoints},envs:{...n.envs,...t?.envs},feeMultipliers:t?.feeMultipliers||n.feeMultipliers,integrations:{...n.integrations,...t?.integrations},localMode:{...n.localMode,...t?.localMode},rpcUrls:{...n.rpcUrls,...t?.rpcUrls},thornodeUrls:{...n.thornodeUrls,...t?.thornodeUrls},v3SwapFlow:{...n.v3SwapFlow,...t?.v3SwapFlow},wallets:n.wallets.concat(t?.wallets||[]),widgetId:t?.widgetId||n.widgetId,widgetKey:t?.widgetKey||n.widgetKey})),setEndpoint:(t,n)=>e((r)=>({endpoints:{...r.endpoints,[t]:n}})),setEnv:(t,n)=>e((r)=>({envs:{...r.envs,[t]:n}})),setFeeMultipliers:(t)=>e(()=>({feeMultipliers:t})),setIntegrationConfig:(t,n)=>e((r)=>({integrations:{...r.integrations,[t]:n}})),setRequestOptions:(t)=>e((n)=>({requestOptions:{retry:{...n.requestOptions.retry,...t.retry},timeoutMs:t.timeoutMs||n.requestOptions.timeoutMs}})),setRpcUrl:(t,n)=>e((r)=>({rpcUrls:{...r.rpcUrls,[t]:n}})),setThornodeUrl:(t,n)=>e((r)=>({thornodeUrls:{...r.thornodeUrls,[t]:n}})),setWidgetId:(t)=>e({widgetId:t}),setWidgetKey:(t)=>e({widgetKey:t})}));Ze((e)=>{P.setState((t)=>t.wallets.includes(e)?t:{wallets:[...t.wallets,e]})});var T={get:(e)=>P.getState()[e],getState:P.getState,reinitialize:()=>P.setState({...st,wallets:Object.values(ge)}),set:(e)=>P.getState().setConfig(e),setApiKey:(e,t)=>P.getState().setApiKey(e,t),setEndpoint:(e,t)=>P.getState().setEndpoint(e,t),setEnv:(e,t)=>P.getState().setEnv(e,t),setFeeMultipliers:(e)=>P.getState().setFeeMultipliers(e),setIntegrationConfig:(e,t)=>P.getState().setIntegrationConfig(e,t),setRequestOptions:(e)=>P.getState().setRequestOptions(e),setRpcUrl:(e,t)=>P.getState().setRpcUrl(e,t),setThornodeUrl:(e,t)=>P.getState().setThornodeUrl(e,t),setWidgetId:(e)=>P.getState().setWidgetId(e),setWidgetKey:(e)=>P.getState().setWidgetKey(e)};var Tn=(e)=>new Promise((t)=>setTimeout(t,e)),wn=(e,{baseDelay:t,backoffMultiplier:n,maxDelay:r})=>Math.min(t*n**e,r);function xn(e,t){if(e instanceof Error&&e.name==="AbortError")return!0;if(e instanceof TypeError)return!0;if(t===429)return!0;if(t&&t>=500&&t<600)return!0;return!1}var Rn=async(e,t)=>{let n=await fetch(e,t),r;try{r=await n.json()}catch{if(!n.ok)throw new b({errorKey:"helpers_invalid_response",info:{status:n.status,statusText:n.statusText}},{status:n.status,statusText:n.statusText});return{}}if(!n.ok){let a={data:r?.data,error:r?.error,message:r?.message,status:n.status};throw new b({errorKey:r?.error||"helpers_invalid_response",info:a},a)}let s=r?.routes?.length||r?.result||r?.data&&!r?.error;if(r?.error&&!s){let a={data:r.data,error:r.error,message:r.message,status:n.status};throw new b({errorKey:r.error,info:a},a)}if(r?.providerErrors?.length||r?.error&&s)console.warn("[SwapKit] Partial errors in response:",r.providerErrors||r.error);return r};function _e(e,t={}){return async function(r,s={}){let{searchParams:a,json:c,body:u,headers:_,dynamicHeader:A,retry:y,timeoutMs:w,abortController:O,onError:S,onSuccess:M,responseHandler:I,...C}={...t,...s},ne=T.get("requestOptions"),re={...ne.retry,...y},R=!!c||r.endsWith(".json"),Ye=Cn(r,a),se=A?await A():{},q=vn(R,{..._,...se}),sn=R?JSON.stringify(c):u,Ee;for(let ue=0;ue<=re.maxRetries;ue++){let je=O||new AbortController,Xe=setTimeout(()=>je.abort(),w||ne.timeoutMs);try{let V=await Rn(Ye,{...C,body:sn,headers:q,method:e,signal:je.signal});return clearTimeout(Xe),M?.(V)||I?.(V)||V}catch(V){clearTimeout(Xe),Ee=V;let on=V?.cause?.status;if(ue>=re.maxRetries||!xn(V,on))return S?S(V):Promise.reject(V);await Tn(wn(ue,re))}}return S?S(Ee):Promise.reject(Ee)}}function vn(e,t){return{...t,...e&&{"Content-Type":"application/json"}}}function Cn(e,t){let n=new URL(e);if(t)n.search=new URLSearchParams(t).toString();return n.toString()}var m={extend:(e)=>({extend:(t)=>m.extend({...e,...t}),get:_e("GET",e),post:_e("POST",e)}),get:_e("GET"),post:_e("POST")};async function it(e,t,n,r){let s=`${t}:${n}:${r}`,a=new TextEncoder,c=await crypto.subtle.importKey("raw",a.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),u=await crypto.subtle.sign("HMAC",c,a.encode(s));return Array.from(new Uint8Array(u)).map((_)=>_.toString(16).padStart(2,"0")).join("")}import{Chain as f,CosmosChains as ct,EVMChains as dt,getChainConfig as pt,StagenetChains as In,SubstrateChains as En,UTXOChains as ut}from"@swapkit/types";import{match as he}from"ts-pattern";function Ai(e,t){try{return e()}catch(n){if(t)throw new b(t,n);return}}var ot=new Set;function Y({condition:e,id:t,warning:n}){if(e){if(ot.has(t))return;console.warn(n),ot.add(t)}}function Pn(e){return he(e).with(...dt,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...ut,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...ct,...In,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(f.Polkadot,f.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(f.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(f.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(f.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(f.Aleo,f.Aptos,f.Tron,f.Radix,f.Stellar,()=>"").with(f.Hype,()=>({type:"meta"})).with(f.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(f.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(f.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new b("helpers_chain_not_supported",{chain:e})})}function at(e){return he(e).with(f.Aptos,()=>"/-/healthy").with(f.Aleo,()=>"/mainnet/block/height/latest").with(f.Hype,()=>"/info").with(f.Radix,()=>"/status/network-configuration").with(f.Stellar,()=>"").with(f.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function lt(e,t){try{let n=t.startsWith("wss")?t.replace("wss","https"):t;if(e===f.Aleo||e===f.Stellar)return(await fetch(`${n}${at(e)}`,{cache:"no-store",method:"GET",signal:AbortSignal.timeout(3000)})).ok;return(await fetch(`${n}${at(e)}`,{body:JSON.stringify(Pn(e)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var De=new Map,Nn=120000;function kn(e){let[t=""]=T.get("rpcUrls")[e];if(!t)throw Y({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 ${e}.`}),new b("helpers_chain_no_public_or_set_rpc_url",{chain:e});let n=De.get(e);if(n&&Date.now()-n.timestamp<Nn)return n.url;return De.set(e,{timestamp:Date.now(),url:t}),t}async function j(e){let t=kn(e),[,...n]=T.get("rpcUrls")[e];if(await lt(e,t))return t;for(let s of n)if(await lt(e,s))return De.set(e,{timestamp:Date.now(),url:s}),s;throw new b("helpers_chain_rpc_connection_failed",{chain:e,fallbackUrls:n,primaryRpcUrl:t})}function Ci(e){Y({condition:!0,id:"initializeRPCUrlsWithFallback",warning:"initializeRPCUrlsWithFallback is deprecated. Use static { rpcUrls, fallbackRpcUrls } SwapKit init config or dynamic SKConfig.setRpcUrl/setFallbackRpcUrl to configure RPC endpoints."})}function Ii({chain:e,txHash:t}){let{explorerUrl:n}=pt(e);return he(e).with(...ct,f.Solana,()=>`${n}/tx/${t.startsWith("0x")?t.slice(2):t}`).with(...dt,...En,()=>`${n}/tx/${t.startsWith("0x")?t:`0x${t}`}`).with(...ut,f.Radix,f.Tron,()=>`${n}/transaction/${t.toLowerCase()}`).with(f.Near,()=>`${n}/txns/${t}`).with(f.Ripple,()=>`${n}/transactions/${t}`).with(f.Stellar,()=>`${n}/explorer/public/tx/${t}`).with(f.Sui,()=>`${n}/txblock/${t}`).with(f.Cardano,f.Hype,f.Spark,f.Ton,()=>`${n}/tx/${t}`).otherwise(()=>"")}function Ei({chain:e,address:t}){let{explorerUrl:n}=pt(e);return he(e).with(f.Solana,f.Sui,f.Radix,()=>`${n}/account/${t}`).with(f.Stellar,()=>`${n}/explorer/public/account/${t}`).otherwise(()=>`${n}/address/${t}`)}function Pi(e){switch(e){case f.THORChain:return`${e}.RUNE`;case f.Cosmos:return`${e}.ATOM`;case f.BinanceSmartChain:return`${e}`;default:return`${e}.${e}`}}import{keccak_256 as On}from"@noble/hashes/sha3.js";import{bytesToHex as Dn}from"@noble/hashes/utils.js";var gt=/^(0x)?[0-9a-fA-F]{40}$/;function fe(e){if(typeof e!=="string"||!gt.test(e))throw Error(`invalid address: ${e}`);let t=e.toLowerCase().replace(/^0x/,""),n=Dn(On(new TextEncoder().encode(t))),r=[...t].map((a,c)=>Number.parseInt(n[c]??"0",16)>=8?a.toUpperCase():a).join(""),s=e.replace(/^0x/,"");if(/[A-F]/.test(s)&&/[a-f]/.test(s)&&s!==r)throw Error(`bad address checksum: ${e}`);return`0x${r}`}function mt(e){if(typeof e!=="string"||!gt.test(e))return!1;try{return fe(e),!0}catch{return!1}}var Bi=[`${d.Maya}.MAYA`,`${d.Maya}.CACAO`,`${d.Ethereum}.THOR`,`${d.Ethereum}.vTHOR`,`${d.Kujira}.USK`,`${d.Ethereum}.FLIP`,`${d.Radix}.XRD`],ft=[d.Arbitrum,d.Aurora,d.Base,d.Ethereum,d.Optimism,d.Robinhood];async function Hn(e){let{baseDecimal:t}=K(d.Radix);try{let n=await j(d.Radix),{manager:r}=await m.post(`${n}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:e}),headers:{Accept:"*/*","Content-Type":"application/json"}});return r?.divisibility?.value?.divisibility}catch(n){let r=n instanceof Error?n.message:String(n);return console.warn(`Failed to fetch Radix asset decimals for ${e}: ${r}`),t}}async function Vn(e){try{let t=await j(d.Radix);return(await m.post(`${t}/state/entity/details`,{body:JSON.stringify({addresses:[e],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((s)=>s.key==="symbol")?.value.typed.value||void 0}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`Failed to fetch Radix asset symbol for ${e}: ${n}`),""}}async function yt({chain:e,address:t,methodHex:n,id:r}){let s=await j(e);return m.post(s,{body:JSON.stringify({id:r,jsonrpc:"2.0",method:"eth_call",params:[{data:n,to:t.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}function Un(e){if(!e||e==="0x")return"UNKNOWN";try{return bt(e.replace(/^0x/,""))?.trim()||"UNKNOWN"}catch(t){return console.warn(`Failed to decode ABI string from ${e}: ${t}`),"UNKNOWN"}}function $n(e,t){if(!e||e==="0x")return t;try{return Number(e)}catch(n){return console.warn(`Failed to decode ABI uint8 from ${e}: ${n}`),t}}async function Bn({chain:e,address:t}){let{baseDecimal:n}=K(e),r=t.toLowerCase();if(t===""||!r.startsWith("0x"))return n;let s=await yt({address:t,chain:e,id:2,methodHex:"0x313ce567"}).catch((c)=>(console.warn(`Could not fetch decimals for ${t} on ${e}: ${c.message}`),{result:""}));return $n(s.result,n)}async function Fn({chain:e,address:t}){let n=t.toLowerCase();if(n===""||!n.startsWith("0x"))return;let r=await yt({address:t,chain:e,id:1,methodHex:"0x95d89b41"}).catch((a)=>(console.warn(`Could not fetch symbol for ${t} on ${e}: ${a.message}`),{result:""}));return Un(r.result)}async function _t({rpcUrl:e,contractAddress:t,functionSelector:n}){return(await m.post(`${e}/wallet/triggerconstantcontract`,{body:JSON.stringify({contract_address:t,function_selector:n,owner_address:t,parameter:"",visible:!0}),headers:{accept:"application/json","content-type":"application/json"}}).catch(()=>{return}))?.constant_result?.[0]}function ht(e){let t=e.match(/.{2}/g)?.map((n)=>Number.parseInt(n,16))??[];return new TextDecoder().decode(new Uint8Array(t))}function bt(e){return oe(e).with(void 0,()=>{return}).when((t)=>t.length>=128,(t)=>{let n=Number.parseInt(t.slice(64,128),16),r=t.slice(128,128+n*2).replace(/(00)+$/,"");return r?ht(r):void 0}).when((t)=>t.length===64,(t)=>{let n=t.replace(/(00)+$/,"");if(n.length>0&&n.length%2===0)return ht(n);return}).otherwise(()=>{return})}function At({chain:e,address:t}){let{baseDecimal:n}=K(e),r={decimals:n,ticker:void 0};return oe(e).with(...Mn,async()=>{try{if(!mt(t.replace(/^0X/,"0x")))return r;let[s,a]=await Promise.all([Fn({address:t,chain:e}),Bn({address:t,chain:e})]);return{decimals:a,ticker:s}}catch(s){return console.warn(`Failed to fetch token info for ${t} on ${e}: ${s?.code} ${s?.message}`),r}}).with(d.Solana,async()=>{if(!t)return r;try{let s=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${t}`);if(s.ok){let a=await s.json(),c=Array.isArray(a)?a[0]:a;if(c)return{decimals:c.decimals??n,ticker:c.symbol||void 0}}}catch(s){console.warn(`Failed to fetch Solana token info for ${t}: ${s?.code} ${s?.message}`)}return r}).with(d.Tron,async()=>{if(!t)return r;try{let s=await j(d.Tron),[a,c]=await Promise.all([_t({contractAddress:t,functionSelector:"symbol()",rpcUrl:s}),_t({contractAddress:t,functionSelector:"decimals()",rpcUrl:s})]),u=bt(a);return{decimals:a!==void 0&&c?Number(BigInt(`0x${c}`)):n,ticker:u}}catch(s){let a=s instanceof Error?s.message:String(s);return console.warn(`Failed to fetch Tron token info for ${t}: ${a}`),r}}).with(d.Near,async()=>{if(!t)return r;try{let s=await j(d.Near),a=await m.post(s,{body:JSON.stringify({id:"dontcare",jsonrpc:"2.0",method:"query",params:{account_id:t,args_base64:"e30=",finality:"final",method_name:"ft_metadata",request_type:"call_function"}}),headers:{accept:"application/json","content-type":"application/json"}});if(!a.result?.result)throw Error("NEAR ft_metadata returned no result");let c=JSON.parse(new TextDecoder().decode(new Uint8Array(a.result.result)));return{decimals:c?.decimals||n,ticker:c?.symbol}}catch(s){let a=s instanceof Error?s.message:String(s);return console.warn(`Failed to fetch Near token info for ${t}: ${a}`),r}}).with(d.Radix,async()=>{if(!t)return r;try{let[s,a]=await Promise.all([Vn(t),Hn(t)]);return{decimals:a,ticker:s}}catch(s){let a=s instanceof Error?s.message:String(s);return console.warn(`Failed to fetch Radix token info for ${t}: ${a}`),r}}).otherwise(async()=>r)}function St({chain:e,symbol:t}){return oe(e).with(...ft,()=>t==="ETH").with(d.Arc,()=>t==="USDC").with(d.Avalanche,()=>t==="AVAX").with(d.Berachain,()=>t==="BERA").with(d.Hyperevm,()=>t==="HYPE").with(d.Hype,()=>t==="HYPE").with(d.Spark,()=>t==="BTC").with(d.BinanceSmartChain,()=>t==="BNB").with(d.Gnosis,()=>t==="xDAI"||t==="XDAI").with(d.Monad,()=>t==="MON").with(d.XLayer,()=>t==="OKB").with(d.Maya,()=>t==="CACAO").with(d.Cosmos,()=>t==="ATOM").with(d.THORChain,()=>t==="RUNE").with(d.Tron,()=>t==="TRX").with(d.Ripple,()=>t==="XRP").with(d.Ton,()=>t==="GRAM"||t==="TON").with(d.Radix,()=>`${e}.${t}`===ye(e).identifier).otherwise(()=>t===e)}var ye=(e)=>{let{baseDecimal:t}=K(e);return oe(e.toUpperCase()).with(...ft,(r)=>({decimal:t,identifier:`${r}.ETH`})).with(d.Arc,(r)=>({decimal:t,identifier:`${r}.USDC`})).with(d.THORChain,(r)=>({decimal:t,identifier:`${r}.RUNE`})).with(d.Cosmos,(r)=>({decimal:t,identifier:`${r}.ATOM`})).with(d.Maya,(r)=>({decimal:10,identifier:`${r}.CACAO`})).with(d.BinanceSmartChain,(r)=>({decimal:t,identifier:`${r}.BNB`})).with(d.Monad,(r)=>({decimal:t,identifier:`${r}.MON`})).with(d.Avalanche,(r)=>({decimal:t,identifier:`${r}.AVAX`})).with(d.Gnosis,(r)=>({decimal:t,identifier:`${r}.xDAI`})).with(d.XLayer,(r)=>({decimal:t,identifier:`${r}.OKB`})).with(d.Berachain,(r)=>({decimal:t,identifier:`${r}.BERA`})).with(d.Hyperevm,(r)=>({decimal:t,identifier:`${r}.HYPE`})).with(d.Hype,(r)=>({decimal:t,identifier:`${r}.HYPE`})).with(d.Spark,(r)=>({decimal:t,identifier:`${r}.BTC`})).with(d.Tron,(r)=>({decimal:t,identifier:`${r}.TRX`})).with(d.Ton,(r)=>({decimal:t,identifier:`${r}.GRAM`})).with(d.Solana,d.Chainflip,d.Kujira,d.Ripple,d.Polkadot,d.Near,...Ln,(r)=>({decimal:t,identifier:`${r}.${r}`})).with(d.Radix,"XRD.XRD",()=>({decimal:t,identifier:"XRD.XRD"})).with(d.Polygon,"POL.POL",()=>({decimal:t,identifier:"POL.POL"})).with("KUJI.USK",(r)=>({decimal:6,identifier:r})).with("ETH.FLIP",()=>({decimal:K(d.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:K(d.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:K(d.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(r)=>({decimal:10,identifier:r})).with("MAYA.MAYA",(r)=>({decimal:4,identifier:r})).otherwise(()=>({decimal:t,identifier:e}))};function Me({chain:e,symbol:t}){if(t.includes("/"))return"Synth";if(t.includes("~"))return"Trade";return oe(e).with(d.Radix,()=>t===d.Radix||`${e}.${t}`===ye(e).identifier).with(d.Arbitrum,d.Optimism,d.Base,d.Aurora,d.Robinhood,()=>t===d.Ethereum).with(d.Arc,()=>t==="USDC").with(d.Cosmos,()=>t==="ATOM").with(d.BinanceSmartChain,()=>t==="BNB").with(d.Maya,()=>t==="CACAO").with(d.Monad,()=>t==="MON").with(d.THORChain,()=>t==="RUNE").with(d.Tron,()=>t==="TRX").with(d.Hyperevm,()=>t==="HYPE").with(d.Hype,()=>t==="HYPE").with(d.Spark,()=>t==="BTC").with(d.XLayer,()=>t==="OKB").with(d.Ton,()=>t==="GRAM"||t==="TON").otherwise(()=>t===e)?"Native":e}var W=(e)=>{let[t,...n]=e.split("."),r=e.includes("/"),s=n.join("."),a=s?.split("-"),c=a?.length?a.length===1?a[0]:a.slice(0,-1).join("-"):void 0;return{chain:t,symbol:s,synth:r,ticker:c}};function ae(e,t){let r=t===d.Near?e.indexOf("-"):e.lastIndexOf("-");if(r===-1)return{address:void 0,ticker:e};return{address:e.slice(r+1),ticker:e.slice(0,r)}}function Fi(e){return`https://tokens.swapkit.dev/images/${e.toLowerCase()}.png`}async function Ki(e){let{loadTokenLists:t}=await import("./tokens.js"),n=await t(void 0,{source:T.get("envs").isDev?"dev":"prod"}),r=Object.values(n).flatMap((a)=>a.tokens);if("identifier"in e)return r.find((a)=>a.identifier===e.identifier)?.identifier;let s=e.contract.toLowerCase();for(let a of r){let{chain:c,symbol:u}=W(a.identifier);if(c!==e.chain)continue;let{address:_}=ae(u,c);if(_?.toLowerCase()===s)return a.identifier}return}import{match as be}from"ts-pattern";var G=8,Kn=10,Wn=64;function X({value:e,bigIntDecimal:t=G,decimal:n=G}){if(n===0)return e.toString();let r=Math.min(t,n),s=r<n?Tt(e,B(n-r)):e,a=s<0n,c=(a?-s:s).toString().padStart(r+1,"0"),u=c.length-r;return`${a?"-":""}${c.slice(0,u)}.${c.slice(u)}`.replace(/\.?0*$/,"")}class F{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(e,t){return new F({decimal:t,value:X({bigIntDecimal:t,decimal:t,value:e})})}static shiftDecimals({value:e,from:t,to:n}){return F.fromBigInt(e.getBaseValue("bigint")*B(n)/B(t),n)}constructor(e){this.decimal=typeof e==="object"?e.decimal:void 0;let t=Ae(typeof e==="object"&&"value"in e?e.value:e),n=typeof e==="object"&&"decimalMultiplier"in e?e.decimalMultiplier:B(this.decimal??0);this.decimalMultiplier=n!==void 0&&n>t.decimalMultiplier?n:t.decimalMultiplier,this.bigIntValue=t.bigIntValue*this.decimalMultiplier/t.decimalMultiplier}toString(e={}){return this.getValue("string")}set(e){return this.#n({decimal:this.decimal,value:new F(e)})}#n(e){return new this.constructor({...e,identifier:this.toString({includeSynthProtocol:!0})})}add(...e){return this.#t("add",...e)}sub(...e){return this.#t("sub",...e)}mul(...e){return this.#t("mul",...e)}div(...e){return this.#t("div",...e)}gt(e){return this.#e("gt",e)}gte(e){return this.#e("gte",e)}lt(e){return this.#e("lt",e)}lte(e){return this.#e("lte",e)}eqValue(e){return this.#e("eqValue",e)}getValue(e,t){let n=Se(this.decimalMultiplier),r=t!==void 0?t:this.decimal,s=r!==void 0?r:n;if(r!==void 0&&r<n){if(this.formatBigIntToSafeValue(this.bigIntValue,r)==="0"&&this.bigIntValue!==0n)s=n}let a=this.formatBigIntToSafeValue(this.bigIntValue,s);return be(e).with("number",()=>Number(a)).with("string",()=>a).with("bigint",()=>this.bigIntValue*B(this.decimal??G)/this.decimalMultiplier).otherwise(()=>a)}getBaseValue(e,t){let n=B(t??this.decimal??G),r=Tt(this.bigIntValue*n,this.decimalMultiplier);return be(e).with("number",()=>Number(r)).with("string",()=>r.toString()).otherwise(()=>r)}getBigIntValue(e,t){if(t===void 0&&typeof e==="object")return e.bigIntValue;let n=Ae(e),r=t===void 0?this.decimalMultiplier:B(t);return n.bigIntValue*r/n.decimalMultiplier}toSignificant(e=6){let t=this.getValue("string"),n=t.startsWith("-"),r=n?t.slice(1):t,[s="",a=""]=r.split("."),c=Number.parseInt(s,10)>0;if((c?s.length+a.length:a.length)<=e)return U(n,r);if(s.length>=e)return U(n,s.slice(0,e).padEnd(s.length,"0"));if(c)return U(n,`${s}.${a.slice(0,e-s.length)}`);let _=a.replace(/^0+/,"")||"0",A=_.slice(0,e),y=a.length-_.length;return U(n,`0.${A.padStart(y+A.length,"0")}`)}toFixed(e=6){let t=this.getValue("string"),n=t.startsWith("-"),[r="0",s=""]=(n?t.slice(1):t).split(".");if(e===0){if(r==="0"&&!s)return"0";let y=s&&Number.parseInt(s[0]||"0",10)>=5?`${BigInt(r)+1n}.0`:`${r}.0`;return U(n,y)}if(!s)return U(n,`${r}.${"0".repeat(e)}`);let a=s[e];if(!(a&&Number.parseInt(a,10)>=5))return U(n,`${r}.${s.slice(0,e).padEnd(e,"0")}`);let u=BigInt(s.slice(0,e).padEnd(e,"0"))+1n,_=10n**BigInt(e);if(u>=_)return U(n,`${BigInt(r)+1n}.${"0".repeat(e)}`);return U(n,`${r}.${u.toString().padStart(e,"0")}`)}toAbbreviation(e=2){let t=this.getValue("string"),n=Number(t),r=["","K","M","B","T","Q","Qi","S"],s=Math.floor(Math.log10(Math.abs(n))/3);if(s===0||!r[s])return t;return`${(n/10**(s*3)).toFixed(e)}${r[s]}`}toCurrency(e="$",{currencyPosition:t="start",decimal:n=2,decimalSeparator:r=".",thousandSeparator:s=",",trimTrailingZeros:a=!0}={}){let c=this.toFixed(n),u=t==="end",[_="0",A=""]=c.split("."),y=_.replace(/\B(?=(\d{3})+(?!\d))/g,s),w=A&&Number.parseInt(A,10)>0,O=w?`${y}${r}${A}`:y,M=O.length<100&&a&&w?O.replace(/\.?0*$/,""):O;return u?`${M}${e}`:`${e}${M}`}formatBigIntToSafeValue(e,t){return X({bigIntDecimal:t||this.decimal||G,decimal:Se(this.decimalMultiplier),value:e})}#t(e,...t){let n=t.map(Ae),r=Math.max(G,Se(this.decimalMultiplier),...n.map(({decimalMultiplier:A})=>Se(A))),s=Math.min(r+Kn,Wn),a=B(s),c=n.reduce((A,y)=>{let w=A.decimalMultiplier*y.decimalMultiplier,O=be(e).with("add",()=>A.bigIntValue*y.decimalMultiplier+y.bigIntValue*A.decimalMultiplier).with("sub",()=>A.bigIntValue*y.decimalMultiplier-y.bigIntValue*A.decimalMultiplier).with("mul",()=>A.bigIntValue*y.bigIntValue).with("div",()=>{if(y.bigIntValue===0n)throw RangeError("Division by zero");return A.bigIntValue*y.decimalMultiplier}).exhaustive(),S=e==="div"?A.decimalMultiplier*y.bigIntValue:w;return{bigIntValue:O*a/S,decimalMultiplier:a}},this),u=this.decimal===void 0?void 0:Math.min(this.decimal,s),_=c.decimalMultiplier===a?c:{bigIntValue:c.bigIntValue*a/c.decimalMultiplier,decimalMultiplier:a};return this.#n({decimal:u,value:_})}#e(e,t){let n=Ae(t),r=this.bigIntValue*n.decimalMultiplier,s=n.bigIntValue*this.decimalMultiplier;return be(e).with("gt",()=>r>s).with("gte",()=>r>=s).with("lt",()=>r<s).with("lte",()=>r<=s).with("eqValue",()=>r===s).exhaustive()}}var Gn=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function qn(e){let n=`${typeof e==="number"?Gn.format(e):e}`.replaceAll(",",".").split(".");return n.length>1?`${n.slice(0,-1).join("")}.${n.at(-1)}`:n[0]||"0"}function Yn(e){let t=e.split(".")[1]?.length||0;return Math.max(t,G)}function Ae(e){if(typeof e==="object")return e;let t=e==="undefined"?"0":qn(e),n=Yn(t),[r="",s=""]=t.split(".");return{bigIntValue:BigInt(`${r}${s.padEnd(n,"0")}`),decimalMultiplier:B(n)}}function U(e,t){return e&&!/^0(?:\.0*)?$/.test(t)?`-${t}`:t}function Tt(e,t){if(t===0n)throw Error("Cannot divide by zero");let n=t/2n;return e>=0n&&t>=0n||e<0n&&t<0n?(e+n)/t:(e-n)/t}function B(e){return 10n**BigInt(e)}function Se(e){return e.toString().length-1}function zn(e=""){let t=e.toUpperCase(),n=T.get("chains"),[r]=t.split(".");if(n.includes(r))return!0;let[s]=t.split("/");if(n.includes(s))return!0;throw new b({errorKey:"helpers_invalid_identifier",info:{identifier:e,message:`Invalid identifier: ${e}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}var J=[v.Hype,v.Near,v.Ripple,v.Solana,v.Stellar,v.Sui,v.Ton,v.Tron],Ue=[v.THORChain,v.Maya];function Te(e,t){return J.includes(e)?t:t.toUpperCase()}var z=new Map,we=new Map,Q=new Map,Qn=3600000;function Jn(e){let t=Q.get(e);if(t?.timestamp&&Date.now()-t.timestamp>Qn){Q.delete(e);return}return t}function Zn(e,t){if(Q.size>1000){let n=Q.keys().next().value;if(n)Q.delete(n)}Q.set(e,{...t,timestamp:Date.now()})}class D extends F{address;chain;isGasAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:e,decimal:t,tax:n,chain:r,symbol:s,identifier:a}){super({decimal:t,value:e});let c=wt(a||`${r}.${s}`);this.type=Me(c),this.tax=n,this.chain=c.chain,this.ticker=c.ticker,this.symbol=c.symbol,this.address=c.address,this.isSynthetic=c.isSynthetic,this.isTradeAsset=c.isTradeAsset,this.isGasAsset=c.isGasAsset,this.chainId=le(c.chain).chainId}toString({includeSynthProtocol:e}={}){return(this.isSynthetic||this.isTradeAsset)&&!e?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 e=this.symbol.replace(/\./g,"__");return`${this.chain}.${e}`}getIconUrl(){return z.get(Te(this.chain,this.toString()))?.logoURI}eqAsset({chain:e,symbol:t}){return this.chain===e&&this.symbol===t}eq(e){return this.eqAsset(e)&&this.eqValue(e)}static fromUrl(e,t=0){let n=e.indexOf(".");if(n===-1)throw new b({errorKey:"helpers_invalid_asset_url",info:{urlAsset:e}});let r=e.slice(0,n),s=e.slice(n+1),a=Ve({chain:r,rest:s}).when(({rest:c})=>c.includes(".."),({chain:c,rest:u})=>`${c}.${u.replace(/\.\./g,"~")}`).when(({chain:c,rest:u})=>Ue.includes(c)&&u.includes("."),({chain:c,rest:u})=>`${c}.${u.replace(/\./g,"/")}`).otherwise(({chain:c,rest:u})=>`${c}.${u.replace(/__/g,".")}`);return D.from({asset:a,value:t})}static from({value:e=0,fromBaseDecimal:t,asyncTokenLookup:n,...r}){let s="address"in r&&"chain"in r,a=rr(r);if(a===null&&n&&s){let{chain:se,address:q}=r;return tr({address:q,chain:se,fromBaseDecimal:t,parsedValue:e})}let c=s&&!a?`${r.chain}.UNKNOWN-${r.address}`:a,{identifier:u,decimal:_}=ye(c),{chain:A,isSynthetic:y,isTradeAsset:w,address:O}=wt(u),{baseDecimal:S}=le(A),M=z.get(Te(A,u));if(!M&&n&&!y&&!w)return(async()=>{let{ticker:se}=W(u),q=await xt({address:O,chain:A,ticker:se});return Le({decimal:q.decimals,identifier:q.identifier,value:t?He(e,t):e})})();let I=M?.decimal||_;Y({condition:!I&&!n,id:`assetValue_static_decimal_not_found_${A}`,warning:`Couldn't find static decimal for one or more tokens on ${A} (Using default ${S} decimal as fallback).
2
+ This can result in incorrect calculations and mess with amount sent on transactions.
3
+ You can load static assets by installing @swapkit/tokens package and calling AssetValue.loadStaticAssets()
4
+ or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`});let{decimal:C,identifier:ne,tax:re}=M||{decimal:I||S,identifier:u},R=t?He(e,t):xe(e,C);return y||w?er(ne,R):Le({decimal:C,identifier:ne,tax:re,value:R})}static async loadStaticAssets(e){let{loadTokenLists:t}=await import("@swapkit/tokens"),n=await t(e,{source:T.get("envs").isDev?"dev":"prod"});for(let{tokens:r}of Object.values(n))for(let s of r){let{identifier:a}=s,{chain:c,symbol:u}=W(a),{address:_}=ae(u,c),{baseDecimal:A}=le(c),y=Te(c,a),w="decimals"in s&&s.decimals!==void 0?s.decimals:A,O="logoURI"in s&&s.logoURI?s.logoURI:`https://tokens.swapkit.dev/images/${a.toLowerCase()}.png`,S={decimal:w,identifier:a,logoURI:O,tax:"tax"in s?s.tax:void 0};if(z.set(y,S),_){let M=J.includes(c)?`${c}:${_}`:`${c}:${_.toUpperCase()}`;we.set(M,a)}}return!0}static setStaticAssets(e){z.clear(),we.clear();for(let[t,n]of e.entries()){let{identifier:r}=n,{chain:s,symbol:a}=W(r),{address:c}=ae(a,s),{baseDecimal:u}=le(s),_=n.chain??s,A=n.address??c,y=Te(_,r),w=n.decimals??n.decimal??u,O=n.logoURI??`https://tokens.swapkit.dev/images/${r.toLowerCase()}.png`,S={decimal:w,identifier:y,logoURI:O,tax:n.tax};if(z.set(y,S),A){let M=J.includes(_)?`${_}:${A}`:`${_}:${A.toUpperCase()}`;we.set(M,r)}}return!0}static get staticAssets(){return z}}function to(e){let t=D.from({chain:e});return Ve(e).with(v.Bitcoin,v.Litecoin,v.BitcoinCash,v.Dash,()=>t.set(0.00010001)).with(v.Dogecoin,()=>t.set(1.00000001)).with(v.Avalanche,v.Ethereum,v.Arbitrum,v.BinanceSmartChain,()=>t.set(0.00000001)).with(v.THORChain,v.Maya,()=>t.set(0)).with(v.Cosmos,v.Kujira,()=>t.set(0.000001)).otherwise(()=>t.set(0.00000001))}async function xt({chain:e,address:t,ticker:n}){let s=J.includes(e)?`${e}:${t||n}`:`${e}:${t||n}`.toUpperCase(),a=Jn(s);if(a)return a;if(!t){let{baseDecimal:_}=le(e);return{decimals:_,identifier:`${e}.${n||"UNKNOWN"}`}}let c=await At({address:t,chain:e}),u=`${e}.${c.ticker||n||"UNKNOWN"}-${t}`;return Y({condition:!!(!c.ticker&&n),id:`async_token_lookup_failed_${e}_${t}`,warning:`Could not fetch token metadata for ${e}:${t} from chain. Using user-provided ticker (${n}) with baseDecimal (${c.decimals}).`}),c.ticker&&Zn(s,{decimals:c.decimals,identifier:u}),{decimals:c.decimals,identifier:u}}function Le({identifier:e,decimal:t,value:n,tax:r}){return zn(e),new D({decimal:t,identifier:e,tax:r,value:xe(n,t)})}function er(e,t=0){let n=e.includes(".")?e.split(".")?.[0]?.toUpperCase():void 0,r=n?Ue.includes(n):!1,s=e.slice(0,14).includes("~")?"~":"/",[a,c]=r?e.split(".").slice(1).join().split(s):e.split(s);if(!(a&&c))throw new b({errorKey:"helpers_invalid_asset_identifier",info:{identifier:e}});return new D({decimal:8,identifier:`${n||v.THORChain}.${a}${s}${c}`,value:xe(t,8)})}async function tr({address:e,chain:t,fromBaseDecimal:n,parsedValue:r}){let{decimals:s,identifier:a}=await xt({address:e,chain:t}),c=n?He(r,n):r;return Le({decimal:s,identifier:a,value:c})}function He(e,t){let n=e instanceof F?e.getValue("string"):e;return xe(BigInt(n),t)}function xe(e,t){return typeof e==="bigint"?X({bigIntDecimal:t,decimal:t,value:e}):e}function nr(e){let t=Ve(e).when((n)=>("chain"in n)&&n.chain!==void 0,({chain:n})=>n).otherwise((n)=>{let r=W(n.asset);return r.synth?v.THORChain:r.chain});if(!jn.includes(t.toUpperCase())){let n="asset"in e?e.asset:t;throw new b({errorKey:"helpers_invalid_asset_identifier",info:{identifier:n,message:`Unsupported chain "${t}" - use the AssetValue constructor directly`}})}}function rr(e){if(nr(e),"chain"in e){let{chain:s,address:a}=e;if(a){let c=J.includes(s)?`${s}:${a}`:`${s}:${a.toUpperCase()}`,u=we.get(c);if(u)return u;return null}return s}let{chain:t,symbol:n}=W(e.asset);return Me({chain:t,symbol:n})==="Native"?t:e.asset}function sr(e,t,n){let r=e.split("."),s=r[0]?.toUpperCase(),a=Ue.includes(s),c=n?"~":"/",[u,_=""]=a?r.slice(1).join(".").split(c):e.split(c);if(!(u&&_))throw new b({errorKey:"helpers_invalid_asset_identifier",info:{identifier:e}});let{ticker:A,address:y}=Rt({chain:u,symbol:_}),w=`${u}${c}${_}`;return{address:y,chain:s,isGasAsset:!1,isSynthetic:t,isTradeAsset:n,symbol:w,ticker:A}}function ir(e){let t=e.indexOf("."),n=(t===-1?e:e.slice(0,t)).toUpperCase(),r=t===-1?e:e.slice(t+1),{address:s,ticker:a}=Rt({chain:n,symbol:r}),c;try{c=s&&Xn.includes(n)&&fe(s)?fe(s):s}catch{c=s}let u=c?`${a}-${c}`:r;return{address:c,chain:n,isGasAsset:St({chain:n,symbol:r}),isSynthetic:!1,isTradeAsset:!1,symbol:u,ticker:a}}function wt(e){let t=e.slice(0,14),n=t.includes("/"),r=t.includes("~");if(n||r)return sr(e,n,r);return ir(e)}function Rt({symbol:e,chain:t}){let{ticker:n,address:r}=ae(e,t);return{address:r&&!J.includes(t)?r.toLowerCase():r,ticker:n}}class Re extends F{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new Re({decimal:t,value:X({bigIntDecimal:t,decimal:t,value:e})})}}function vt(e=!0){return e?"https://gateway.liquify.com/chain/thorchain_midgard":"https://midgard.mayachain.info"}function ar(e=!0){let t=vt(e);return e?`${t}/v2/thorname`:`${t}/v2/mayaname`}function lr(e){return function(n){let r=n?`?status=${n}`:"";return m.get(`${e}/v2/pools${r}`)}}function cr(e){return function(n){return m.get(`${e}/v2/pool/${n}`)}}function dr(e){return function(n,r){let s=r?`?period=${r}`:"";return m.get(`${e}/v2/pool/${n}/stats${s}`)}}function pr(e){return function(n,r){let s=new URLSearchParams;if(r?.interval)s.append("interval",r.interval);if(r?.count)s.append("count",r.count.toString());if(r?.from)s.append("from",r.from.toString());if(r?.to)s.append("to",r.to.toString());let a=s.toString()?`?${s.toString()}`:"";return m.get(`${e}/v2/history/depths/${n}${a}`)}}function ur(e){return function(){return m.get(`${e}/v2/network`)}}function gr(e){return function(){return m.get(`${e}/v2/health`)}}function mr(e){return function(){return m.get(`${e}/v2/nodes`)}}function _r(e){return function(n){return m.get(`${e}/v2/node/${n}`)}}function hr(e){return function(){return m.get(`${e}/v2/mimir/votes`)}}function fr(e){return function(){return m.get(`${e}/v2/mimir`)}}function yr(e){return function(){return m.get(`${e}/v2/constants`)}}function br(e){return function(){return m.get(`${e}/v2/stats`)}}function Ar(e){return function(n){let r=new URLSearchParams;if(n?.interval)r.append("interval",n.interval);if(n?.count)r.append("count",n.count.toString());if(n?.from)r.append("from",n.from.toString());if(n?.to)r.append("to",n.to.toString());let s=r.toString()?`?${r.toString()}`:"";return m.get(`${e}/v2/history/earnings${s}`)}}function Sr(e){return function(n,r){let s=new URLSearchParams;if(r?.interval)s.append("interval",r.interval);if(r?.count)s.append("count",r.count.toString());if(r?.from)s.append("from",r.from.toString());if(r?.to)s.append("to",r.to.toString());let a=s.toString()?`?${s.toString()}`:"",c=n?`/swaps/${n}`:"/swaps";return m.get(`${e}/v2/history${c}${a}`)}}function Tr(e){return function(n){let r=new URLSearchParams;if(n?.interval)r.append("interval",n.interval);if(n?.count)r.append("count",n.count.toString());if(n?.from)r.append("from",n.from.toString());if(n?.to)r.append("to",n.to.toString());let s=r.toString()?`?${r.toString()}`:"";return m.get(`${e}/v2/history/tvl${s}`)}}function wr(e){if(!e)return"";let t=new URLSearchParams,n=(r,s)=>{if(s!==void 0)t.append(r,typeof s==="number"?s.toString():s)};return n("address",e.address),n("txid",e.txid),n("asset",e.asset),n("type",e.type),n("affiliate",e.affiliate),n("limit",e.limit),n("offset",e.offset),t.toString()?`?${t.toString()}`:""}function xr(e){return function(n){let r=wr(n);return m.get(`${e}/v2/actions${r}`)}}function Rr(e){return function(n){return m.get(`${e}/v2/member/${n}`)}}function vr(e){return function(n){let r=n?`/${n}`:"";return m.get(`${e}/v2/members${r}`)}}function Cr(e){return function(n,r){let s=r?`&asset=${r}`:"";return m.get(`${e}/v2/saver/${n}${s?`?${s.substring(1)}`:""}`)}}function Ir(e){return function(n){return m.get(`${e}/v2/savers/${n}`)}}function Er(e){return function(n,r){let s=new URLSearchParams;if(r?.interval)s.append("interval",r.interval);if(r?.count)s.append("count",r.count.toString());if(r?.from)s.append("from",r.from.toString());if(r?.to)s.append("to",r.to.toString());let a=s.toString()?`?${s.toString()}`:"",c=n?`/savers/${n}`:"/savers";return m.get(`${e}/v2/history${c}${a}`)}}function Pr(e){return function(n){return m.get(`${e}/v2/balance/${n}`)}}function Nr(e){return async function(n){let r=(s)=>{if(s?.cause?.status===404)return;throw s};return await m.get(`${e}/lookup/${n}`,{onError:r,retry:{maxRetries:1}})}}function kr(e){return async function(n){let r=(s)=>{if(s?.cause?.status===404)return[];throw s};return await m.get(`${e}/rlookup/${n}`,{onError:r,retry:{maxRetries:1}})}}function Or(e){return async function(n){let r=(s)=>{if(s?.cause?.status===404)return[];throw s};return await m.get(`${e}/owner/${n}`,{onError:r,retry:{maxRetries:1}})}}function Z({asset:e,value:t}){return D.from({asset:e,fromBaseDecimal:or(ve.THORChain).baseDecimal,value:t})}function Dr({liquidityPositionGetter:e,isThorchain:t}){return async function(r){let s=await e(r),a=t?"rune":"cacao";return s.pools.map((c)=>({[`${a}Pending`]:Z({asset:"THOR.RUNE",value:c.runePending}),[`${a}RegisteredAddress`]:c.runeAddress,[`${a}Withdrawn`]:Z({asset:"THOR.RUNE",value:c.runeWithdrawn}),[a]:Z({asset:"THOR.RUNE",value:c.runeAdded}),asset:Z({asset:c.pool,value:c.assetAdded}),assetPending:Z({asset:c.pool,value:c.assetPending}),assetRegisteredAddress:c.assetAddress,assetWithdrawn:Z({asset:c.pool,value:c.assetWithdrawn}),dateFirstAdded:c.dateFirstAdded,dateLastAdded:c.dateLastAdded,poolShare:new Re(c.liquidityUnits).div(c.pool)}))}}function Ct(e){let t=e===ve.THORChain,n=vt(t),r=ar(t),s=Rr(n);return{getActions:xr(n),getBalance:Pr(n),getConstants:yr(n),getEarningsHistory:Ar(n),getHealth:gr(n),getLiquidityPosition:Dr({isThorchain:t,liquidityPositionGetter:s}),getLiquidityPositionRaw:s,getMembers:vr(n),getMimir:fr(n),getMimirVotes:hr(n),getNameDetails:Nr(r),getNamesByAddress:kr(r),getNamesByOwner:Or(r),getNetworkInfo:ur(n),getNode:_r(n),getNodes:mr(n),getPool:cr(n),getPoolDepthHistory:pr(n),getPoolStats:dr(n),getPools:lr(n),getSaverDetails:Cr(n),getSavers:Ir(n),getSaversHistory:Er(n),getStats:br(n),getSwapHistory:Sr(n),getTVLHistory:Tr(n)}}var It=Ct(ve.THORChain),Et=Ct(ve.Maya);var Ge={};ze(Ge,{SKRequestClient:()=>k,getChainBalance:()=>Ss,getChainflipDepositChannel:()=>Is,getGasRate:()=>Cs,getNearDepositChannel:()=>Es,getPrice:()=>vs,getRouteWithTx:()=>As,getSwapQuote:()=>bs,getSwapTo:()=>Ds,getTokenApproval:()=>Ts,getTokenList:()=>xs,getTokenListProviders:()=>ws,getTrackerDetails:()=>ys,searchTokens:()=>Rs});import{EVMChains as We}from"@swapkit/types";import{match as fs,P as pe}from"ts-pattern";import{Chain as Ce,ChainId as ce}from"@swapkit/types";import{array as x,boolean as H,coerce as Ot,number as h,object as g,optional as p,string as o,union as $e,unknown as Be,z as i}from"zod";var Dt;((r)=>{r.CHEAPEST="CHEAPEST";r.FASTEST="FASTEST";r.RECOMMENDED="RECOMMENDED"})(Dt||={});var Ie;((y)=>{y.PSBT="PSBT";y.EVM="EVM";y.COSMOS="COSMOS";y.RADIX="RADIX";y.NEAR="NEAR";y.STELLAR="STELLAR";y.TON="TON";y.TRON="TRON";y.EIP_712_HYPE_SEND_ASSET="EIP_712_HYPE_SEND_ASSET";y.EIP_712_HYPE_WITHDRAW="EIP_712_HYPE_WITHDRAW"})(Ie||={});var Mt;((C)=>{C.approve="approve";C.claim="claim";C.deposit="deposit";C.donate="donate";C.lending="lending";C.lp_action="lp_action";C.native_contract_call="native_contract_call";C.native_send="native_send";C.stake="stake";C.streaming_swap="streaming_swap";C.swap="swap";C.thorname_action="thorname_action";C.token_contract_call="token_contract_call";C.token_transfer="token_transfer";C.unknown="unknown";C.unstake="unstake"})(Mt||={});var Lt;((S)=>{S.swap="swap";S.aggregation="aggregation";S.addLiquidity="addLiquidity";S.withdrawLiquidity="withdrawLiquidity";S.addSavers="addSavers";S.withdrawSavers="withdrawSavers";S.borrow="borrow";S.repay="repay";S.name="name";S.donate="donate";S.claim="claim";S.stake="stake";S.unstake="unstake"})(Lt||={});var Ht;((u)=>{u.unknown="unknown";u.not_started="not_started";u.pending="pending";u.swapping="swapping";u.completed="completed";u.refunded="refunded";u.failed="failed"})(Ht||={});var Vt;((I)=>{I.not_started="not_started";I.starting="starting";I.broadcasted="broadcasted";I.mempool="mempool";I.inbound="inbound";I.outbound="outbound";I.swapping="swapping";I.completed="completed";I.refunded="refunded";I.partially_refunded="partially_refunded";I.dropped="dropped";I.reverted="reverted";I.replaced="replaced";I.retries_exceeded="retries_exceeded";I.parsing_error="parsing_error"})(Vt||={});var mo=g({address:p(o()),chain:i.enum(Ce).optional(),chainId:i.enum(ce),coingeckoId:p(o()),decimals:Ot.number(),extensions:p(i.looseObject({})),identifier:o(),logoURI:p(o()),name:p(o()),shortCode:p(o()),symbol:p(o()),ticker:o()}),_o=i.object({block:i.optional(i.number().describe("Block number. Required for Polkadot chain. e.g. `123456`")),chainId:i.optional(i.string().describe("ChainId for the hash. e.g. `thorchain-1`")),depositChannelId:i.optional(i.string().describe("Deposit channel ID, required for Chainflip if tx was broadcasted without wallet connection")),hash:i.optional(i.string().describe("Hash for the first transaction broadcasted by the end user. e.g. `88D1819378ECD09E5284C54937CDC1E99B52F253C007617A02DD1200710CE677`"))}).refine((e)=>e.hash&&e.chainId||e.depositChannelId,{message:"Either `hash` and `chainId` or `depositChannelId` must be provided"}),ho=i.object({forceUpdate:i.string().toLowerCase().transform((e)=>e==="true").pipe(i.boolean()).optional()}),fo=g({error:o(),message:o()}),ee=g({address:p(o()),chain:i.enum(Ce),decimal:p(h()),isGasAsset:H(),isSynthetic:H(),symbol:o(),tax:p(g({buy:h(),sell:h()})),ticker:o()}),Ut=g({id:o(),market_cap:h(),name:o(),price_change_24h_usd:h(),price_change_percentage_24h_usd:h(),sparkline_in_7d:x(h()),timestamp:o(),total_volume:h()}).partial(),yo=g({cg:p(Ut),identifier:o(),price_usd:h(),provider:o(),timestamp:h()}),$t=x(g({cg:p(Ut),identifier:o(),price_usd:h(),provider:o(),timestamp:h()}).partial()),bo=g({affiliate:p(o().describe("Affiliate thorname")),affiliateFee:p(h().describe("Affiliate fee in basis points").refine((e)=>e===Math.floor(e)&&e>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:p(H().describe("Allow smart contract as recipient")),allowSmartContractSender:p(H().describe("Allow smart contract as sender")),buyAsset:o().describe("Asset to buy"),cfBoost:p(H().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:p(o().describe("Address to send asset to")),disableSecurityChecks:p(H().describe("Disable security checks")),includeTx:p(H().describe("Set to true to include an transaction object (EVM only)")),providers:p(x(o().describe("List of providers to use").refine((e)=>E[e]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:p(o().describe("Referrer address (referral program)")),sellAmount:o().describe("Amount of asset to sell").refine((e)=>+e>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:o().describe("Asset to sell"),slippage:p(h().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:p(o().describe("Address to send asset from"))}).refine((e)=>e.sellAsset!==e.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),Ao=g({metadata:H(),tokens:x(g({identifier:o()}))}),Bt=g({destinationAddress:o()}),Mr=Bt.extend({affiliateFees:x(g({brokerAddress:o(),feeBps:h()})).optional(),brokerCommissionBps:h().optional(),buyAsset:g({asset:o(),chain:o()}),channelMetadata:g({cfParameters:o().optional(),gasBudget:o().optional(),message:o().optional()}).optional(),dcaParameters:g({chunkInterval:h().optional(),numberOfChunks:h().optional()}).optional(),maxBoostFeeBps:h().optional(),refundParameters:g({minPrice:o().optional(),refundAddress:o().optional(),retryDuration:h().optional()}).optional(),sellAsset:g({asset:o(),chain:o()})}),Ft=g({channelId:o(),depositAddress:o()}),Pt=Bt.extend({affiliateFees:g({feeBps:h(),nearId:o()}).optional(),buyAsset:o(),sellAmount:o(),sellAsset:o(),slippage:Ot.number(),sourceAddress:o()}),Nt=g({amountIn:o(),amountInFormatted:o(),amountInUsd:o(),amountOut:o(),amountOutFormatted:o(),amountOutUsd:o(),deadline:o().optional(),minAmountIn:o(),minAmountOut:o(),timeEstimate:h().optional(),timeWhenInactive:o().optional()}),So=Nt.extend({depositAddress:o(),quote:Nt,signature:o(),timestamp:o(),tx:Be()}),Kt=g({buyAsset:o(),buyAssetAmount:o(),buyAssetAmountMaxSlippage:o(),deadline:o().optional(),depositAddress:o(),depositAmount:o(),depositAsset:o(),tx:Be()}),Lr=g({evmCalldata:i.optional(i.string()),intentHash:i.optional(i.string()),logs:i.optional(i.unknown()),manifest:i.optional(i.unknown()),memo:i.optional(i.string()),spender:i.optional(i.string()),thorname:i.optional(i.string())}),Hr=g({currentStage:o(),inboundConfirmation:h(),inboundObservation:h(),outboundDelay:h(),outboundObservation:h(),streamingSwap:h()}),Vr=g({count:p(h()),interval:p(h()),quantity:p(h()),subSwapsMap:p(x(h()))}),Ur=i.object({currentLegIndex:i.optional(i.number()),estimatedTimeToComplete:i.number(),estimates:i.optional(Hr),providerDetails:i.optional(i.object({streamingDetails:i.optional(Vr)}))}),$r=g({affiliate:p(ee),liquidity:p(ee),network:p(ee),protocol:p(ee),tax:p(ee)}),Br=g({affiliate:o(),bps:o(),isReferrer:H()}),Fr=g({affiliate:p(o()),affiliateFees:p(x(Br)),broadcastedAt:p(h()),explorerUrl:p(o()),fees:p($r),images:p(g({chain:p(o()),from:p(o()),provider:p(o()),to:p(o())})),provider:p(i.enum(E)),providerAction:i.optional(i.enum(Lt)),quoteId:p(o()),wallet:p(o())}),te=i.object({block:i.number(),chainId:i.enum(ce),finalAddress:i.optional(i.string()),finalAsset:i.optional(ee),finalisedAt:i.number(),fromAddress:i.string(),fromAmount:i.string(),fromAsset:i.string(),hash:i.string(),meta:i.optional(Fr),payload:i.optional(Lr),status:i.enum(Ht),toAddress:i.string(),toAmount:i.string(),toAsset:i.string(),trackingStatus:i.optional(i.enum(Vt)),transient:i.optional(Ur),type:i.enum(Mt)}),Wt=te.extend({legs:i.array(te)}),To=te.extend({legs:x(te)}),wo=te.extend({legs:x(te)}),Fe=x(g({amount:o(),asset:o(),chain:o(),protocol:i.enum(E),type:i.enum(Ne)})),Ke=i.object({inbound:i.optional(i.number().describe("Time to receive inbound asset in seconds")),outbound:i.optional(i.number().describe("Time to receive outbound asset in seconds")),swap:i.optional(i.number().describe("Time to swap assets in seconds")),total:i.number().describe("Total time in seconds")}),Kr=/^(?:0x[0-9a-fA-F]+|[0-9]+)$/;function Wr(e){return e===""||Kr.test(e)}function xo(e){return e?BigInt(e):0n}function Ro(e){let t=typeof e==="bigint"?e:BigInt(e);return t>0n?`0x${t.toString(16)}`:"0x0"}var de=o().refine(Wr,{message:"Value must be a base-10 integer string or 0x-prefixed hex integer string"}).describe("Value to send in base units as a base-10 integer string or 0x-prefixed hex integer string"),Gr=g({data:o().describe("Data to send"),from:o().describe("Address of the sender"),to:o().describe("Address of the recipient"),value:de}),qr=i.object({data:i.string().optional(),raw_data:i.object({contract:i.any(),data:i.string().optional(),expiration:i.number(),fee_limit:i.number().optional(),ref_block_bytes:i.string(),ref_block_hash:i.string(),timestamp:i.number()}).passthrough(),raw_data_hex:i.string(),txID:i.string(),value:de.optional(),visible:i.boolean()}),Yr=x($e([o(),h(),x(o()),g({from:o(),value:de}).describe("Parameters to pass to the contract method")])),vo=g({approvalSpender:p(o().describe("Address of the spender to approve")),approvalToken:p(o().describe("Address of the token to approve spending of")),contractAddress:o().describe("Address of the contract to interact with"),contractMethod:o().describe("Name of the method to call"),contractParamNames:x(o().describe("Names of the parameters to pass to the contract method")),contractParams:Yr}),jr=g({typeUrl:o("/types.MsgDeposit"),value:g({coins:x(g({amount:o(),asset:g({chain:o(),symbol:o(),synth:H(),ticker:o()})})),memo:o(),signer:o()})}),Xr=g({typeUrl:o("/types.MsgSend"),value:g({amount:x(g({amount:o(),denom:o()})),fromAddress:o(),toAddress:o()})}),zr=g({typeUrl:o(),value:Xr.shape.value.or(jr.shape.value)}),Qr=g({amount:x(g({amount:o(),denom:o()})),gas:o()}),Jr=g({accountNumber:h(),chainId:i.enum(ce),fee:Qr,memo:o(),msgs:x(zr),sequence:h()}),Zr=i.array(i.object({calldata:i.array(i.string()),contractAddress:i.string(),entrypoint:i.string()})),es=i.object({address:i.string().describe("Destination address in friendly format"),amount:i.string().describe("Amount in nanotons"),payload:i.string().optional().describe("Base64 BOC of body cell"),stateInit:i.string().optional().describe("Base64 BOC of state init")}),ts=i.object({messages:i.array(es),sendMode:i.number().describe("TON wallet send mode for the whole transfer")}),Co="USDC:0x6d1e7cde53ba9467b783cb7c530ce054",ns=i.looseObject({domain:i.looseObject({chainId:p($e([h(),o()])),name:p(o()),verifyingContract:p(o()),version:p(o())}),message:i.record(o(),Be()),primaryType:o(),types:i.record(o(),x(i.looseObject({name:o(),type:o()})))}),rs=i.looseObject({amount:o(),destination:o(),destinationDex:o(),fromSubAccount:o(),hyperliquidChain:o(),nonce:h().int(),signatureChainId:o(),sourceDex:o(),token:o(),type:i.literal("sendAsset")}),Gt=i.looseObject({action:i.looseObject({type:o()}),submitTo:o(),typedData:ns}),Io=Gt.extend({action:rs}),qt=$e([Gr,Jr,qr,ts,Gt,o()]),ss=qt.or(Zr),is=g({affiliate:o().describe("Affiliate address").optional(),affiliateFee:h().describe("Affiliate fee").optional(),buyAsset:o().describe("Asset to buy"),destinationAddress:o().describe("Destination address"),estimatedTime:Ke.optional(),provider:i.enum(E),sellAsset:o().describe("Asset to sell"),slipPercentage:h().describe("Slippage as a percentage"),sourceAddress:o().describe("Source address")}),Eo=is.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),os=g({asset:o().describe("Asset name"),image:o().describe("Asset image"),price:h().describe("Price in USD")}),as=Mr,Yt=g({assets:p(x(os)),maxStreamingQuantity:h().optional(),referrer:o().optional(),streamingInterval:h().optional(),tags:x(i.enum(Dt))}),jt=Yt.extend({affiliate:p(o()),affiliateFee:p(o()),approvalAddress:p(o().describe("Approval address for swap")),chainflip:as.optional(),garden:Pt.optional(),near:Pt.optional(),priceImpact:p(h().describe("Price impact")),referrer:p(o()),txType:p(i.enum(Ie))}),Xt=x(g({code:i.enum(Pe),display:o(),tooltip:o().optional()})),ls=g({buyAmount:o().describe("Buy amount"),buyAmountMaxSlippage:o().describe("Buy amount max slippage"),buyAsset:o().describe("Asset to buy"),fees:p(Fe),provider:i.enum(E),sellAmount:o().describe("Sell amount"),sellAsset:o().describe("Asset to sell")}),cs=g({buyAsset:o().describe("Asset to buy"),destinationAddress:p(o().describe("Destination address")),estimatedTime:p(Ke),expectedBuyAmount:o().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:o().describe("Expected Buy amount max slippage"),expiration:p(o().describe("Expiration")),fees:Fe,inboundAddress:p(o().describe("Inbound address")),legs:x(ls),memo:p(o().describe("Memo")),meta:jt,providers:x(i.enum(E)),routeId:o().describe("Route ID"),sellAmount:o().describe("Sell amount"),sellAsset:o().describe("Asset to sell"),sourceAddress:p(o().describe("Source address")),targetAddress:p(o().describe("Target address")),totalSlippageBps:h().describe("Total slippage in bps"),tx:p(ss),txType:p(i.enum(Ie)),warnings:Xt}),zt=g({error:p(o().describe("Error message")),providerErrors:p(x(g({errorCode:p(i.enum(ie)),message:p(o()),provider:i.enum(E).optional()}))),quoteId:o().describe("Quote ID"),routes:x(cs)}),Qt=i.object({chainId:i.enum(ce),createdAt:i.date(),id:i.number(),unit:i.string(),value:i.string()}),ds=i.array(Qt),Jt=i.union([Qt,ds]),Po=x(g({chain:i.enum(Ce),decimal:h(),identifier:o(),symbol:o(),ticker:o(),value:o()})),No=i.union([i.object({amount:i.string(),spender:i.string(),tokenIdentifier:i.string(),userWalletAddress:i.string()}),i.object({amount:i.string(),chainId:i.enum(ce),spender:i.string(),tokenContractAddress:i.string(),userWalletAddress:i.string()}),i.object({routeId:i.string()})]),ko=i.object({approvalTransaction:i.optional(i.object({data:i.string(),from:i.string(),gasLimit:i.optional(i.string()),gasPrice:i.optional(i.string()),to:i.string(),value:de})),approvedAmount:i.string(),isApproved:i.boolean()}),ps=i.object({data:i.string().describe("Encoded approval call data"),from:i.string().describe("User wallet address"),gasLimit:i.string().optional().describe("Estimated gas limit"),gasPrice:i.string().optional().describe("Current gas price"),to:i.string().describe("Token contract address"),value:de.describe("ETH value (always '0' for approvals)")}),us=i.object({tx:i.string(),txType:i.literal("STELLAR")}),gs=i.union([ps,us]),kt=i.object({buyAmount:i.string().describe("Buy amount").optional(),buyAmountMaxSlippage:i.string().describe("Buy amount max slippage").optional(),buyAsset:i.string().describe("Asset to buy"),expectedBuyAmount:i.string().describe("Expected Buy amount").optional(),expectedBuyAmountMaxSlippage:i.string().describe("Expected Buy amount max slippage").optional(),fees:Fe,provider:i.enum(E),sellAmount:i.string().describe("Sell amount"),sellAsset:i.string().describe("Asset to sell")}),Zt=kt.extend({estimatedTime:i.optional(Ke),expiration:i.optional(i.string().describe("Expiration")),legs:i.array(kt),providers:i.array(i.enum(E)),routeId:i.string().describe("Route ID"),totalSlippageBps:i.number().describe("Total slippage in bps"),warnings:Xt}).omit({provider:!0}),en=i.object({method:i.string(),payload:i.optional(i.unknown()),url:i.string()}),ms=Zt.extend({meta:Yt,nextActions:i.optional(i.array(en))}),Oo=i.object({error:i.optional(i.string().describe("Error message")),providerErrors:i.optional(i.array(i.object({errorCode:i.optional(i.enum(ie)),message:i.optional(i.string()),provider:i.enum(E).optional()}))),quoteId:i.string().describe("Quote ID"),routes:i.array(ms)}),Do=i.object({providers:i.array(i.enum(E)).optional().describe("Optional list of providers to query for trading pairs"),sellAsset:i.string().describe("Asset identifier to sell (e.g., 'BTC.BTC' or 'ETH.ETH')")}),_s=i.object({chain:i.enum(Ce).describe("Chain the asset is on"),identifier:i.string().describe("Asset identifier (e.g., 'ETH.USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')"),providers:i.array(i.enum(E)).describe("Providers that support this trading pair"),symbol:i.string().describe("Asset symbol"),ticker:i.string().describe("Asset ticker")}),Mo=i.object({buyAssets:i.array(_s).describe("List of assets that can be swapped to"),sellAsset:i.string().describe("The input sell asset identifier")}),tn=Zt.extend({destinationAddress:i.string().describe("Destination address"),inboundAddress:i.optional(i.string().describe("Inbound address")),memo:i.optional(i.string().describe("Memo to include in the transaction")),meta:jt,sourceAddress:i.string().describe("Source address"),targetAddress:i.optional(i.string().describe("Target address")),tx:p(qt),txType:i.optional(i.enum(Ie))}),hs=i.object({data:i.optional(i.record(i.string(),i.string().optional())),errorCode:i.enum(ie),message:i.string().optional(),provider:i.enum(E).optional()}),Lo=i.object({error:i.optional(i.string().describe("Error message")),providerErrors:i.optional(i.array(hs)),quoteId:i.string().describe("Quote ID"),routes:i.array(tn)}),nn=tn.extend({approvalTx:gs.optional().describe("Optional approval transaction required before swap execution"),nextActions:i.optional(i.array(en)),swapId:i.string().describe("The unique swap ID for tracking")});var k=m.extend({dynamicHeader:async()=>{let e=T.get("widgetId"),t=T.get("widgetKey");if(e&&t&&typeof window<"u"){let r=Math.floor(Date.now()/1000),s=window.location.origin,a=await it(t,e,s,r);return{Origin:s,"X-Signature":a,"X-Timestamp":r.toString(),"x-widget-id":e}}let{swapKit:n}=T.get("apiKeys");return n?{"x-api-key":n}:{}}});async function ys(e){let t=await k.post(N("/track"),{json:e});try{let n=Wt.safeParse(t);if(!n.success)throw new b("api_v2_invalid_response",n.error);return n.data}catch(n){return t}}async function bs(e){let{getQuote:t}=T.get("endpoints");if(t)return t(e);let r=T.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",s=await k.post(N(r),{json:e});if(s.error)throw new b("api_v2_server_error",{message:s.error});try{let a=zt.safeParse(s);if(!a.success)throw new b("api_v2_invalid_response",a.error);return a.data}catch{return s}}async function As(e){let{getRouteWithTx:t}=T.get("endpoints");if(t)return t(e);let r=T.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",s=await k.post(N(r),{json:e});try{let a=nn.safeParse(s);if(!a.success)throw new b("api_v2_invalid_response",a.error);return a.data}catch(a){return console.error(new b("api_v2_invalid_response",a)),s}}async function Ss({chain:e,address:t,scamFilter:n=!0}){let{getBalance:r}=T.get("endpoints");if(r)return r({address:t,chain:e});let s=N(`/balance?chain=${e}&address=${t}`),a=await k.get(s),c=Array.isArray(a)?a:[];return n?Os(c):c}function Ts(e){let t=fs(e).with({routeId:pe.string,spender:pe.string},({routeId:n,spender:r})=>N(`/approve?routeId=${n}&sourceAddress=${r}`)).with({assetValue:pe.instanceOf(D),spender:pe.string,userWallet:pe.string},({spender:n,userWallet:r,assetValue:s})=>N(`/approve?tokenIdentifier=${s.toString()}&userWalletAddress=${r}&spender=${n}&amount=${s.getValue("string")}`)).exhaustive();return k.get(t)}function ws(){let e=N("/providers");return k.get(e)}function xs(e){let t=N(`/tokens?provider=${e}`);return k.get(t)}function Rs({query:e,chain:t,page:n,limit:r}){let s=new URLSearchParams({query:e});if(t!==void 0)s.set("chain",t);if(n!==void 0)s.set("page",n.toString());if(r!==void 0)s.set("limit",r.toString());let a=N(`/tokens/search?${s.toString()}`);return k.get(a)}async function vs(e){let t=N("/price"),n=await k.post(t,{json:e});try{let r=$t.safeParse(n);if(!r.success)throw new b("api_v2_invalid_response",r.error);return r.data}catch(r){throw new b("api_v2_invalid_response",r)}}async function Cs(){let e=N("/gas"),t=await k.get(e);try{let n=Jt.safeParse(t);if(!n.success)throw new b("api_v2_invalid_response",n.error);return Array.isArray(n)?n:[n]}catch(n){throw new b("api_v2_invalid_response",n)}}async function Is(e){let{destinationAddress:t}=e;if(!t)throw new b("chainflip_broker_invalid_params");let n=T.get("integrations").chainflip?.brokerUrl||N("/chainflip/broker/channel"),r=await k.post(n,{json:e});try{let s=Ft.safeParse(r);if(!s.success)throw new b("api_v2_invalid_response",s.error);return s.data}catch(s){throw new b("api_v2_invalid_response",s)}}async function Es(e){let{destinationAddress:t}=e;if(!t)throw new b("chainflip_broker_invalid_params");let n=N("/near/channel"),r=await k.post(n,{json:e});try{let s=Kt.safeParse(r);if(!s.success)throw new b("api_v2_invalid_response",s.error);return s.data}catch(s){throw new b("api_v2_invalid_response",s)}}function N(e){let{isDev:t,apiUrl:n,devApiUrl:r}=T.get("envs"),{enabled:s,quoteUrl:a,swapUrl:c}=T.get("localMode");if(s&&e){let[_]=e.split("?");if(_==="/quote"||_==="/v3/quote")return`${a}${e}`;if(_==="/swap"||_==="/v3/swap")return`${c}${e}`}return`${t?r:n}${e}`}function Ps(e){try{return D.from({asset:e.identifier})}catch{return}}var Ns=new Set(["OP.OP"]),ks=/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/im;function Os(e){return e.filter((t)=>{let n=Ps(t);if(!n)return!1;if(Ns.has(n.toString().toUpperCase()))return!0;return(!We.includes(n.chain)||n.isGasAsset||!!n.address)&&!ks.test(n.ticker)})}async function Ds(e){let{getSwapTo:t}=T.get("endpoints");if(t)return t(e);let n=new URLSearchParams({sellAsset:e.sellAsset});if(e.providers?.length)for(let c of e.providers)n.append("providers",c);let r=N(`/swapTo?${n.toString()}`),s=await k.get(r);if(!Array.isArray(s))return{buyAssets:[],sellAsset:e.sellAsset};let a=[];for(let c of s)try{let u=D.from({asset:c});a.push({chain:u.chain,identifier:u.toString(),providers:[],symbol:u.symbol,ticker:u.ticker})}catch{}return{buyAssets:a,sellAsset:e.sellAsset}}var qe={};ze(qe,{getInboundAddresses:()=>Bs,getLastBlock:()=>Hs,getMimirInfo:()=>$s,getNodes:()=>Us,getRunePoolInfo:()=>Ks,getRunePoolProviderInfo:()=>Ws,getTHORNodeTNSDetails:()=>rn,getTNSPreferredAsset:()=>Fs,getTcyClaimer:()=>Ys,getTcyClaimers:()=>js,getTcyStaker:()=>Gs,getTcyStakers:()=>qs,getThorchainQueue:()=>Vs});import{match as Ms}from"ts-pattern";function L(e){let{isStagenet:t}=T.get("envs"),n=T.get("thornodeUrls");return`${Ms({isStagenet:t,type:e}).with({type:"mayachain"},({isStagenet:s})=>s?n.MAYA_STAGENET:n.MAYA).otherwise(({isStagenet:s})=>s?n.THOR_STAGENET:n.THOR)}/${e??"thorchain"}`}function Ls(e){let t=e==="mayachain"?"mayaname":"thorname";return`${L(e)}/${t}`}function Hs(e="thorchain"){return m.get(`${L(e)}/lastblock`)}function Vs(e){return m.get(`${L(e)}/queue`)}function Us(e){return m.get(`${L(e)}/nodes`)}function $s(e){return m.get(`${L(e)}/mimir`)}function Bs(e){return m.get(`${L(e)}/inbound_addresses`)}async function rn({type:e,name:t}){try{return await m.get(`${Ls(e)}/${t}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:t,owner:"",preferred_asset:""}}}async function Fs({type:e,tns:t}){let n=await rn({name:t,type:e});if(!n.preferred_asset||n.preferred_asset===".")return;return D.from({asset:n.preferred_asset,asyncTokenLookup:!0})}function Ks(e){return m.get(`${L(e)}/runepool`)}function Ws({type:e,thorAddress:t}){return m.get(`${L(e)}/rune_provider/${t}`)}function Gs({type:e,address:t}){return m.get(`${L(e)}/tcy_staker/${t}`)}function qs(e){return m.get(`${L(e)}/tcy_stakers`)}function Ys({type:e,address:t}){return m.get(`${L(e)}/tcy_claimer/${t}`)}function js(e){return m.get(`${L(e)}/tcy_claimers`)}var zo={...Ge,mayachainMidgard:Et,thorchainMidgard:It,thornode:qe};
5
+ export{Qs as a,ie as b,Pe as c,E as d,Ne as e,un as f,gn as g,mn as h,b as i,ti as j,ge as k,Ze as l,si as m,_n as n,P as o,T as p,m as q,it as r,Ai as s,Y as t,De as u,kn as v,j as w,Ci as x,Ii as y,Ei as z,Pi as A,Bi as B,Un as C,bt as D,At as E,St as F,ye as G,Me as H,W as I,ae as J,Fi as K,Ki as L,X as M,F as N,zn as O,D as P,to as Q,Re as R,Dt as S,Ie as T,Mt as U,Lt as V,Ht as W,Vt as X,mo as Y,_o as Z,ho as _,fo as $,ee as aa,Ut as ba,yo as ca,$t as da,bo as ea,Ao as fa,Bt as ga,Mr as ha,Ft as ia,Pt as ja,So as ka,Kt as la,Wt as ma,To as na,wo as oa,Fe as pa,Ke as qa,Wr as ra,xo as sa,Ro as ta,Gr as ua,qr as va,Yr as wa,vo as xa,Jr as ya,Zr as za,es as Aa,ts as Ba,Co as Ca,ns as Da,rs as Ea,Gt as Fa,Io as Ga,is as Ha,Eo as Ia,os as Ja,as as Ka,Yt as La,jt as Ma,Xt as Na,cs as Oa,zt as Pa,Qt as Qa,Jt as Ra,No as Sa,ko as Ta,ps as Ua,us as Va,gs as Wa,Oo as Xa,Do as Ya,_s as Za,Mo as _a,tn as $a,hs as ab,Lo as bb,nn as cb,zo as db};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{$ as gr,$a as wn,A as zt,Aa as Hr,B as Vt,Ba as zr,C as Xt,Ca as Vr,D as jt,Da as Xr,E as Gt,Ea as jr,F as qt,Fa as Gr,G as Yt,Ga as qr,H as Zt,Ha as Yr,I as Jt,Ia as Zr,J as Qt,Ja as Jr,K as er,Ka as Qr,L as tr,La as en,M as rr,Ma as tn,N as nr,Na as rn,O as or,Oa as nn,P as ir,Pa as on,Q as ar,Qa as an,R as h,Ra as sn,S as sr,Sa as un,T as ur,Ta as pn,U as pr,Ua as cn,V as cr,Va as mn,W as mr,Wa as dn,X as dr,Xa as ln,Y as lr,Ya as hn,Z as hr,Za as fn,_ as fr,_a as gn,a as v,aa as wr,ab as Pn,b as xt,ba as Pr,bb as vn,c as St,ca as vr,cb as yn,d as Ct,da as yr,db as bn,e as Mt,ea as br,f as N,fa as Er,g as _t,ga as Tr,h as ee,ha as Ar,i as d,ia as xr,j as Wt,ja as Sr,k as p,ka as Cr,l as $t,la as Mr,m as Dt,ma as _r,n as Rt,na as Wr,o as It,oa as $r,p as x,pa as Dr,q as Ot,qa as Rr,r as Ft,ra as Ir,s as Nt,sa as Or,t as M,ta as Fr,u as Lt,ua as Nr,v as Bt,va as Lr,w as kt,wa as Br,x as Ut,xa as kr,y as Kt,ya as Ur,z as Ht,za as Kr}from"./chunk-jrfr92s5.js";export*from"@swapkit/tokens";export*from"@swapkit/types";var L={average:1,fast:1.5,fastest:2};function S(e="average"){let t=x.get("feeMultipliers");if(t&&t[e]!==void 0)return t[e];return L[e]}function B(e="average"){let t=S(e),n=10n,r=BigInt(Math.round(t*10));return{denominator:n,numerator:r}}function ce(e,t="average"){let{numerator:n,denominator:r}=B(t);return e*n/r}function me(e,t="average",n=!1){let r=S(t),o=e*r;return n?Math.floor(o):o}import{Chain as P,EVMChains as k}from"@swapkit/types";import{match as U}from"ts-pattern";function g(e,t){let n=e.length-1;return e.map((o,i)=>{if(i===n&&t.index!==void 0)return t.index;if(i===0&&t.purpose!==void 0)return t.purpose;if(i===2&&t.account!==void 0)return t.account;if(i===3&&t.change!==void 0)return t.change;return o})}var l={bech32:84,legacy:44,p2sh:49,taproot:86},C;((o)=>{o.P2PKH="P2PKH";o.P2SH_P2WPKH="P2SH_P2WPKH";o.P2WPKH="P2WPKH";o.P2TR="P2TR"})(C||={});var K=Object.freeze({["P2PKH"]:{inputSize:148,outputSize:34,purpose:l.legacy,witness:!1},["P2SH_P2WPKH"]:{inputSize:91,outputSize:32,purpose:l.p2sh,witness:!0},["P2WPKH"]:{inputSize:68,outputSize:31,purpose:l.bech32,witness:!0},["P2TR"]:{inputSize:58,outputSize:43,purpose:l.taproot,witness:!0}}),H=Object.values(C);function z(e){if(e===void 0)return;return H.find((t)=>K[t].purpose===e)}function V(e){if(!e)return;if(typeof e!=="string")return e[0];let t=Number.parseInt(e.replace(/^[mM]'?\//,"").split("/")[0]??"",10);return Number.isNaN(t)?void 0:t}function ge(e){return z(V(e))}var X=Object.freeze([P.Near,P.Stellar,P.Sui]),we=Object.freeze([P.Ton]);function j({chain:e,derivationPath:t,index:n=0}){if(t)return t;return g(v[e],X.includes(e)?{account:n}:{index:n})}function G([e,t,n,r,o],{allHardened:i}={}){let s=i?"'":"",u=typeof o!=="number";if(typeof r!=="number")return`m/${e}'/${t}'/${n}'`;return`m/${e}'/${t}'/${n}'/${r}${s}${u?"":`/${o}${s}`}`}function Pe({chain:e,index:t,addressIndex:n=0,type:r}){let o=v[e],i=k.includes(e)?"evm":e===P.Solana?"solana":"other";return U([i,r]).with(["evm","legacy"],["evm","account"],()=>[44,60,0,t]).with(["evm","ledgerLive"],()=>[44,60,t,0,n]).with(["evm","nativeSegwitMiddleAccount"],["evm","segwit"],["evm",void 0],()=>g(o,{index:t})).with(["solana","account"],()=>[44,501,0,t]).with(["solana","legacy"],["solana","ledgerLive"],["solana","nativeSegwitMiddleAccount"],["solana","segwit"],["solana",void 0],()=>g(o,{index:t})).with(["other","nativeSegwitMiddleAccount"],()=>g(o,{account:t,index:n,purpose:l.bech32})).with(["other","segwit"],()=>g(o,{account:0,index:t,purpose:l.p2sh})).with(["other","legacy"],()=>g(o,{account:0,index:t,purpose:l.legacy})).with(["other","account"],["other","ledgerLive"],["other",void 0],()=>j({chain:e,index:t})).exhaustive()}function ve(e){let[t,n]=e.split("/").map((r)=>Number.parseInt(r,10));switch(n){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var ye=Object.freeze(Object.fromEntries(Object.keys(v).map((e)=>[e,G(v[e])])));import{Chain as q,getChainConfig as Y}from"@swapkit/types";function Z({liquidityUnits:e,poolUnits:t,runeDepth:n}){let r=c(e),o=c(t),i=c(n),s=r.mul(i),u=o.mul(o).mul(2),a=o.mul(r).mul(2),m=r.mul(r),f=o.mul(o).mul(o);return s.mul(u.sub(a).add(m)).div(f)}function J({liquidityUnits:e,poolUnits:t,assetDepth:n}){let r=c(e),o=c(t),i=c(n),s=r.mul(i),u=o.mul(o).mul(2),a=o.mul(r).mul(2),m=r.mul(r),f=s.mul(u.sub(a).add(m)),w=o.mul(o).mul(o);return f.div(w)}function Ae({percent:e,runeDepth:t,liquidityUnits:n,poolUnits:r}){return Z({liquidityUnits:n,poolUnits:r,runeDepth:t}).mul(e)}function xe({percent:e,assetDepth:t,liquidityUnits:n,poolUnits:r}){return J({assetDepth:t,liquidityUnits:n,poolUnits:r}).mul(e)}function c(e){return h.fromBigInt(BigInt(e),Y(q.THORChain).baseDecimal)}function Q({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r}){return{assetAmount:c(r).mul(e).div(t),runeAmount:c(n).mul(e).div(t)}}function Se({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r,percent:o}){return Object.fromEntries(Object.entries(Q({assetDepth:r,liquidityUnits:e,poolUnits:t,runeDepth:n})).map(([i,s])=>[i,s.mul(o)]))}function Ce({runeDepth:e,poolUnits:t,assetDepth:n,liquidityUnits:r,runeAmount:o,assetAmount:i}){let s=new h({decimal:8,value:e}),u=new h({decimal:8,value:n}),a=new h({decimal:8,value:t}),m=new h({decimal:8,value:o}),f=new h({decimal:8,value:i}),w=m.mul(u),T=f.mul(s),D=m.mul(f),R=s.mul(u),I=a.mul(w.add(T.add(D.mul(2)))),O=w.add(T.add(R.mul(2))),A=I.div(O),E=c(r).add(A);if(A.getBaseValue("number")===0)return E.div(a).getBaseValue("number");let F=a.add(E);return E.div(F).getBaseValue("number")}function Me({runeAmount:e,assetAmount:t,runeDepth:n,assetDepth:r}){if(e==="0"||t==="0"||n==="0"||r==="0")return 0;let o=c(n),i=c(r),s=c(t),u=c(e),a=s.mul(o).sub(i.mul(u)),m=i.mul(u).add(o.mul(i));return Math.abs(a.div(m).getBaseValue("number"))}import{Chain as y}from"@swapkit/types";import{match as te}from"ts-pattern";function Ie({type:e,address:t}){return`${e}:${t}`}function Oe({address:e,unbondAmount:t}){return`${"UNBOND"}:${e}:${t}`}function Fe(e){return b("POOL+",e)}function Ne({chain:e,symbol:t,address:n,...r}){let o=re({chain:e,symbol:t}),i=n?`:${n}:`:":";return b(`${"+"}:${o}${i}`,r)}function Le({chain:e,symbol:t,ticker:n,basisPoints:r,targetAsset:o}){let i=e==="ETH"&&n!=="ETH"?`${n}-${t.slice(-3)}`:t,s=o?`:${o}`:"";return`${"-"}:${e}.${i}:${r}${s}`}function Be({basisPoints:e,...t}){return b(`${"POOL-"}:${e}`,t)}function ke({name:e,chain:t,address:n,owner:r}){let o=`${"~"}:${e}:${t}:${n}`,i=r?`:${r}`:"";return`${o}${i}`}function Ue({name:e,chain:t,asset:n,payout:r,owner:o}){return`${"~"}:${e}:${t}:${r}:${o}:${n}`}function Ke(e,{address:t}){return`${e}:${t}`}function He(e,{unstakeBps:t,...n}){let r=t?`:${t}`:"",o=`${e}${r}`;return b(`${o}`,n)}function b(e,{affiliateAddress:t,affiliateBasisPoints:n}={}){let r=`${e}${t?`:${t}:${n||0}`:""}`;return r.endsWith(":")?r.slice(0,-1):r}function re({chain:e,symbol:t}){return te(e).with(y.Bitcoin,y.Dogecoin,y.Litecoin,()=>e.slice(0,1).toLowerCase()).with(y.BitcoinCash,()=>"c").otherwise(()=>`${e}.${t}`)}function ze(e){if(e<0)throw new d({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:e}});return 10+e}function Ve(e){if(e<0)throw new d({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:e}});return Math.round((10+e*1.0512)*10000000000)/10000000000}function Xe(e){if(e.length>30)return!1;let t=/^[a-zA-Z0-9+_-]+$/g;return!!e.match(t)}import{getChainConfig as _}from"@swapkit/types";function Je(){return typeof window.ethereum<"u"}function Qe(e){return ne().includes(e)}function ne(){let e=window?.ethereum&&!window.ethereum?.isBraveWallet,t=window?.ctrl||window?.ethereum?.__XDEFI,n=window?.vultisig,r=window?.ethereum?.isBraveWallet,o=window?.ethereum?.isTrust||window?.trustwallet,i=window?.ethereum?.overrideIsMetaMask&&window?.ethereum?.selectedProvider?.isCoinbaseWallet||window?.coinbaseWalletExtension,s=window?.bitkeep?.ethereum,u=window?.$onekey?.ethereum,a=[];if(e)a.push(p.METAMASK);if(t)a.push(p.CTRL);if(n)a.push(p.VULTISIG);if(r)a.push(p.BRAVE);if(o)a.push(p.TRUSTWALLET_WEB);if(i)a.push(p.COINBASE_WEB);if(se())a.push(p.OKX_MOBILE);if(s)a.push(p.BITGET);if(u)a.push(p.ONEKEY);return a}async function oe(e,t,n){let r=_(t);try{await W({method:"wallet_switchEthereumChain",params:[{chainId:r.chainIdHex}],provider:e})}catch(o){if(!n)throw new d("helpers_failed_to_switch_network",{error:o,reason:"networkParams not provided"});await ae(e,n)}}function et({chains:e,supportedChains:t,walletType:n}){let r=e.filter((i)=>!i||t.includes(i));if(r.length===0)throw new d("wallet_chain_not_supported",{chain:e.join(", "),wallet:n});let o=e.filter((i)=>!t.includes(i));return M({condition:o.length>0,id:`wallet_chain_not_supported_${n}`,warning:`${n} wallet does not support the following chains: ${o.join(", ")}. These chains will be ignored.`}),r}function ie(e,t,n){return async(...r)=>{let{chainIdHex:o}=_(n);if((await t.getNetwork()).chainId.toString()===o)return e(...r);try{await oe(t,n)}catch(i){throw new d({errorKey:"helpers_failed_to_switch_network",info:{error:i}})}return e(...r)}}function tt({toolbox:e,chain:t,provider:n,methodNames:r=[]}){let i=[...r,"approve","approvedAmount","call","sendTransaction","transfer","isApproved","approvedAmount","EIP1193SendTransaction","getFeeData","broadcastTransaction","estimateCall","estimateGasLimit","estimateGasPrices","createContractTxObject"].reduce((s,u)=>{if(!e[u])return s;let a=e[u];if(typeof a!=="function")return s;let m=ie(a,n,t);return{...s,[u]:m}},{});return{...e,...i}}function ae(e,t){return W({method:"wallet_addEthereumChain",params:[t],provider:e})}function rt(e){window.ethereum?.on("accountsChanged",()=>e()),window.ctrl?.ethereum.on("accountsChanged",()=>e())}function nt(){let{isTrust:e,isBraveWallet:t,__XDEFI:n,overrideIsMetaMask:r,selectedProvider:o}=window?.ethereum||{};if(e)return p.TRUSTWALLET_WEB;if(t)return p.BRAVE;if(r&&o?.isCoinbaseWallet)return p.COINBASE_WEB;if(n)return p.CTRL;if(window?.$onekey?.ethereum)return p.ONEKEY;return p.METAMASK}function ot(){let e=[];function t(r){if(e.map((o)=>o.info.uuid).includes(r.detail.info.uuid))return;e.push(r.detail)}window.addEventListener("eip6963:announceProvider",t),window.dispatchEvent(new Event("eip6963:requestProvider"));function n(){window.removeEventListener("eip6963:announceProvider",t)}return{providers:e,removeEIP6963EventListener:n}}function se(){let e=navigator.userAgent,t=/iphone|ipad|ipod|ios/i.test(e),n=/android|XiaoMi|MiuiBrowser/i.test(e),r=t||n,o=/OKApp/i.test(e);return r&&o}function W({provider:e,params:t,method:n}){if(!e?.send)throw new d("helpers_not_found_provider");let r=t?Array.isArray(t)?t:[t]:[];return e.send(n,r)}export{X as ACCOUNT_INDEXED_CHAINS,gr as ApiV2ErrorSchema,cn as ApprovalTransactionSchema,_t as ApproveMode,un as ApproveRequestParams,pn as ApproveResponseSchema,ir as AssetValue,wr as AssetValueSchema,nr as BigIntArithmetics,Ar as BrokerDepositChannelParamsSchema,Qr as ChainflipMetadataSchema,Pr as CoinGeckoMetadataSchema,Vt as CommonAssetStrings,Ur as CosmosTransactionSchema,L as DEFAULT_FEE_MULTIPLIERS,Tr as DepositChannelParamsSchema,xr as DepositChannelResponseSchema,ye as DerivationPath,Br as EVMTransactionDetailsParamsSchema,kr as EVMTransactionDetailsSchema,Nr as EVMTransactionSchema,xt as ErrorCode,Rr as EstimatedTimeSchema,N as FeeOption,Mt as FeeTypeEnum,Dr as FeesSchema,sn as GasResponseSchema,an as GasSchema,Vr as HYPERCORE_USDC_TOKEN_ID,Xr as HyperCoreEip712TypedDataSchema,jr as HyperCoreSendAssetActionSchema,qr as HyperCoreSendAssetTransactionSchema,Gr as HyperCoreTypedDataTransactionSchema,Rt as LedgerErrorCode,ee as MemoType,Sr as NearDepositChannelParamsSchema,Cr as NearDepositChannelResultSchema,Mr as NearSwapResponseSchema,v as NetworkDerivationPath,Er as PriceRequestSchema,yr as PriceResponseSchema,sr as PriorityLabel,cr as ProviderAction,Ct as ProviderName,br as QuoteRequestSchema,nn as QuoteResponseRouteItem,on as QuoteResponseSchema,wn as QuoteRouteV2Response,vn as QuoteV2ResponseSchema,ln as QuoteV3ResponseSchema,Ot as RequestClient,Yr as RouteLegSchema,Zr as RouteLegWithoutAddressesSchema,Jr as RouteQuoteMetadataAssetSchema,en as RouteQuoteMetadataSchema,tn as RouteQuoteMetadataV2Schema,Pn as RouteQuoteProviderErrorSchema,ur as RouteQuoteTxType,rn as RouteQuoteWarningSchema,we as SINGLE_WALLET_CHAINS,x as SKConfig,Kr as StarknetTransactionSchema,mn as StellarApprovalTransactionSchema,dn as SwapApprovalTransactionSchema,bn as SwapKitApi,d as SwapKitError,h as SwapKitNumber,yn as SwapRouteV2ResponseSchema,fn as SwapToAssetSchema,hn as SwapToRequestSchema,gn as SwapToResponseSchema,Hr as TONTransactionMessageSchema,zr as TONTransactionSchema,vr as TokenDetailsMetadataSchema,lr as TokenSchema,_r as TrackerResponseSchema,fr as TrackingRequestQuerySchema,hr as TrackingRequestSchema,dr as TrackingStatus,$r as TransactionDTOSchema,Wr as TransactionSchema,Lr as TronTransactionSchema,mr as TxnStatus,pr as TxnType,l as UTXOPurpose,C as UTXOScriptType,K as UTXO_SCRIPT_TYPES,H as UTXO_SCRIPT_TYPE_LIST,p as WalletOption,St as WarningCodeEnum,Lt as _rpcCache,rt as addAccountsChangedCallback,ae as addEVMWalletNetwork,me as applyFeeMultiplier,ce as applyFeeMultiplierToBigInt,Jt as assetFromString,jt as decodeABIDynamicString,Xt as decodeABIString,G as derivationPathToString,Gt as fetchTokenInfo,et as filterSupportedChains,tr as findAssetBy,rr as formatBigIntToSafeValue,Zt as getAssetType,J as getAsymmetricAssetShare,xe as getAsymmetricAssetWithdrawAmount,Z as getAsymmetricRuneShare,Ae as getAsymmetricRuneWithdrawAmount,zt as getChainIdentifier,Yt as getCommonAssetInfo,Pe as getDerivationPathFor,ot as getEIP6963Wallets,nt as getETHDefaultWallet,Ce as getEstimatedPoolShare,Ht as getExplorerAddressUrl,Kt as getExplorerTxUrl,S as getFeeMultiplier,B as getFeeMultiplierAsBigInt,Me as getLiquiditySlippage,Ve as getMAYANameCost,Ne as getMemoForDeposit,Ie as getMemoForLeaveAndBond,Ue as getMemoForNamePreferredAssetRegister,ke as getMemoForNameRegister,Fe as getMemoForRunePoolDeposit,Be as getMemoForRunePoolWithdraw,Ke as getMemoForTcyClaim,He as getMemoForTcyStake,Oe as getMemoForUnbond,Le as getMemoForWithdraw,ar as getMinAmountByChain,V as getPurposeFromPath,kt as getRPCUrl,Bt as getRPCUrlSync,Q as getSymmetricPoolShare,Se as getSymmetricWithdraw,ze as getTHORNameCost,er as getTokenLogoURI,ge as getUTXOScriptTypeForPath,z as getUTXOScriptTypeForPurpose,ve as getWalletFormatFor,Ut as initializeRPCUrlsWithFallback,Qe as isDetected,qt as isGasAsset,Ir as isTransactionValue,Je as isWeb3Detected,ne as listWeb3EVMWallets,se as okxMobileEnabled,Qt as parseSymbolForAddress,Or as parseTransactionValue,tt as prepareNetworkSwitch,W as providerRequest,Wt as registerErrorCodes,Dt as registerWalletOption,j as resolveDerivationPath,Ft as signWidgetRequest,$t as subscribeWalletOptionRegistration,It as swapKitConfigStore,oe as switchEVMWalletNetwork,Fr as toHexTransactionValue,g as updateDerivationPath,or as validateIdentifier,Xe as validateTNS,M as warnOnce,ie as wrapMethodWithNetworkSwitch,Nt as wrapWithThrow};
1
+ import{$ as gr,$a as wn,A as zt,Aa as Hr,B as Vt,Ba as zr,C as Xt,Ca as Vr,D as jt,Da as Xr,E as Gt,Ea as jr,F as qt,Fa as Gr,G as Yt,Ga as qr,H as Zt,Ha as Yr,I as Jt,Ia as Zr,J as Qt,Ja as Jr,K as er,Ka as Qr,L as tr,La as en,M as rr,Ma as tn,N as nr,Na as rn,O as or,Oa as nn,P as ir,Pa as on,Q as ar,Qa as an,R as h,Ra as sn,S as sr,Sa as un,T as ur,Ta as pn,U as pr,Ua as cn,V as cr,Va as mn,W as mr,Wa as dn,X as dr,Xa as ln,Y as lr,Ya as hn,Z as hr,Za as fn,_ as fr,_a as gn,a as v,aa as wr,ab as Pn,b as xt,ba as Pr,bb as vn,c as St,ca as vr,cb as yn,d as Ct,da as yr,db as bn,e as Mt,ea as br,f as N,fa as Er,g as _t,ga as Tr,h as ee,ha as Ar,i as d,ia as xr,j as Wt,ja as Sr,k as p,ka as Cr,l as $t,la as Mr,m as Dt,ma as _r,n as Rt,na as Wr,o as It,oa as $r,p as x,pa as Dr,q as Ot,qa as Rr,r as Ft,ra as Ir,s as Nt,sa as Or,t as M,ta as Fr,u as Lt,ua as Nr,v as Bt,va as Lr,w as kt,wa as Br,x as Ut,xa as kr,y as Kt,ya as Ur,z as Ht,za as Kr}from"./chunk-dna905ac.js";export*from"@swapkit/tokens";export*from"@swapkit/types";var L={average:1,fast:1.5,fastest:2};function S(e="average"){let t=x.get("feeMultipliers");if(t&&t[e]!==void 0)return t[e];return L[e]}function B(e="average"){let t=S(e),n=10n,r=BigInt(Math.round(t*10));return{denominator:n,numerator:r}}function ce(e,t="average"){let{numerator:n,denominator:r}=B(t);return e*n/r}function me(e,t="average",n=!1){let r=S(t),o=e*r;return n?Math.floor(o):o}import{Chain as P,EVMChains as k}from"@swapkit/types";import{match as U}from"ts-pattern";function g(e,t){let n=e.length-1;return e.map((o,i)=>{if(i===n&&t.index!==void 0)return t.index;if(i===0&&t.purpose!==void 0)return t.purpose;if(i===2&&t.account!==void 0)return t.account;if(i===3&&t.change!==void 0)return t.change;return o})}var l={bech32:84,legacy:44,p2sh:49,taproot:86},C;((o)=>{o.P2PKH="P2PKH";o.P2SH_P2WPKH="P2SH_P2WPKH";o.P2WPKH="P2WPKH";o.P2TR="P2TR"})(C||={});var K=Object.freeze({["P2PKH"]:{inputSize:148,outputSize:34,purpose:l.legacy,witness:!1},["P2SH_P2WPKH"]:{inputSize:91,outputSize:32,purpose:l.p2sh,witness:!0},["P2WPKH"]:{inputSize:68,outputSize:31,purpose:l.bech32,witness:!0},["P2TR"]:{inputSize:58,outputSize:43,purpose:l.taproot,witness:!0}}),H=Object.values(C);function z(e){if(e===void 0)return;return H.find((t)=>K[t].purpose===e)}function V(e){if(!e)return;if(typeof e!=="string")return e[0];let t=Number.parseInt(e.replace(/^[mM]'?\//,"").split("/")[0]??"",10);return Number.isNaN(t)?void 0:t}function ge(e){return z(V(e))}var X=Object.freeze([P.Near,P.Stellar,P.Sui]),we=Object.freeze([P.Ton]);function j({chain:e,derivationPath:t,index:n=0}){if(t)return t;return g(v[e],X.includes(e)?{account:n}:{index:n})}function G([e,t,n,r,o],{allHardened:i}={}){let s=i?"'":"",u=typeof o!=="number";if(typeof r!=="number")return`m/${e}'/${t}'/${n}'`;return`m/${e}'/${t}'/${n}'/${r}${s}${u?"":`/${o}${s}`}`}function Pe({chain:e,index:t,addressIndex:n=0,type:r}){let o=v[e],i=k.includes(e)?"evm":e===P.Solana?"solana":"other";return U([i,r]).with(["evm","legacy"],["evm","account"],()=>[44,60,0,t]).with(["evm","ledgerLive"],()=>[44,60,t,0,n]).with(["evm","nativeSegwitMiddleAccount"],["evm","segwit"],["evm",void 0],()=>g(o,{index:t})).with(["solana","account"],()=>[44,501,0,t]).with(["solana","legacy"],["solana","ledgerLive"],["solana","nativeSegwitMiddleAccount"],["solana","segwit"],["solana",void 0],()=>g(o,{index:t})).with(["other","nativeSegwitMiddleAccount"],()=>g(o,{account:t,index:n,purpose:l.bech32})).with(["other","segwit"],()=>g(o,{account:0,index:t,purpose:l.p2sh})).with(["other","legacy"],()=>g(o,{account:0,index:t,purpose:l.legacy})).with(["other","account"],["other","ledgerLive"],["other",void 0],()=>j({chain:e,index:t})).exhaustive()}function ve(e){let[t,n]=e.split("/").map((r)=>Number.parseInt(r,10));switch(n){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var ye=Object.freeze(Object.fromEntries(Object.keys(v).map((e)=>[e,G(v[e])])));import{Chain as q,getChainConfig as Y}from"@swapkit/types";function Z({liquidityUnits:e,poolUnits:t,runeDepth:n}){let r=c(e),o=c(t),i=c(n),s=r.mul(i),u=o.mul(o).mul(2),a=o.mul(r).mul(2),m=r.mul(r),f=o.mul(o).mul(o);return s.mul(u.sub(a).add(m)).div(f)}function J({liquidityUnits:e,poolUnits:t,assetDepth:n}){let r=c(e),o=c(t),i=c(n),s=r.mul(i),u=o.mul(o).mul(2),a=o.mul(r).mul(2),m=r.mul(r),f=s.mul(u.sub(a).add(m)),w=o.mul(o).mul(o);return f.div(w)}function Ae({percent:e,runeDepth:t,liquidityUnits:n,poolUnits:r}){return Z({liquidityUnits:n,poolUnits:r,runeDepth:t}).mul(e)}function xe({percent:e,assetDepth:t,liquidityUnits:n,poolUnits:r}){return J({assetDepth:t,liquidityUnits:n,poolUnits:r}).mul(e)}function c(e){return h.fromBigInt(BigInt(e),Y(q.THORChain).baseDecimal)}function Q({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r}){return{assetAmount:c(r).mul(e).div(t),runeAmount:c(n).mul(e).div(t)}}function Se({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r,percent:o}){return Object.fromEntries(Object.entries(Q({assetDepth:r,liquidityUnits:e,poolUnits:t,runeDepth:n})).map(([i,s])=>[i,s.mul(o)]))}function Ce({runeDepth:e,poolUnits:t,assetDepth:n,liquidityUnits:r,runeAmount:o,assetAmount:i}){let s=new h({decimal:8,value:e}),u=new h({decimal:8,value:n}),a=new h({decimal:8,value:t}),m=new h({decimal:8,value:o}),f=new h({decimal:8,value:i}),w=m.mul(u),T=f.mul(s),D=m.mul(f),R=s.mul(u),I=a.mul(w.add(T.add(D.mul(2)))),O=w.add(T.add(R.mul(2))),A=I.div(O),E=c(r).add(A);if(A.getBaseValue("number")===0)return E.div(a).getBaseValue("number");let F=a.add(E);return E.div(F).getBaseValue("number")}function Me({runeAmount:e,assetAmount:t,runeDepth:n,assetDepth:r}){if(e==="0"||t==="0"||n==="0"||r==="0")return 0;let o=c(n),i=c(r),s=c(t),u=c(e),a=s.mul(o).sub(i.mul(u)),m=i.mul(u).add(o.mul(i));return Math.abs(a.div(m).getBaseValue("number"))}import{Chain as y}from"@swapkit/types";import{match as te}from"ts-pattern";function Ie({type:e,address:t}){return`${e}:${t}`}function Oe({address:e,unbondAmount:t}){return`${"UNBOND"}:${e}:${t}`}function Fe(e){return b("POOL+",e)}function Ne({chain:e,symbol:t,address:n,...r}){let o=re({chain:e,symbol:t}),i=n?`:${n}:`:":";return b(`${"+"}:${o}${i}`,r)}function Le({chain:e,symbol:t,ticker:n,basisPoints:r,targetAsset:o}){let i=e==="ETH"&&n!=="ETH"?`${n}-${t.slice(-3)}`:t,s=o?`:${o}`:"";return`${"-"}:${e}.${i}:${r}${s}`}function Be({basisPoints:e,...t}){return b(`${"POOL-"}:${e}`,t)}function ke({name:e,chain:t,address:n,owner:r}){let o=`${"~"}:${e}:${t}:${n}`,i=r?`:${r}`:"";return`${o}${i}`}function Ue({name:e,chain:t,asset:n,payout:r,owner:o}){return`${"~"}:${e}:${t}:${r}:${o}:${n}`}function Ke(e,{address:t}){return`${e}:${t}`}function He(e,{unstakeBps:t,...n}){let r=t?`:${t}`:"",o=`${e}${r}`;return b(`${o}`,n)}function b(e,{affiliateAddress:t,affiliateBasisPoints:n}={}){let r=`${e}${t?`:${t}:${n||0}`:""}`;return r.endsWith(":")?r.slice(0,-1):r}function re({chain:e,symbol:t}){return te(e).with(y.Bitcoin,y.Dogecoin,y.Litecoin,()=>e.slice(0,1).toLowerCase()).with(y.BitcoinCash,()=>"c").otherwise(()=>`${e}.${t}`)}function ze(e){if(e<0)throw new d({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:e}});return 10+e}function Ve(e){if(e<0)throw new d({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:e}});return Math.round((10+e*1.0512)*10000000000)/10000000000}function Xe(e){if(e.length>30)return!1;let t=/^[a-zA-Z0-9+_-]+$/g;return!!e.match(t)}import{getChainConfig as _}from"@swapkit/types";function Je(){return typeof window.ethereum<"u"}function Qe(e){return ne().includes(e)}function ne(){let e=window?.ethereum&&!window.ethereum?.isBraveWallet,t=window?.ctrl||window?.ethereum?.__XDEFI,n=window?.vultisig,r=window?.ethereum?.isBraveWallet,o=window?.ethereum?.isTrust||window?.trustwallet,i=window?.ethereum?.overrideIsMetaMask&&window?.ethereum?.selectedProvider?.isCoinbaseWallet||window?.coinbaseWalletExtension,s=window?.bitkeep?.ethereum,u=window?.$onekey?.ethereum,a=[];if(e)a.push(p.METAMASK);if(t)a.push(p.CTRL);if(n)a.push(p.VULTISIG);if(r)a.push(p.BRAVE);if(o)a.push(p.TRUSTWALLET_WEB);if(i)a.push(p.COINBASE_WEB);if(se())a.push(p.OKX_MOBILE);if(s)a.push(p.BITGET);if(u)a.push(p.ONEKEY);return a}async function oe(e,t,n){let r=_(t);try{await W({method:"wallet_switchEthereumChain",params:[{chainId:r.chainIdHex}],provider:e})}catch(o){if(!n)throw new d("helpers_failed_to_switch_network",{error:o,reason:"networkParams not provided"});await ae(e,n)}}function et({chains:e,supportedChains:t,walletType:n}){let r=e.filter((i)=>!i||t.includes(i));if(r.length===0)throw new d("wallet_chain_not_supported",{chain:e.join(", "),wallet:n});let o=e.filter((i)=>!t.includes(i));return M({condition:o.length>0,id:`wallet_chain_not_supported_${n}`,warning:`${n} wallet does not support the following chains: ${o.join(", ")}. These chains will be ignored.`}),r}function ie(e,t,n){return async(...r)=>{let{chainIdHex:o}=_(n);if((await t.getNetwork()).chainId.toString()===o)return e(...r);try{await oe(t,n)}catch(i){throw new d({errorKey:"helpers_failed_to_switch_network",info:{error:i}})}return e(...r)}}function tt({toolbox:e,chain:t,provider:n,methodNames:r=[]}){let i=[...r,"approve","approvedAmount","call","sendTransaction","transfer","isApproved","approvedAmount","EIP1193SendTransaction","getFeeData","broadcastTransaction","estimateCall","estimateGasLimit","estimateGasPrices","createContractTxObject"].reduce((s,u)=>{if(!e[u])return s;let a=e[u];if(typeof a!=="function")return s;let m=ie(a,n,t);return{...s,[u]:m}},{});return{...e,...i}}function ae(e,t){return W({method:"wallet_addEthereumChain",params:[t],provider:e})}function rt(e){window.ethereum?.on("accountsChanged",()=>e()),window.ctrl?.ethereum.on("accountsChanged",()=>e())}function nt(){let{isTrust:e,isBraveWallet:t,__XDEFI:n,overrideIsMetaMask:r,selectedProvider:o}=window?.ethereum||{};if(e)return p.TRUSTWALLET_WEB;if(t)return p.BRAVE;if(r&&o?.isCoinbaseWallet)return p.COINBASE_WEB;if(n)return p.CTRL;if(window?.$onekey?.ethereum)return p.ONEKEY;return p.METAMASK}function ot(){let e=[];function t(r){if(e.map((o)=>o.info.uuid).includes(r.detail.info.uuid))return;e.push(r.detail)}window.addEventListener("eip6963:announceProvider",t),window.dispatchEvent(new Event("eip6963:requestProvider"));function n(){window.removeEventListener("eip6963:announceProvider",t)}return{providers:e,removeEIP6963EventListener:n}}function se(){let e=navigator.userAgent,t=/iphone|ipad|ipod|ios/i.test(e),n=/android|XiaoMi|MiuiBrowser/i.test(e),r=t||n,o=/OKApp/i.test(e);return r&&o}function W({provider:e,params:t,method:n}){if(!e?.send)throw new d("helpers_not_found_provider");let r=t?Array.isArray(t)?t:[t]:[];return e.send(n,r)}export{X as ACCOUNT_INDEXED_CHAINS,gr as ApiV2ErrorSchema,cn as ApprovalTransactionSchema,_t as ApproveMode,un as ApproveRequestParams,pn as ApproveResponseSchema,ir as AssetValue,wr as AssetValueSchema,nr as BigIntArithmetics,Ar as BrokerDepositChannelParamsSchema,Qr as ChainflipMetadataSchema,Pr as CoinGeckoMetadataSchema,Vt as CommonAssetStrings,Ur as CosmosTransactionSchema,L as DEFAULT_FEE_MULTIPLIERS,Tr as DepositChannelParamsSchema,xr as DepositChannelResponseSchema,ye as DerivationPath,Br as EVMTransactionDetailsParamsSchema,kr as EVMTransactionDetailsSchema,Nr as EVMTransactionSchema,xt as ErrorCode,Rr as EstimatedTimeSchema,N as FeeOption,Mt as FeeTypeEnum,Dr as FeesSchema,sn as GasResponseSchema,an as GasSchema,Vr as HYPERCORE_USDC_TOKEN_ID,Xr as HyperCoreEip712TypedDataSchema,jr as HyperCoreSendAssetActionSchema,qr as HyperCoreSendAssetTransactionSchema,Gr as HyperCoreTypedDataTransactionSchema,Rt as LedgerErrorCode,ee as MemoType,Sr as NearDepositChannelParamsSchema,Cr as NearDepositChannelResultSchema,Mr as NearSwapResponseSchema,v as NetworkDerivationPath,Er as PriceRequestSchema,yr as PriceResponseSchema,sr as PriorityLabel,cr as ProviderAction,Ct as ProviderName,br as QuoteRequestSchema,nn as QuoteResponseRouteItem,on as QuoteResponseSchema,wn as QuoteRouteV2Response,vn as QuoteV2ResponseSchema,ln as QuoteV3ResponseSchema,Ot as RequestClient,Yr as RouteLegSchema,Zr as RouteLegWithoutAddressesSchema,Jr as RouteQuoteMetadataAssetSchema,en as RouteQuoteMetadataSchema,tn as RouteQuoteMetadataV2Schema,Pn as RouteQuoteProviderErrorSchema,ur as RouteQuoteTxType,rn as RouteQuoteWarningSchema,we as SINGLE_WALLET_CHAINS,x as SKConfig,Kr as StarknetTransactionSchema,mn as StellarApprovalTransactionSchema,dn as SwapApprovalTransactionSchema,bn as SwapKitApi,d as SwapKitError,h as SwapKitNumber,yn as SwapRouteV2ResponseSchema,fn as SwapToAssetSchema,hn as SwapToRequestSchema,gn as SwapToResponseSchema,Hr as TONTransactionMessageSchema,zr as TONTransactionSchema,vr as TokenDetailsMetadataSchema,lr as TokenSchema,_r as TrackerResponseSchema,fr as TrackingRequestQuerySchema,hr as TrackingRequestSchema,dr as TrackingStatus,$r as TransactionDTOSchema,Wr as TransactionSchema,Lr as TronTransactionSchema,mr as TxnStatus,pr as TxnType,l as UTXOPurpose,C as UTXOScriptType,K as UTXO_SCRIPT_TYPES,H as UTXO_SCRIPT_TYPE_LIST,p as WalletOption,St as WarningCodeEnum,Lt as _rpcCache,rt as addAccountsChangedCallback,ae as addEVMWalletNetwork,me as applyFeeMultiplier,ce as applyFeeMultiplierToBigInt,Jt as assetFromString,jt as decodeABIDynamicString,Xt as decodeABIString,G as derivationPathToString,Gt as fetchTokenInfo,et as filterSupportedChains,tr as findAssetBy,rr as formatBigIntToSafeValue,Zt as getAssetType,J as getAsymmetricAssetShare,xe as getAsymmetricAssetWithdrawAmount,Z as getAsymmetricRuneShare,Ae as getAsymmetricRuneWithdrawAmount,zt as getChainIdentifier,Yt as getCommonAssetInfo,Pe as getDerivationPathFor,ot as getEIP6963Wallets,nt as getETHDefaultWallet,Ce as getEstimatedPoolShare,Ht as getExplorerAddressUrl,Kt as getExplorerTxUrl,S as getFeeMultiplier,B as getFeeMultiplierAsBigInt,Me as getLiquiditySlippage,Ve as getMAYANameCost,Ne as getMemoForDeposit,Ie as getMemoForLeaveAndBond,Ue as getMemoForNamePreferredAssetRegister,ke as getMemoForNameRegister,Fe as getMemoForRunePoolDeposit,Be as getMemoForRunePoolWithdraw,Ke as getMemoForTcyClaim,He as getMemoForTcyStake,Oe as getMemoForUnbond,Le as getMemoForWithdraw,ar as getMinAmountByChain,V as getPurposeFromPath,kt as getRPCUrl,Bt as getRPCUrlSync,Q as getSymmetricPoolShare,Se as getSymmetricWithdraw,ze as getTHORNameCost,er as getTokenLogoURI,ge as getUTXOScriptTypeForPath,z as getUTXOScriptTypeForPurpose,ve as getWalletFormatFor,Ut as initializeRPCUrlsWithFallback,Qe as isDetected,qt as isGasAsset,Ir as isTransactionValue,Je as isWeb3Detected,ne as listWeb3EVMWallets,se as okxMobileEnabled,Qt as parseSymbolForAddress,Or as parseTransactionValue,tt as prepareNetworkSwitch,W as providerRequest,Wt as registerErrorCodes,Dt as registerWalletOption,j as resolveDerivationPath,Ft as signWidgetRequest,$t as subscribeWalletOptionRegistration,It as swapKitConfigStore,oe as switchEVMWalletNetwork,Fr as toHexTransactionValue,g as updateDerivationPath,or as validateIdentifier,Xe as validateTNS,M as warnOnce,ie as wrapMethodWithNetworkSwitch,Nt as wrapWithThrow};