@swapkit/helpers 5.1.0 → 5.2.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 +13 -0
- package/dist/api/index.js +1 -1
- package/dist/chunk-q0s1vae8.js +5 -0
- package/dist/index.js +1 -1
- package/dist/types/modules/swapKitError.d.ts +2 -0
- package/dist/types/types/derivationPath.d.ts +11 -1
- package/dist/types/utils/derivationPath.d.ts +98 -11
- package/package.json +4 -4
- package/dist/chunk-sht0fjw7.js +0 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# @swapkit/helpers
|
|
2
2
|
|
|
3
|
+
## 5.2.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Update generated token lists. (via @swapkit/tokens@5.0.5)
|
|
8
|
+
|
|
9
|
+
## 5.2.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- [`1c3d941`](https://github.com/swapkit/sdk/commit/1c3d941eecfe123aa29fd34cd710f848fcb1122f) Thanks [@ice-chillios](https://github.com/ice-chillios)! - **Derived addresses change for a non-zero index or an explicit derivation path.** Index 0 without a path is unchanged everywhere, which is why this ships as a minor rather than a major. EVM (every chain, including the OP-stack ones) declared `derivationPath` and `index` and read neither, so every phrase collapsed onto `m/44'/60'/0'/0/0`. Sui and Ripple had no path or index parameter at all and always used their library's default path. Cardano applied `index` to the address index but never read `derivationPath` and hardcoded the account to 0. Zcash overwrote the last slot of an explicit path with `index`. All of these now honour supported values, so the address returned for a non-zero index — or for an explicit path — differs from earlier versions. Nothing is lost: the funds stay at the previous address, which is unchanged and still reachable by requesting index 0 with no path. Cached addresses, saved address books, deposit instructions and in-flight quotes built against the old behaviour will no longer match, so audit anything that persisted an address before upgrading.
|
|
14
|
+
- Update generated token lists. (via @swapkit/tokens@5.0.4)
|
|
15
|
+
|
|
3
16
|
## 5.1.0
|
|
4
17
|
|
|
5
18
|
### Minor Changes
|
package/dist/api/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as j,$a as ja,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 $,S as a,Sa as aa,T as b,Ta as ba,U as c,Ua as ca,V as d,Va as da,W as e,Wa as ea,X as f,Xa as fa,Y as g,Ya as ga,Z as h,Za as ha,_ as i,_a as ia,aa as k,ab as ka,ba as l,bb as la,ca as m,cb as ma,da as n,db as na,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-
|
|
1
|
+
import{$ as j,$a as ja,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 $,S as a,Sa as aa,T as b,Ta as ba,U as c,Ua as ca,V as d,Va as da,W as e,Wa as ea,X as f,Xa as fa,Y as g,Ya as ga,Z as h,Za as ha,_ as i,_a as ia,aa as k,ab as ka,ba as l,bb as la,ca as m,cb as ma,da as n,db as na,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-q0s1vae8.js";export{D as toHexTransactionValue,C as parseTransactionValue,B as isTransactionValue,c as TxnType,e as TxnStatus,F as TronTransactionSchema,x as TransactionSchema,y as TransactionDTOSchema,f as TrackingStatus,h as TrackingRequestSchema,i as TrackingRequestQuerySchema,w as TrackerResponseSchema,g as TokenSchema,m as TokenDetailsMetadataSchema,L as TONTransactionSchema,K as TONTransactionMessageSchema,ia as SwapToResponseSchema,ga as SwapToRequestSchema,ha as SwapToAssetSchema,ma as SwapRouteV2ResponseSchema,na as SwapKitApi,ea as SwapApprovalTransactionSchema,da as StellarApprovalTransactionSchema,J as StarknetTransactionSchema,X as RouteQuoteWarningSchema,b as RouteQuoteTxType,ka as RouteQuoteProviderErrorSchema,W as RouteQuoteMetadataV2Schema,V as RouteQuoteMetadataSchema,T as RouteQuoteMetadataAssetSchema,S as RouteLegWithoutAddressesSchema,R as RouteLegSchema,fa as QuoteV3ResponseSchema,la as QuoteV2ResponseSchema,ja as QuoteRouteV2Response,Z as QuoteResponseSchema,Y as QuoteResponseRouteItem,o as QuoteRequestSchema,d as ProviderAction,a as PriorityLabel,n as PriceResponseSchema,p as PriceRequestSchema,v as NearSwapResponseSchema,u as NearDepositChannelResultSchema,t as NearDepositChannelParamsSchema,P as HyperCoreTypedDataTransactionSchema,Q as HyperCoreSendAssetTransactionSchema,O as HyperCoreSendAssetActionSchema,N as HyperCoreEip712TypedDataSchema,M as HYPERCORE_USDC_TOKEN_ID,_ as GasSchema,$ as GasResponseSchema,z as FeesSchema,A as EstimatedTimeSchema,E as EVMTransactionSchema,H as EVMTransactionDetailsSchema,G as EVMTransactionDetailsParamsSchema,s as DepositChannelResponseSchema,q as DepositChannelParamsSchema,I as CosmosTransactionSchema,l as CoinGeckoMetadataSchema,U as ChainflipMetadataSchema,r as BrokerDepositChannelParamsSchema,k as AssetValueSchema,ba as ApproveResponseSchema,aa as ApproveRequestParams,ca as ApprovalTransactionSchema,j as ApiV2ErrorSchema};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
var HT=Object.defineProperty;var LT=(N)=>N;function PT(N,A){this[N]=LT.bind(null,A)}var lN=(N,A)=>{for(var T in A)HT(N,T,{get:A[T],enumerable:!0,configurable:!0,set:PT.bind(A,T)})};var rN=((N)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(N,{get:(A,T)=>(typeof require<"u"?require:A)[T]}):N)(function(N){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+N+'" is not supported')});import{Chain as bN,getChainConfig as AH}from"@swapkit/types";import{AllChains as oT,Chain as b,EVMChains as CT,getChainConfig as IN}from"@swapkit/types";import{match as KN}from"ts-pattern";import{Chain as B,EVMChains as VT,getChainConfig as p,UTXOChains as xT}from"@swapkit/types";import{match as PN}from"ts-pattern";import{AllChains as eN,Chain as aN,getChainConfig as $T,MAYAConfig as YT,StagenetChain as _N,StagenetMAYAConfig as NA,StagenetTHORConfig as AA,THORConfig as MT}from"@swapkit/types";import{createStore as _T}from"zustand/vanilla";import{AllChains as FT,getChainConfig as OT}from"@swapkit/types";var hL=Object.freeze(Object.fromEntries(FT.map((N)=>[N,Object.freeze(OT(N).networkDerivationPath)])));var LN;((I)=>{I.unknownError="unknownError";I.test_error="test_error";I.providerDetailsError="providerDetailsError";I.blockHeaderNotFound="blockHeaderNotFound";I.blockHashNotFoundAtHeight="blockHashNotFoundAtHeight";I.blockHashNotFoundAtHash="blockHashNotFoundAtHash";I.txHashMissing="txHashMissing";I.assetValueMissingInfo="assetValueMissingInfo";I.invalidAsset="invalidAsset";I.blockIsRequired="blockIsRequired";I.currentBlockHeaderNotFound="currentBlockHeaderNotFound";I.failedToRetrieveBalance="failedToRetrieveBalance";I.failedToRetrieveBlock="failedToRetrieveBlock";I.failedToRetrieveFees="failedToRetrieveFees";I.notImplementedBCH="notImplementedBCH";I.notImplementedDoge="notImplementedDoge";I.noPoolsFound="noPoolsFound";I.noVaultsFound="noVaultsFound";I.noTxFound="noTxFound";I.noInputCoinFound="noInputCoinFound";I.noBlockDataFound="noBlockDataFound";I.multipleCosmosMessages="multipleCosmosMessages";I.heightOrHashNotProvided="heightOrHashNotProvided";I.unknownDenom="unknownDenom";I.invalidBlockHeight="invalidBlockHeight";I.timestampExtrinsicNoArgumentsForBlock="timestampExtrinsicNoArgumentsForBlock";I.timestampExtrinsicNoTimestampForBlock="timestampExtrinsicNoTimestampForBlock";I.noTimestampExtrinsicForHash="noTimestampExtrinsicForHash";I.timestampExtrinsicNoArgumentsForHash="timestampExtrinsicNoArgumentsForHash";I.txMemoUndefined="txMemoUndefined";I.txMemoIncorrect="txMemoIncorrect";I.txTypeNotFound="txTypeNotFound";I.txNoMessage="txNoMessage";I.txNotFound="txNotFound";I.txReceiptNotFound="txReceiptNotFound";I.txParsingError="txParsingError";I.txLogsParsingError="txLogsParsingError";I.blockNotFound="blockNotFound";I.balanceNotFound="balanceNotFound";I.configError="configError";I.synthSwapDisallowed="synthSwapDisallowed";I.providerQuoteTimeout="providerQuoteTimeout";I.noQuoteResponse="noQuoteResponse";I.noPoolAssetsFound="noPoolAssetsFound";I.noThorchainPools="noThorchainPools";I.noMayachainPools="noMayachainPools";I.noThorchainNetworkInfo="noThorchainNetworkInfo";I.invalidAffiliateFee="invalidAffiliateFee";I.invalidBuyAssetAddress="invalidBuyAssetAddress";I.invalidSellAssetAddress="invalidSellAssetAddress";I.invalidSourceAddress="invalidSourceAddress";I.invalidDestinationAddress="invalidDestinationAddress";I.sourceAddressIsSmartContract="sourceAddressIsSmartContract";I.destinationAddressIsSmartContract="destinationAddressIsSmartContract";I.invalidChainId="invalidChainId";I.unsupportedChainId="unsupportedChainId";I.unsupportedEVMChainId="unsupportedEVMChainId";I.unsupportedMethod="unsupportedMethod";I.unsupportedProvider="unsupportedProvider";I.invalidParamsForMethod="invalidParamsForMethod";I.unsupportedAdapter="unsupportedAdapter";I.noWhitelistTokens="noWhitelistTokens";I.failedFetchGasPrice="failedFetchGasPrice";I.failedToCreateDepositChannel="failedToCreateDepositChannel";I.noProviderDetailsFound="noProviderDetailsFound";I.noTokenListsFound="noTokenListsFound";I.tokenNotFound="tokenNotFound";I.tokenPriceNotFound="tokenPriceNotFound";I.tokenPriceFailedToUpdate="tokenPriceFailedToUpdate";I.swapAmountTooSmall="swapAmountTooSmall";I.legsArrayIsEmpty="legsArrayIsEmpty";I.failedToFetchQuoteForLeg="failedToFetchQuoteForLeg";I.noBlockHeaderFound="noBlockHeaderFound";I.failedToSimulateSwap="failedToSimulateSwap";I.addressScreeningFailed="addressScreeningFailed";I.noLiquidtyProvidersFound="noLiquidtyProvidersFound";I.insufficientLiquidity="insufficientLiquidity";I.noInboundDataFound="noInbounDataFound";I.noInboundAddressesFound="noInboundAddressesFound";I.noInboundAddressFoundForChain="noInboundAddressFoundForChain";I.noLastBlocksFound="noLastBlocksFound";I.noVersionFound="noVersionFound";I.noConstantsFound="noConstantsFound";I.noMimirsFound="noMimirsFound";I.noRoutesFound="noRoutesFound";I.quoteNotFound="quoteNotFound";I.ledgerSignFailed="ledgerSignFailed";I.ledgerWrongPayload="ledgerWrongPayload";I.ledgerFetchSwapFailed="ledgerFetchSwapFailed";I.failedToFetchTx="failedToFetchTx";I.failedBuildTransactionDetails="failedBuildTransactionDetails";I.noLegsForRoute="noLegsForRoute";I.noRouterAddressFound="noRouterAddressFound";I.noAggregatorAddressFound="noAggregatorAddressFound";I.noContractInstanceFound="noContractInstanceFound";I.noContractAddressFound="noContractAddressFound";I.invalidAffiliate="invalidAffiliate";I.thornameAffiliate="thornameAffiliate";I.providerNotfound="No provider found";I.noRecordFound="No Record found";I.slippageTooLow="Slippage too low";I.tradingHalted="tradingHalted";I.noWrappedGasAsset="noWrappedGasAsset";I.aggregatorAddressNotFound="aggregatorAddressNotFound";I.routerAddressNotFound="routerAddressNotFound";I.dummyAddressNotFound="dummyAddressNotFound";I.trackerError="trackerError";I.thorchainPoolUnavailable="thorchainPoolUnavailable";I.noOhlcvDataFound="noOhlcvDataFound";I.noTradingPairs="noTradingPairs";I.noLendingAvailability="noLendingAvailability";I.lendingRepayTooSmall="lendingRepayTooSmall";I.missingState="missingState";I.ledgerSwapNotFound="ledgerSwapNotFound";I.ledgerSwapNotReadyForTracking="ledgerSwapNotReadyForTracking";I.errorEstimatingGas="errorEstimatingGas";I.apiKeyInvalid="apiKeyInvalid";I.apiKeyFailedToUpdate="apiKeyFailedToUpdate";I.apiKeyExpired="apiKeyExpired";I.unauthorized="unauthorized";I.failedToCreateMemo="failedToCreateMemo";I.radixIncorrectInstructions="radixIncorrectInstructions";I.radixTxMissedParam="radixTxMissedParam";I.radixTxMissedAccount="radixTxMissedAccount";I.radixManifestParseError="radixManifestParseError";I.radixManifestBuildError="radixManifestBuildError";I.invalidAddressForChain="invalidAddressForChain";I.riskyAddress="riskyAddress";I.noRoutesToProcess="noRoutesToProcess";I.sellAssetAmountTooSmall="sellAssetAmountTooSmall";I.missingPrivateKey="missingPrivateKey";I.noMemoPriceProtection="noMemoPriceProtection"})(LN||={});var ZN;((H)=>{H.highSlippage="highSlippage";H.highPriceImpact="highPriceImpact";H.insufficientBalance="insufficientBalance"})(ZN||={});var j;((z)=>{z.CHAINFLIP="CHAINFLIP";z.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";z.JUPITER="JUPITER";z.MAYACHAIN="MAYACHAIN";z.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";z.ONEINCH="ONEINCH";z.PANCAKESWAP="PANCAKESWAP";z.SUSHISWAP_V2="SUSHISWAP_V2";z.THORCHAIN="THORCHAIN";z.THORCHAIN_STREAMING="THORCHAIN_STREAMING";z.TRADERJOE_V2="TRADERJOE_V2";z.UNISWAP_V2="UNISWAP_V2";z.UNISWAP_V3="UNISWAP_V3";z.NEAR="NEAR";z.GARDEN="GARDEN";z.OKX="OKX";z.HARBOR="HARBOR";z.FLASHNET="FLASHNET";z.MAYAN="MAYAN"})(j||={});var wN;((M)=>{M.LIQUIDITY="liquidity";M.NETWORK="network";M.INBOUND="inbound";M.OUTBOUND="outbound";M.AFFILIATE="affiliate";M.TAX="tax";M.PRIORITY="priority";M.SERVICE="service"})(wN||={});var IT;((H)=>{H.Average="average";H.Fast="fast";H.Fastest="fastest"})(IT||={});var RT;((T)=>{T.Approve="approve";T.CheckOnly="checkOnly"})(RT||={});var BT;((u)=>{u.NAME_REGISTER="~";u.BOND="BOND";u.DEPOSIT="+";u.LEAVE="LEAVE";u.UNBOND="UNBOND";u.WITHDRAW="-";u.RUNEPOOL_DEPOSIT="POOL+";u.RUNEPOOL_WITHDRAW="POOL-";u.CLAIM_TCY="tcy";u.STAKE_TCY="tcy+";u.UNSTAKE_TCY="tcy-"})(BT||={});var iN={core_estimated_max_spendable_chain_not_supported:10001,core_extend_error:10002,core_inbound_data_not_found:10003,core_approve_asset_address_or_from_not_found:10004,core_plugin_not_found:10005,core_plugin_swap_not_found:10006,core_approve_asset_target_invalid:10007,core_explorer_unsupported_chain:10008,core_verify_message_not_supported:10009,core_chain_halted:10010,core_wallet_connection_not_found:10101,core_wallet_ctrl_not_installed:10102,core_wallet_evmwallet_not_installed:10103,core_wallet_walletconnect_not_installed:10104,core_wallet_keystore_not_installed:10105,core_wallet_ledger_not_installed:10106,core_wallet_trezor_not_installed:10107,core_wallet_keplr_not_installed:10108,core_wallet_okx_not_installed:10109,core_wallet_keepkey_not_installed:10110,core_wallet_talisman_not_installed:10111,core_wallet_not_keypair_wallet:10112,core_wallet_sign_message_not_supported:10113,core_wallet_connection_failed:10114,core_wallet_create_not_supported:10115,core_wallet_sign_typed_data_not_supported:10116,core_swap_invalid_params:10201,core_swap_route_not_complete:10202,core_swap_asset_not_recognized:10203,core_swap_contract_not_found:10204,core_swap_route_transaction_not_found:10205,core_swap_contract_not_supported:10206,core_swap_transaction_error:10207,core_swap_quote_mode_not_supported:10208,core_transaction_deposit_error:10301,core_transaction_create_liquidity_base_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_base_address:10306,core_transaction_add_liquidity_base_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_invalid_sender_address:10313,core_transaction_deposit_server_error:10314,core_transaction_user_rejected:10315,core_transaction_failed:10316,core_transaction_invalid_recipient_address:10317,wallet_connection_rejected_by_user:20001,wallet_missing_api_key:20002,wallet_chain_not_supported:20003,wallet_missing_params:20004,wallet_provider_not_found:20005,wallet_failed_to_add_or_switch_network:20006,wallet_ledger_connection_error:20101,wallet_ledger_connection_claimed:20102,wallet_ledger_get_address_error:20103,wallet_ledger_device_not_found:20104,wallet_ledger_device_locked:20105,wallet_ledger_transport_error:20106,wallet_ledger_public_key_error:20107,wallet_ledger_derivation_path_error:20108,wallet_ledger_signing_error:20109,wallet_ledger_app_not_open:20110,wallet_ledger_invalid_response:20111,wallet_ledger_method_not_supported:20112,wallet_ledger_invalid_params:20113,wallet_ledger_invalid_signature:20114,wallet_ledger_no_provider:20115,wallet_ledger_pubkey_not_found:20116,wallet_ledger_transport_not_defined:20117,wallet_ledger_webusb_not_supported:20118,wallet_ledger_chain_not_supported:20119,wallet_ledger_invalid_asset:20120,wallet_ledger_invalid_account:20121,wallet_ledger_address_not_found:20122,wallet_ledger_failed_to_get_address:20123,wallet_ledger_webhid_not_supported:20124,wallet_phantom_not_found:20201,wallet_ctrl_not_found:20301,wallet_ctrl_send_transaction_no_address:20302,wallet_ctrl_contract_address_not_provided:20303,wallet_ctrl_asset_not_defined:20304,wallet_walletconnect_project_id_not_specified:20401,wallet_walletconnect_connection_not_established:20402,wallet_walletconnect_namespace_not_supported:20403,wallet_walletconnect_chain_not_supported:20404,wallet_walletconnect_invalid_method:20405,wallet_walletconnect_method_not_supported:20406,wallet_trezor_failed_to_sign_transaction:20501,wallet_trezor_derivation_path_not_supported:20502,wallet_trezor_failed_to_get_address:20503,wallet_trezor_transport_error:20504,wallet_trezor_method_not_supported:20505,wallet_trezor_failed_to_get_public_key:20506,wallet_talisman_not_enabled:20601,wallet_talisman_not_found:20602,wallet_polkadot_not_found:20701,wallet_radix_not_found:20801,wallet_radix_transaction_failed:20802,wallet_radix_invalid_manifest:20803,wallet_radix_method_not_supported:20804,wallet_radix_no_account:20805,wallet_keepkey_not_found:20901,wallet_keepkey_asset_not_defined:20902,wallet_keepkey_contract_address_not_provided:20903,wallet_keepkey_send_transaction_no_address:20904,wallet_keepkey_derivation_path_error:20905,wallet_keepkey_signing_error:20906,wallet_keepkey_transport_error:20907,wallet_keepkey_unsupported_chain:20908,wallet_keepkey_invalid_response:20909,wallet_keepkey_chain_not_supported:20910,wallet_keepkey_signer_not_found:20911,wallet_keepkey_no_accounts:20912,wallet_keepkey_method_not_supported:20913,wallet_keepkey_invalid_params:20914,wallet_keepkey_config_not_found:20915,wallet_keepkey_no_provider:20916,wallet_keepkey_account_not_found:20917,wallet_keepkey_failed_to_get_public_key:20918,wallet_bitkeep_not_found:21001,wallet_bitkeep_failed_to_switch_network:21002,wallet_bitkeep_no_accounts:21003,wallet_passkeys_sign_transaction_error:21101,wallet_passkeys_not_found:21102,wallet_passkeys_no_address:21103,wallet_passkeys_request_canceled:21104,wallet_passkeys_signature_canceled:21105,wallet_passkeys_failed_to_switch_network:21106,wallet_passkeys_chain_not_supported:21107,wallet_passkeys_instance_missing:21108,wallet_onekey_not_found:21201,wallet_onekey_sign_transaction_error:21202,wallet_okx_not_found:21301,wallet_okx_chain_not_supported:21302,wallet_okx_failed_to_switch_network:21303,wallet_okx_no_accounts:21304,wallet_keplr_not_found:21401,wallet_keplr_chain_not_supported:21402,wallet_keplr_signer_not_found:21403,wallet_keplr_no_accounts:21404,wallet_cosmostation_not_found:21501,wallet_cosmostation_chain_not_supported:21502,wallet_cosmostation_evm_provider_not_found:21503,wallet_cosmostation_keplr_provider_not_found:21504,wallet_cosmostation_no_accounts:21505,wallet_cosmostation_no_evm_accounts:21506,wallet_cosmostation_no_evm_address:21507,wallet_cosmostation_signer_not_found:21508,wallet_passkey_not_supported:21601,wallet_passkey_connection_failed:21602,wallet_coinbase_not_found:21701,wallet_coinbase_chain_not_supported:21702,wallet_coinbase_method_not_supported:21703,wallet_coinbase_no_accounts:21704,wallet_evm_extensions_failed_to_switch_network:21801,wallet_evm_extensions_no_provider:21802,wallet_evm_extensions_not_found:21803,wallet_keystore_invalid_password:21901,wallet_keystore_unsupported_version:21902,wallet_near_extensions_failed_to_switch_network:22001,wallet_near_extensions_no_provider:22002,wallet_near_extensions_not_found:22003,wallet_near_method_not_supported:22004,wallet_petra_not_found:22201,wallet_vultisig_not_found:22101,wallet_vultisig_contract_address_not_provided:22102,wallet_vultisig_asset_not_defined:22103,wallet_vultisig_send_transaction_no_address:22104,wallet_xaman_not_configured:23001,wallet_xaman_not_connected:23002,wallet_xaman_auth_failed:23003,wallet_xaman_connection_failed:23004,wallet_xaman_transaction_failed:23005,wallet_xaman_monitoring_failed:23006,wallet_tronlink_request_accounts_failed:24001,wallet_tronlink_locked:24002,chainflip_channel_error:30001,chainflip_unknown_asset:30002,chainflip_broker_invalid_params:30101,chainflip_broker_recipient_error:30102,chainflip_broker_register:30103,chainflip_broker_tx_error:30104,chainflip_broker_withdraw:30105,chainflip_broker_fund_only_flip_supported:30106,chainflip_broker_fund_invalid_address:30107,thorchain_chain_halted:40001,thorchain_trading_halted:40002,thorchain_asset_is_not_tcy:40003,thorchain_swapin_router_required:40101,thorchain_swapin_vault_required:40102,thorchain_swapin_memo_required:40103,thorchain_swapin_token_required:40104,thorchain_preferred_asset_payout_required:40105,toolbox_cosmos_account_not_found:50101,toolbox_cosmos_invalid_fee:50102,toolbox_cosmos_invalid_params:50103,toolbox_cosmos_no_signer:50104,toolbox_cosmos_not_supported:50105,toolbox_cosmos_signer_not_defined:50106,toolbox_cosmos_validate_address_prefix_not_found:50107,toolbox_cosmos_verify_signature_no_pubkey:50108,toolbox_evm_error_estimating_gas_limit:50201,toolbox_evm_error_sending_transaction:50202,toolbox_evm_gas_estimation_error:50203,toolbox_evm_invalid_gas_asset_address:50204,toolbox_evm_invalid_params:50205,toolbox_evm_invalid_transaction:50206,toolbox_evm_no_abi_fragment:50207,toolbox_evm_no_contract_address:50208,toolbox_evm_no_fee_data:50209,toolbox_evm_no_from_address:50210,toolbox_evm_no_gas_price:50211,toolbox_evm_no_signer_address:50212,toolbox_evm_no_signer:50213,toolbox_evm_no_to_address:50214,toolbox_evm_not_supported:50215,toolbox_evm_provider_not_eip1193_compatible:50216,toolbox_evm_invalid_eip7702_authorization:50217,toolbox_utxo_api_error:50301,toolbox_utxo_broadcast_failed:50302,toolbox_utxo_insufficient_balance:50303,toolbox_utxo_invalid_address:50304,toolbox_utxo_invalid_params:50305,toolbox_utxo_invalid_transaction:50306,toolbox_utxo_no_signer:50307,toolbox_utxo_not_supported:50308,toolbox_utxo_tx_not_found:50309,toolbox_utxo_rbf_not_supported:50310,toolbox_utxo_tx_not_replaceable:50311,toolbox_utxo_tx_already_confirmed:50312,toolbox_utxo_rbf_fee_too_low:50313,toolbox_utxo_rbf_insufficient_change:50314,toolbox_solana_no_signer:50401,toolbox_substrate_not_supported:50501,toolbox_substrate_transfer_error:50502,toolbox_radix_method_not_supported:50601,toolbox_ripple_get_balance_error:50701,toolbox_ripple_rpc_not_configured:50702,toolbox_ripple_signer_not_found:50703,toolbox_ripple_asset_not_supported:50704,toolbox_ripple_broadcast_error:50705,toolbox_ripple_get_trust_lines_error:50706,toolbox_ripple_invalid_trust_line_limit:50707,toolbox_tron_no_signer:50801,toolbox_tron_invalid_token_identifier:50802,toolbox_tron_token_transfer_failed:50803,toolbox_tron_transaction_creation_failed:50804,toolbox_tron_trongrid_api_error:50805,toolbox_tron_approve_failed:50806,toolbox_tron_invalid_token_contract:50807,toolbox_tron_allowance_check_failed:50808,toolbox_tron_invalid_transaction_integrity:50809,toolbox_tron_broadcast_failed:50810,toolbox_hypercore_no_signer:51001,toolbox_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 jN(N){return JSON.stringify(N,(A,T)=>typeof T==="bigint"?T.toString():T)}class U extends Error{static ErrorCode=iN;errorKey;info;constructor(N,A){let T=typeof N==="string",H=T?N:N.errorKey,L=T?void 0:N.info,O=`${H}${L?`: ${jN(L)}`:""}`;super(O);if(Object.setPrototypeOf(this,U.prototype),this.name="SwapKitError",this.errorKey=H,this.info=L,this.cause=A,A){let R=A instanceof Error?`${A.message}${A.cause?` (${A.cause})`:""}`:jN(A);console.error(`SwapKitError [${H}]: ${R}`)}else if(L)console.error(`SwapKitError [${H}]: ${jN(L)}`)}}function iL(N){let A=iN;for(let[T,H]of Object.entries(N)){if(Object.hasOwn(A,T)){if(A[T]===H)continue;throw new U({errorKey:"helpers_invalid_params",info:{code:H,existingCode:A[T],key:T}})}let L=Object.keys(A).find((O)=>A[O]===H);if(L)throw new U({errorKey:"helpers_invalid_params",info:{code:H,existingKey:L,key:T}});A[T]=H}}var MN={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"},VN=new Set;function sN(N){return VN.add(N),()=>VN.delete(N)}function eL(N,A){let T=MN;if(Object.hasOwn(T,N)){if(T[N]===A)return;throw new U({errorKey:"helpers_invalid_params",info:{existingValue:T[N],key:N,value:A}})}T[N]=A;for(let H of VN)H(A)}var GT;((H)=>{H[H.NoError=36864]="NoError";H[H.LockedDevice=21781]="LockedDevice";H[H.TC_NotFound=65535]="TC_NotFound"})(GT||={});var ST=eN.reduce((N,A)=>{if(!N.THOR_STAGENET)N[_N.Maya]=NA.rpcUrls,N[_N.THORChain]=AA.rpcUrls;return N[A]=$T(A).rpcUrls,N},{}),DT={[aN.THORChain]:MT.nodeUrl,[aN.Maya]:YT.nodeUrl,[_N.THORChain]:AA.nodeUrl,[_N.Maya]:NA.nodeUrl},TA={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:eN,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:ST,thornodeUrls:DT,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(MN),widgetId:"",widgetKey:""},V=_T((N)=>({...TA,setApiKey:(A,T)=>N((H)=>({apiKeys:{...H.apiKeys,[A]:T}})),setConfig:(A)=>N((T)=>({apiKeys:{...T.apiKeys,...A?.apiKeys},chains:T.chains.concat(A?.chains||[]),endpoints:{...T.endpoints,...A?.endpoints},envs:{...T.envs,...A?.envs},feeMultipliers:A?.feeMultipliers||T.feeMultipliers,integrations:{...T.integrations,...A?.integrations},localMode:{...T.localMode,...A?.localMode},rpcUrls:{...T.rpcUrls,...A?.rpcUrls},thornodeUrls:{...T.thornodeUrls,...A?.thornodeUrls},v3SwapFlow:{...T.v3SwapFlow,...A?.v3SwapFlow},wallets:T.wallets.concat(A?.wallets||[]),widgetId:A?.widgetId||T.widgetId,widgetKey:A?.widgetKey||T.widgetKey})),setEndpoint:(A,T)=>N((H)=>({endpoints:{...H.endpoints,[A]:T}})),setEnv:(A,T)=>N((H)=>({envs:{...H.envs,[A]:T}})),setFeeMultipliers:(A)=>N(()=>({feeMultipliers:A})),setIntegrationConfig:(A,T)=>N((H)=>({integrations:{...H.integrations,[A]:T}})),setRequestOptions:(A)=>N((T)=>({requestOptions:{retry:{...T.requestOptions.retry,...A.retry},timeoutMs:A.timeoutMs||T.requestOptions.timeoutMs}})),setRpcUrl:(A,T)=>N((H)=>({rpcUrls:{...H.rpcUrls,[A]:T}})),setThornodeUrl:(A,T)=>N((H)=>({thornodeUrls:{...H.thornodeUrls,[A]:T}})),setWidgetId:(A)=>N({widgetId:A}),setWidgetKey:(A)=>N({widgetKey:A})}));sN((N)=>{V.setState((A)=>A.wallets.includes(N)?A:{wallets:[...A.wallets,N]})});var g={get:(N)=>V.getState()[N],getState:V.getState,reinitialize:()=>V.setState({...TA,wallets:Object.values(MN)}),set:(N)=>V.getState().setConfig(N),setApiKey:(N,A)=>V.getState().setApiKey(N,A),setEndpoint:(N,A)=>V.getState().setEndpoint(N,A),setEnv:(N,A)=>V.getState().setEnv(N,A),setFeeMultipliers:(N)=>V.getState().setFeeMultipliers(N),setIntegrationConfig:(N,A)=>V.getState().setIntegrationConfig(N,A),setRequestOptions:(N)=>V.getState().setRequestOptions(N),setRpcUrl:(N,A)=>V.getState().setRpcUrl(N,A),setThornodeUrl:(N,A)=>V.getState().setThornodeUrl(N,A),setWidgetId:(N)=>V.getState().setWidgetId(N),setWidgetKey:(N)=>V.getState().setWidgetKey(N)};var UT=(N)=>new Promise((A)=>setTimeout(A,N)),XT=(N,{baseDelay:A,backoffMultiplier:T,maxDelay:H})=>Math.min(A*T**N,H);function uT(N,A){if(N instanceof Error&&N.name==="AbortError")return!0;if(N instanceof TypeError)return!0;if(A===429)return!0;if(A&&A>=500&&A<600)return!0;return!1}var gT=async(N,A)=>{let T=await fetch(N,A),H;try{H=await T.json()}catch{if(!T.ok)throw new U({errorKey:"helpers_invalid_response",info:{status:T.status,statusText:T.statusText}},{status:T.status,statusText:T.statusText});return{}}if(!T.ok){let O={data:H?.data,error:H?.error,message:H?.message,status:T.status};throw new U({errorKey:H?.error||"helpers_invalid_response",info:O},O)}let L=H?.routes?.length||H?.result||H?.data&&!H?.error;if(H?.error&&!L){let O={data:H.data,error:H.error,message:H.message,status:T.status};throw new U({errorKey:H.error,info:O},O)}if(H?.providerErrors?.length||H?.error&&L)console.warn("[SwapKit] Partial errors in response:",H.providerErrors||H.error);return H};function SN(N,A={}){return async function(H,L={}){let{searchParams:O,json:R,body:$,headers:M,dynamicHeader:J,retry:X,timeoutMs:u,abortController:w,onError:E,onSuccess:K,responseHandler:Q,...Z}={...A,...L},TN=g.get("requestOptions"),d={...TN.retry,...X},z=!!R||H.endsWith(".json"),$N=ET(H,O),dN=J?await J():{},HN=WT(z,{...M,...dN}),h=z?JSON.stringify(R):$,QN;for(let YN=0;YN<=d.maxRetries;YN++){let hN=w||new AbortController,cN=setTimeout(()=>hN.abort(),u||TN.timeoutMs);try{let m=await gT($N,{...Z,body:h,headers:HN,method:N,signal:hN.signal});return clearTimeout(cN),K?.(m)||Q?.(m)||m}catch(m){clearTimeout(cN),QN=m;let TT=m?.cause?.status;if(YN>=d.maxRetries||!uT(m,TT))return E?E(m):Promise.reject(m);await UT(XT(YN,d))}}return E?E(QN):Promise.reject(QN)}}function WT(N,A){return{...A,...N&&{"Content-Type":"application/json"}}}function ET(N,A){let T=new URL(N);if(A)T.search=new URLSearchParams(A).toString();return T.toString()}var _={extend:(N)=>({extend:(A)=>_.extend({...N,...A}),get:SN("GET",N),post:SN("POST",N)}),get:SN("GET"),post:SN("POST")};async function HA(N,A,T,H){let L=`${A}:${T}:${H}`,O=new TextEncoder,R=await crypto.subtle.importKey("raw",O.encode(N),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),$=await crypto.subtle.sign("HMAC",R,O.encode(L));return Array.from(new Uint8Array($)).map((M)=>M.toString(16).padStart(2,"0")).join("")}import{Chain as D,CosmosChains as OA,EVMChains as IA,getChainConfig as RA,StagenetChains as bT,SubstrateChains as zT,UTXOChains as BA}from"@swapkit/types";import{match as DN}from"ts-pattern";function _P(N,A){try{return N()}catch(T){if(A)throw new U(A,T);return}}var LA=new Set;function c({condition:N,id:A,warning:T}){if(N){if(LA.has(A))return;console.warn(T),LA.add(A)}}function JT(N){return DN(N).with(...IA,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...BA,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...OA,...bT,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(D.Polkadot,D.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(D.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(D.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(D.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(D.Aleo,D.Aptos,D.Tron,D.Radix,D.Stellar,()=>"").with(D.Hype,()=>({type:"meta"})).with(D.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(D.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(D.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new U("helpers_chain_not_supported",{chain:N})})}function PA(N){return DN(N).with(D.Aptos,()=>"/-/healthy").with(D.Aleo,()=>"/mainnet/block/height/latest").with(D.Hype,()=>"/info").with(D.Radix,()=>"/status/network-configuration").with(D.Stellar,()=>"").with(D.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function FA(N,A){try{let T=A.startsWith("wss")?A.replace("wss","https"):A;if(N===D.Aleo||N===D.Stellar)return(await fetch(`${T}${PA(N)}`,{cache:"no-store",method:"GET",signal:AbortSignal.timeout(3000)})).ok;return(await fetch(`${T}${PA(N)}`,{body:JSON.stringify(JT(N)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var xN=new Map,QT=120000;function ZT(N){let[A=""]=g.get("rpcUrls")[N];if(!A)throw c({condition:!0,id:"helpers_chain_no_public_or_set_rpc_url",warning:`No public or set RPC URL found for chain. Please ensure you configured rpcUrls for ${N}.`}),new U("helpers_chain_no_public_or_set_rpc_url",{chain:N});let T=xN.get(N);if(T&&Date.now()-T.timestamp<QT)return T.url;return xN.set(N,{timestamp:Date.now(),url:A}),A}async function l(N){let A=ZT(N),[,...T]=g.get("rpcUrls")[N];if(await FA(N,A))return A;for(let L of T)if(await FA(N,L))return xN.set(N,{timestamp:Date.now(),url:L}),L;throw new U("helpers_chain_rpc_connection_failed",{chain:N,fallbackUrls:T,primaryRpcUrl:A})}function WP(N){c({condition:!0,id:"initializeRPCUrlsWithFallback",warning:"initializeRPCUrlsWithFallback is deprecated. Use static { rpcUrls, fallbackRpcUrls } SwapKit init config or dynamic SKConfig.setRpcUrl/setFallbackRpcUrl to configure RPC endpoints."})}function EP({chain:N,txHash:A}){let{explorerUrl:T}=RA(N);return DN(N).with(...OA,D.Solana,()=>`${T}/tx/${A.startsWith("0x")?A.slice(2):A}`).with(...IA,...zT,()=>`${T}/tx/${A.startsWith("0x")?A:`0x${A}`}`).with(...BA,D.Radix,D.Tron,()=>`${T}/transaction/${A.toLowerCase()}`).with(D.Near,()=>`${T}/txns/${A}`).with(D.Ripple,()=>`${T}/transactions/${A}`).with(D.Stellar,()=>`${T}/explorer/public/tx/${A}`).with(D.Sui,()=>`${T}/txblock/${A}`).with(D.Cardano,D.Hype,D.Spark,D.Ton,()=>`${T}/tx/${A}`).otherwise(()=>"")}function bP({chain:N,address:A}){let{explorerUrl:T}=RA(N);return DN(N).with(D.Solana,D.Sui,D.Radix,()=>`${T}/account/${A}`).with(D.Stellar,()=>`${T}/explorer/public/account/${A}`).otherwise(()=>`${T}/address/${A}`)}function zP(N){switch(N){case D.THORChain:return`${N}.RUNE`;case D.Cosmos:return`${N}.ATOM`;case D.BinanceSmartChain:return`${N}`;default:return`${N}.${N}`}}import{keccak_256 as wT}from"@noble/hashes/sha3.js";import{bytesToHex as jT}from"@noble/hashes/utils.js";var GA=/^(0x)?[0-9a-fA-F]{40}$/;function UN(N){if(typeof N!=="string"||!GA.test(N))throw Error(`invalid address: ${N}`);let A=N.toLowerCase().replace(/^0x/,""),T=jT(wT(new TextEncoder().encode(A))),H=[...A].map((O,R)=>Number.parseInt(T[R]??"0",16)>=8?O.toUpperCase():O).join(""),L=N.replace(/^0x/,"");if(/[A-F]/.test(L)&&/[a-f]/.test(L)&&L!==H)throw Error(`bad address checksum: ${N}`);return`0x${H}`}function $A(N){if(typeof N!=="string"||!GA.test(N))return!1;try{return UN(N),!0}catch{return!1}}var KP=[`${B.Maya}.MAYA`,`${B.Maya}.CACAO`,`${B.Ethereum}.THOR`,`${B.Ethereum}.vTHOR`,`${B.Kujira}.USK`,`${B.Ethereum}.FLIP`,`${B.Radix}.XRD`],_A=[B.Arbitrum,B.Aurora,B.Base,B.Ethereum,B.Optimism,B.Robinhood];async function qT(N){let{baseDecimal:A}=p(B.Radix);try{let T=await l(B.Radix),{manager:H}=await _.post(`${T}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:N}),headers:{Accept:"*/*","Content-Type":"application/json"}});return H?.divisibility?.value?.divisibility}catch(T){let H=T instanceof Error?T.message:String(T);return console.warn(`Failed to fetch Radix asset decimals for ${N}: ${H}`),A}}async function nT(N){try{let A=await l(B.Radix);return(await _.post(`${A}/state/entity/details`,{body:JSON.stringify({addresses:[N],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((L)=>L.key==="symbol")?.value.typed.value||void 0}catch(A){let T=A instanceof Error?A.message:String(A);return console.warn(`Failed to fetch Radix asset symbol for ${N}: ${T}`),""}}async function SA({chain:N,address:A,methodHex:T,id:H}){let L=await l(N);return _.post(L,{body:JSON.stringify({id:H,jsonrpc:"2.0",method:"eth_call",params:[{data:T,to:A.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}function vT(N){if(!N||N==="0x")return"UNKNOWN";try{return DA(N.replace(/^0x/,""))?.trim()||"UNKNOWN"}catch(A){return console.warn(`Failed to decode ABI string from ${N}: ${A}`),"UNKNOWN"}}function KT(N,A){if(!N||N==="0x")return A;try{return Number(N)}catch(T){return console.warn(`Failed to decode ABI uint8 from ${N}: ${T}`),A}}async function kT({chain:N,address:A}){let{baseDecimal:T}=p(N),H=A.toLowerCase();if(A===""||!H.startsWith("0x"))return T;let L=await SA({address:A,chain:N,id:2,methodHex:"0x313ce567"}).catch((R)=>{return console.warn(`Could not fetch decimals for ${A} on ${N}: ${R.message}`),{result:""}});return KT(L.result,T)}async function mT({chain:N,address:A}){let T=A.toLowerCase();if(T===""||!T.startsWith("0x"))return;let H=await SA({address:A,chain:N,id:1,methodHex:"0x95d89b41"}).catch((O)=>{return console.warn(`Could not fetch symbol for ${A} on ${N}: ${O.message}`),{result:""}});return vT(H.result)}async function YA({rpcUrl:N,contractAddress:A,functionSelector:T}){return(await _.post(`${N}/wallet/triggerconstantcontract`,{body:JSON.stringify({contract_address:A,function_selector:T,owner_address:A,parameter:"",visible:!0}),headers:{accept:"application/json","content-type":"application/json"}}).catch(()=>{return}))?.constant_result?.[0]}function MA(N){let A=N.match(/.{2}/g)?.map((T)=>Number.parseInt(T,16))??[];return new TextDecoder().decode(new Uint8Array(A))}function DA(N){return PN(N).with(void 0,()=>{return}).when((A)=>A.length>=128,(A)=>{let T=Number.parseInt(A.slice(64,128),16),H=A.slice(128,128+T*2).replace(/(00)+$/,"");return H?MA(H):void 0}).when((A)=>A.length===64,(A)=>{let T=A.replace(/(00)+$/,"");if(T.length>0&&T.length%2===0)return MA(T);return}).otherwise(()=>{return})}function UA({chain:N,address:A}){let{baseDecimal:T}=p(N),H={decimals:T,ticker:void 0};return PN(N).with(...VT,async()=>{try{if(!$A(A.replace(/^0X/,"0x")))return H;let[L,O]=await Promise.all([mT({address:A,chain:N}),kT({address:A,chain:N})]);return{decimals:O,ticker:L}}catch(L){return console.warn(`Failed to fetch token info for ${A} on ${N}: ${L?.code} ${L?.message}`),H}}).with(B.Solana,async()=>{if(!A)return H;try{let L=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${A}`);if(L.ok){let O=await L.json(),R=Array.isArray(O)?O[0]:O;if(R)return{decimals:R.decimals??T,ticker:R.symbol||void 0}}}catch(L){console.warn(`Failed to fetch Solana token info for ${A}: ${L?.code} ${L?.message}`)}return H}).with(B.Tron,async()=>{if(!A)return H;try{let L=await l(B.Tron),[O,R]=await Promise.all([YA({contractAddress:A,functionSelector:"symbol()",rpcUrl:L}),YA({contractAddress:A,functionSelector:"decimals()",rpcUrl:L})]),$=DA(O);return{decimals:O!==void 0&&R?Number(BigInt(`0x${R}`)):T,ticker:$}}catch(L){let O=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Tron token info for ${A}: ${O}`),H}}).with(B.Near,async()=>{if(!A)return H;try{let L=await l(B.Near),O=await _.post(L,{body:JSON.stringify({id:"dontcare",jsonrpc:"2.0",method:"query",params:{account_id:A,args_base64:"e30=",finality:"final",method_name:"ft_metadata",request_type:"call_function"}}),headers:{accept:"application/json","content-type":"application/json"}});if(!O.result?.result)throw Error("NEAR ft_metadata returned no result");let R=JSON.parse(new TextDecoder().decode(new Uint8Array(O.result.result)));return{decimals:R?.decimals||T,ticker:R?.symbol}}catch(L){let O=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Near token info for ${A}: ${O}`),H}}).with(B.Radix,async()=>{if(!A)return H;try{let[L,O]=await Promise.all([nT(A),qT(A)]);return{decimals:O,ticker:L}}catch(L){let O=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Radix token info for ${A}: ${O}`),H}}).otherwise(async()=>H)}function XA({chain:N,symbol:A}){return PN(N).with(..._A,()=>A==="ETH").with(B.Avalanche,()=>A==="AVAX").with(B.Berachain,()=>A==="BERA").with(B.Hyperevm,()=>A==="HYPE").with(B.Hype,()=>A==="HYPE").with(B.Spark,()=>A==="BTC").with(B.BinanceSmartChain,()=>A==="BNB").with(B.Gnosis,()=>A==="xDAI"||A==="XDAI").with(B.Monad,()=>A==="MON").with(B.XLayer,()=>A==="OKB").with(B.Maya,()=>A==="CACAO").with(B.Cosmos,()=>A==="ATOM").with(B.THORChain,()=>A==="RUNE").with(B.Tron,()=>A==="TRX").with(B.Ripple,()=>A==="XRP").with(B.Radix,()=>`${N}.${A}`===XN(N).identifier).otherwise(()=>A===N)}var XN=(N)=>{let{baseDecimal:A}=p(N);return PN(N.toUpperCase()).with(..._A,(H)=>({decimal:A,identifier:`${H}.ETH`})).with(B.THORChain,(H)=>({decimal:A,identifier:`${H}.RUNE`})).with(B.Cosmos,(H)=>({decimal:A,identifier:`${H}.ATOM`})).with(B.Maya,(H)=>({decimal:10,identifier:`${H}.CACAO`})).with(B.BinanceSmartChain,(H)=>({decimal:A,identifier:`${H}.BNB`})).with(B.Monad,(H)=>({decimal:A,identifier:`${H}.MON`})).with(B.Avalanche,(H)=>({decimal:A,identifier:`${H}.AVAX`})).with(B.Gnosis,(H)=>({decimal:A,identifier:`${H}.xDAI`})).with(B.XLayer,(H)=>({decimal:A,identifier:`${H}.OKB`})).with(B.Berachain,(H)=>({decimal:A,identifier:`${H}.BERA`})).with(B.Hyperevm,(H)=>({decimal:A,identifier:`${H}.HYPE`})).with(B.Hype,(H)=>({decimal:A,identifier:`${H}.HYPE`})).with(B.Spark,(H)=>({decimal:A,identifier:`${H}.BTC`})).with(B.Tron,(H)=>({decimal:A,identifier:`${H}.TRX`})).with(B.Solana,B.Chainflip,B.Kujira,B.Ripple,B.Polkadot,B.Near,...xT,(H)=>({decimal:A,identifier:`${H}.${H}`})).with(B.Radix,"XRD.XRD",()=>({decimal:A,identifier:"XRD.XRD"})).with(B.Polygon,"POL.POL",()=>({decimal:A,identifier:"POL.POL"})).with("KUJI.USK",(H)=>({decimal:6,identifier:H})).with("ETH.FLIP",()=>({decimal:p(B.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:p(B.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:p(B.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(H)=>({decimal:10,identifier:H})).with("MAYA.MAYA",(H)=>({decimal:4,identifier:H})).otherwise(()=>({decimal:A,identifier:N}))};function qN({chain:N,symbol:A}){if(A.includes("/"))return"Synth";if(A.includes("~"))return"Trade";return PN(N).with(B.Radix,()=>A===B.Radix||`${N}.${A}`===XN(N).identifier).with(B.Arbitrum,B.Optimism,B.Base,B.Aurora,B.Robinhood,()=>A===B.Ethereum).with(B.Cosmos,()=>A==="ATOM").with(B.BinanceSmartChain,()=>A==="BNB").with(B.Maya,()=>A==="CACAO").with(B.Monad,()=>A==="MON").with(B.THORChain,()=>A==="RUNE").with(B.Tron,()=>A==="TRX").with(B.Hyperevm,()=>A==="HYPE").with(B.Hype,()=>A==="HYPE").with(B.Spark,()=>A==="BTC").with(B.XLayer,()=>A==="OKB").otherwise(()=>A===N)?"Native":N}var y=(N)=>{let[A,...T]=N.split("."),H=N.includes("/"),L=T.join("."),O=L?.split("-"),R=O?.length?O.length===1?O[0]:O.slice(0,-1).join("-"):void 0;return{chain:A,symbol:L,synth:H,ticker:R}};function FN(N,A){let H=A===B.Near?N.indexOf("-"):N.lastIndexOf("-");if(H===-1)return{address:void 0,ticker:N};return{address:N.slice(H+1),ticker:N.slice(0,H)}}function kP(N){return`https://storage.googleapis.com/token-list-swapkit-dev/images/${N.toLowerCase()}.png`}async function mP(N){let{loadTokenLists:A}=await import("./tokens.js"),T=await A(void 0,{source:g.get("envs").isDev?"dev":"prod"}),H=Object.values(T).flatMap((O)=>O.tokens);if("identifier"in N)return H.find((O)=>O.identifier===N.identifier)?.identifier;let L=N.contract.toLowerCase();for(let O of H){let{chain:R,symbol:$}=y(O.identifier);if(R!==N.chain)continue;let{address:M}=FN($,R);if(M?.toLowerCase()===L)return O.identifier}return}import{match as uN}from"ts-pattern";var r=8,tT=10,fT=64;function C({value:N,bigIntDecimal:A=r,decimal:T=r}){if(T===0)return N.toString();let H=N<0n,L=N.toString().substring(H?1:0),O=T-(L.length-1);if(O>0)L="0".repeat(O)+L;let R=L.length-T,$=L.slice(-T);if(Number.parseInt($[A]||"0",10)>=5){let J=Number.parseInt($[A-1]||"0",10);$=`${$.substring(0,A-1)}${J+1}`}else $=$.substring(0,A);return`${H?"-":""}${L.slice(0,R)}.${$}`.replace(/\.?0*$/,"")}class t{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(N,A){return new t({decimal:A,value:C({bigIntDecimal:A,decimal:A,value:N})})}static shiftDecimals({value:N,from:A,to:T}){return t.fromBigInt(N.getBaseValue("bigint")*o(T)/o(A),T)}constructor(N){let A=nN(N),T=typeof N==="object";this.decimal=T?N.decimal:void 0,this.decimalMultiplier=T&&"decimalMultiplier"in N?N.decimalMultiplier:o(Math.max(uA(gN(A)),this.decimal||0)),this.#L(A)}set(N){return new this.constructor({decimal:this.decimal,identifier:this.toString?.({includeSynthProtocol:!0}),value:N})}add(...N){return this.#A("add",...N)}sub(...N){return this.#A("sub",...N)}mul(...N){return this.#A("mul",...N)}div(...N){return this.#A("div",...N)}gt(N){return this.#N("gt",N)}gte(N){return this.#N("gte",N)}lt(N){return this.#N("lt",N)}lte(N){return this.#N("lte",N)}eqValue(N){return this.#N("eqValue",N)}getValue(N,A){let T=ON(this.decimalMultiplier),H=A!==void 0?A:this.decimal,L=H!==void 0?H:T;if(H!==void 0&&H<T){if(this.formatBigIntToSafeValue(this.bigIntValue,H)==="0"&&this.bigIntValue!==0n)L=T}let O=this.formatBigIntToSafeValue(this.bigIntValue,L);return uN(N).with("number",()=>Number(O)).with("string",()=>O).with("bigint",()=>{return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}).otherwise(()=>O)}getBaseValue(N,A){let T=this.decimalMultiplier/o(A||this.decimal||r),H=yT(this.bigIntValue,T);return uN(N).with("number",()=>Number(H)).with("string",()=>H.toString()).otherwise(()=>H)}getBigIntValue(N,A){if(!A&&typeof N==="object")return N.bigIntValue;let T=nN(N),H=gN(T);if(H==="0"||H==="undefined")return 0n;return this.#H(H,A)}toSignificant(N=6){let A=this.getValue("string"),[T="",H=""]=A.split("."),L=Number.parseInt(T,10)>0;if((L?T.length+H.length:H.length)<=N)return A;if(T.length>=N)return T.slice(0,N).padEnd(T.length,"0");if(L)return`${T}.${H.slice(0,N-T.length)}`;let R=H.replace(/^0+/,"")||"0",$=R.slice(0,N),M=H.length-R.length;return`0.${$.padStart(M+$.length,"0")}`}toFixed(N=6){let A=this.getValue("string"),T=A.startsWith("-"),[H="0",L=""]=(T?A.slice(1):A).split("."),O=H==="0"&&Number.parseInt(L.slice(0,N),10)===0,R=T&&!O?"-":"";if(N===0){if(H==="0"&&!L)return"0";return L&&Number.parseInt(L[0]||"0",10)>=5?`${R}${BigInt(H)+1n}.0`:`${R}${H}.0`}if(!L)return`${R}${H}.${"0".repeat(N)}`;let $=L[N];if(!($&&Number.parseInt($,10)>=5))return`${R}${H}.${L.slice(0,N).padEnd(N,"0")}`;let J=BigInt(L.slice(0,N).padEnd(N,"0"))+1n,X=10n**BigInt(N);if(J>=X)return`${R}${BigInt(H)+1n}.${"0".repeat(N)}`;return`${R}${H}.${J.toString().padStart(N,"0")}`}toAbbreviation(N=2){let A=this.getValue("string"),T=Number(A),H=["","K","M","B","T","Q","Qi","S"],L=Math.floor(Math.log10(Math.abs(T))/3);if(L===0||!H[L])return A;return`${(T/10**(L*3)).toFixed(N)}${H[L]}`}toCurrency(N="$",{currencyPosition:A="start",decimal:T=2,decimalSeparator:H=".",thousandSeparator:L=",",trimTrailingZeros:O=!0}={}){let R=this.toFixed(T),$=A==="end",[M="0",J=""]=R.split("."),X=M.replace(/\B(?=(\d{3})+(?!\d))/g,L),u=J&&Number.parseInt(J,10)>0,w=u?`${X}${H}${J}`:X,K=w.length<100&&O&&u?w.replace(/\.?0*$/,""):w;return $?`${K}${N}`:`${N}${K}`}formatBigIntToSafeValue(N,A){let T=A||this.decimal||r,H=Math.max(T,ON(this.decimalMultiplier));return C({bigIntDecimal:T,decimal:H,value:N})}#A(N,...A){let T=this.#T(this,...A),H=ON(this.decimalMultiplier),L=Math.max(T,H),O=Math.min(L+tT,fT),R=o(O),$=A.reduce((X,u)=>{let w=this.getBigIntValue(u,O);return uN(N).with("add",()=>X+w).with("sub",()=>X-w).with("mul",()=>X*w/R).with("div",()=>{if(w===0n)throw RangeError("Division by zero");return X*R/w}).otherwise(()=>X)},this.bigIntValue*R/this.decimalMultiplier),M=C({bigIntDecimal:O,decimal:O,value:$}),J=this.decimal===void 0?void 0:Math.min(this.decimal,O);return new this.constructor({decimal:J,decimalMultiplier:o(O),identifier:this.toString(),value:M})}#N(N,...A){let T=this.#T(this,...A),H=this.getBigIntValue(A[0]||"0",T),L=this.getBigIntValue(this,T);return uN(N).with("gt",()=>L>H).with("gte",()=>L>=H).with("lt",()=>L<H).with("lte",()=>L<=H).with("eqValue",()=>L===H).otherwise(()=>!1)}#L(N){let A=gN(N)||"0";this.bigIntValue=this.#H(A)}#T(...N){let A=N.map((T)=>{return typeof T==="object"?T.decimal||ON(T.decimalMultiplier):uA(gN(T))}).filter(Boolean);return Math.max(...A,r)}#H(N,A){let T=A?o(A):this.decimalMultiplier,H=ON(T),[L="",O=""]=N.split(".");return BigInt(`${L}${O.padEnd(H,"0")}`)}}var pT=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function gN(N){let T=`${typeof N==="number"?pT.format(N):nN(N)}`.replaceAll(",",".").split(".");return T.length>1?`${T.slice(0,-1).join("")}.${T.at(-1)}`:T[0]||"0"}function uA(N){let A=N.split(".")[1]?.length||0;return Math.max(A,r)}function nN(N){return typeof N==="object"?"getValue"in N?N.getValue("string"):N.value:N}function yT(N,A){if(A===0n)throw Error("Cannot divide by zero");let T=A/2n;return N>=0n&&A>=0n||N<0n&&A<0n?(N+T)/A:(N-T)/A}function o(N){return 10n**BigInt(N)}function ON(N){return N.toString().length-1}function dT(N=""){let A=N.toUpperCase(),T=g.get("chains"),[H]=A.split(".");if(T.includes(H))return!0;let[L]=A.split("/");if(T.includes(L))return!0;throw new U({errorKey:"helpers_invalid_identifier",info:{identifier:N,message:`Invalid identifier: ${N}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}var f=[b.Hype,b.Near,b.Ripple,b.Solana,b.Stellar,b.Sui,b.Ton,b.Tron],kN=[b.THORChain,b.Maya],i=new Map,WN=new Map,s=new Map,hT=3600000;function cT(N){let A=s.get(N);if(A?.timestamp&&Date.now()-A.timestamp>hT){s.delete(N);return}return A}function lT(N,A){if(s.size>1000){let T=s.keys().next().value;if(T)s.delete(T)}s.set(N,{...A,timestamp:Date.now()})}class n extends t{address;chain;isGasAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:N,decimal:A,tax:T,chain:H,symbol:L,identifier:O}){super(typeof N==="object"?N:{decimal:A,value:N});let R=gA(O||`${H}.${L}`);this.type=qN(R),this.tax=T,this.chain=R.chain,this.ticker=R.ticker,this.symbol=R.symbol,this.address=R.address,this.isSynthetic=R.isSynthetic,this.isTradeAsset=R.isTradeAsset,this.isGasAsset=R.isGasAsset,this.chainId=IN(R.chain).chainId}toString({includeSynthProtocol:N}={}){return(this.isSynthetic||this.isTradeAsset)&&!N?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){if(this.isSynthetic)return`${this.chain}.${this.symbol.replace(/\//g,".")}`;if(this.isTradeAsset)return`${this.chain}.${this.symbol.replace(/~/g,"..")}`;let N=this.symbol.replace(/\./g,"__");return`${this.chain}.${N}`}getIconUrl(){return i.get(this.toString())?.logoURI}eqAsset({chain:N,symbol:A}){return this.chain===N&&this.symbol===A}eq(N){return this.eqAsset(N)&&this.eqValue(N)}static fromUrl(N,A=0){let T=N.indexOf(".");if(T===-1)throw new U({errorKey:"helpers_invalid_asset_url",info:{urlAsset:N}});let H=N.slice(0,T),L=N.slice(T+1),O=KN({chain:H,rest:L}).when(({rest:R})=>R.includes(".."),({chain:R,rest:$})=>`${R}.${$.replace(/\.\./g,"~")}`).when(({chain:R,rest:$})=>kN.includes(R)&&$.includes("."),({chain:R,rest:$})=>`${R}.${$.replace(/\./g,"/")}`).otherwise(({chain:R,rest:$})=>`${R}.${$.replace(/__/g,".")}`);return n.from({asset:O,value:A})}static from({value:N=0,fromBaseDecimal:A,asyncTokenLookup:T,...H}){let L=N instanceof t?N.getValue("string"):N,O="address"in H&&"chain"in H,R=aT(H);if(R===null&&T&&O){let{chain:HN,address:h}=H;return iT({address:h,chain:HN,fromBaseDecimal:A,parsedValue:L})}let $=O&&!R?`${H.chain}.UNKNOWN-${H.address}`:R,{identifier:M,decimal:J}=XN($),{chain:X,isSynthetic:u,isTradeAsset:w,address:E}=gA(M),{baseDecimal:K}=IN(X),Q=i.get(f.includes(X)?M:M.toUpperCase());if(!Q&&T&&!u&&!w)return(async()=>{let{ticker:HN}=y(M),h=await WA({address:E,chain:X,ticker:HN});return vN({decimal:h.decimals,identifier:h.identifier,value:A?a(BigInt(L),A):L})})();let Z=Q?.decimal||J;c({condition:!Z&&!T,id:`assetValue_static_decimal_not_found_${X}`,warning:`Couldn't find static decimal for one or more tokens on ${X} (Using default ${K} decimal as fallback).
|
|
2
|
+
This can result in incorrect calculations and mess with amount sent on transactions.
|
|
3
|
+
You can load static assets by installing @swapkit/tokens package and calling AssetValue.loadStaticAssets()
|
|
4
|
+
or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`});let{decimal:TN,identifier:d,tax:z}=Q||{decimal:Z||K,identifier:M},$N=A?a(BigInt(L),A):a(L,TN);return u||w?rT(d,$N):vN({decimal:TN,identifier:d,tax:z,value:$N})}static async loadStaticAssets(N){let{loadTokenLists:A}=await import("@swapkit/tokens"),T=await A(N,{source:g.get("envs").isDev?"dev":"prod"});for(let{tokens:H}of Object.values(T))for(let L of H){let{identifier:O}=L,{chain:R,symbol:$}=y(O),{address:M}=FN($,R),{baseDecimal:J}=IN(R),X=f.includes(R)?O:O.toUpperCase(),u="decimals"in L&&L.decimals!==void 0?L.decimals:J,w="logoURI"in L&&L.logoURI?L.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${O.toLowerCase()}.png`,E={decimal:u,identifier:O,logoURI:w,tax:"tax"in L?L.tax:void 0};if(i.set(X,E),M){let K=f.includes(R)?`${R}:${M}`:`${R}:${M.toUpperCase()}`;WN.set(K,O)}}return!0}static setStaticAssets(N){i.clear(),WN.clear();for(let[A,T]of N.entries()){let{identifier:H}=T,{chain:L,symbol:O}=y(H),{address:R}=FN(O,L),{baseDecimal:$}=IN(L),M=T.chain??L,J=T.address??R,X=f.includes(M)?H:H.toUpperCase(),u=T.decimals??T.decimal??$,w=T.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${H.toLowerCase()}.png`,E={decimal:u,identifier:X,logoURI:w,tax:T.tax};if(i.set(X,E),J){let K=f.includes(M)?`${M}:${J}`:`${M}:${J.toUpperCase()}`;WN.set(K,H)}}return!0}static get staticAssets(){return i}}function iP(N){let A=n.from({chain:N});return KN(N).with(b.Bitcoin,b.Litecoin,b.BitcoinCash,b.Dash,()=>A.set(0.00010001)).with(b.Dogecoin,()=>A.set(1.00000001)).with(b.Avalanche,b.Ethereum,b.Arbitrum,b.BinanceSmartChain,()=>A.set(0.00000001)).with(b.THORChain,b.Maya,()=>A.set(0)).with(b.Cosmos,b.Kujira,()=>A.set(0.000001)).otherwise(()=>A.set(0.00000001))}async function WA({chain:N,address:A,ticker:T}){let L=f.includes(N)?`${N}:${A||T}`:`${N}:${A||T}`.toUpperCase(),O=cT(L);if(O)return O;if(!A){let{baseDecimal:M}=IN(N);return{decimals:M,identifier:`${N}.${T||"UNKNOWN"}`}}let R=await UA({address:A,chain:N}),$=`${N}.${R.ticker||T||"UNKNOWN"}-${A}`;return c({condition:!!(!R.ticker&&T),id:`async_token_lookup_failed_${N}_${A}`,warning:`Could not fetch token metadata for ${N}:${A} from chain. Using user-provided ticker (${T}) with baseDecimal (${R.decimals}).`}),R.ticker&&lT(L,{decimals:R.decimals,identifier:$}),{decimals:R.decimals,identifier:$}}function vN({identifier:N,decimal:A,value:T,tax:H}){return dT(N),new n({decimal:A,identifier:N,tax:H,value:a(T,A)})}function rT(N,A=0){let T=N.includes(".")?N.split(".")?.[0]?.toUpperCase():void 0,H=T?kN.includes(T):!1,L=N.slice(0,14).includes("~")?"~":"/",[O,R]=H?N.split(".").slice(1).join().split(L):N.split(L);if(!(O&&R))throw new U({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});return new n({decimal:8,identifier:`${T||b.THORChain}.${O}${L}${R}`,value:a(A,8)})}async function iT({address:N,chain:A,fromBaseDecimal:T,parsedValue:H}){let{decimals:L,identifier:O}=await WA({address:N,chain:A}),R=T?a(BigInt(H),T):H;return vN({decimal:L,identifier:O,value:R})}function a(N,A){return typeof N==="bigint"?C({bigIntDecimal:A,decimal:A,value:N}):N}function sT(N){let A=KN(N).when((T)=>("chain"in T)&&T.chain!==void 0,({chain:T})=>T).otherwise((T)=>{let H=y(T.asset);return H.synth?b.THORChain:H.chain});if(!oT.includes(A.toUpperCase())){let T="asset"in N?N.asset:A;throw new U({errorKey:"helpers_invalid_asset_identifier",info:{identifier:T,message:`Unsupported chain "${A}" - use the AssetValue constructor directly`}})}}function aT(N){if(sT(N),"chain"in N){let{chain:L,address:O}=N;if(O){let R=f.includes(L)?`${L}:${O}`:`${L}:${O.toUpperCase()}`,$=WN.get(R);if($)return $;return null}return L}let{chain:A,symbol:T}=y(N.asset);return qN({chain:A,symbol:T})==="Native"?A:N.asset}function eT(N,A,T){let H=N.split("."),L=H[0]?.toUpperCase(),O=kN.includes(L),R=T?"~":"/",[$,M=""]=O?H.slice(1).join(".").split(R):N.split(R);if(!($&&M))throw new U({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});let{ticker:J,address:X}=EA({chain:$,symbol:M}),u=`${$}${R}${M}`;return{address:X,chain:L,isGasAsset:!1,isSynthetic:A,isTradeAsset:T,symbol:u,ticker:J}}function NH(N){let A=N.indexOf("."),T=(A===-1?N:N.slice(0,A)).toUpperCase(),H=A===-1?N:N.slice(A+1),{address:L,ticker:O}=EA({chain:T,symbol:H}),R;try{R=L&&CT.includes(T)&&UN(L)?UN(L):L}catch{R=L}let $=R?`${O}-${R}`:H;return{address:R,chain:T,isGasAsset:XA({chain:T,symbol:H}),isSynthetic:!1,isTradeAsset:!1,symbol:$,ticker:O}}function gA(N){let A=N.slice(0,14),T=A.includes("/"),H=A.includes("~");if(T||H)return eT(N,T,H);return NH(N)}function EA({symbol:N,chain:A}){let{ticker:T,address:H}=FN(N,A);return{address:H&&!f.includes(A)?H.toLowerCase():H,ticker:T}}class EN extends t{eq(N){return this.eqValue(N)}static fromBigInt(N,A){return new EN({decimal:A,value:C({bigIntDecimal:A,decimal:A,value:N})})}}function bA(N=!0){return N?"https://gateway.liquify.com/chain/thorchain_midgard":"https://midgard.mayachain.info"}function TH(N=!0){let A=bA(N);return N?`${A}/v2/thorname`:`${A}/v2/mayaname`}function HH(N){return function(T){let H=T?`?status=${T}`:"";return _.get(`${N}/v2/pools${H}`)}}function LH(N){return function(T){return _.get(`${N}/v2/pool/${T}`)}}function PH(N){return function(T,H){let L=H?`?period=${H}`:"";return _.get(`${N}/v2/pool/${T}/stats${L}`)}}function FH(N){return function(T,H){let L=new URLSearchParams;if(H?.interval)L.append("interval",H.interval);if(H?.count)L.append("count",H.count.toString());if(H?.from)L.append("from",H.from.toString());if(H?.to)L.append("to",H.to.toString());let O=L.toString()?`?${L.toString()}`:"";return _.get(`${N}/v2/history/depths/${T}${O}`)}}function OH(N){return function(){return _.get(`${N}/v2/network`)}}function IH(N){return function(){return _.get(`${N}/v2/health`)}}function RH(N){return function(){return _.get(`${N}/v2/nodes`)}}function BH(N){return function(T){return _.get(`${N}/v2/node/${T}`)}}function GH(N){return function(){return _.get(`${N}/v2/mimir/votes`)}}function $H(N){return function(){return _.get(`${N}/v2/mimir`)}}function YH(N){return function(){return _.get(`${N}/v2/constants`)}}function MH(N){return function(){return _.get(`${N}/v2/stats`)}}function _H(N){return function(T){let H=new URLSearchParams;if(T?.interval)H.append("interval",T.interval);if(T?.count)H.append("count",T.count.toString());if(T?.from)H.append("from",T.from.toString());if(T?.to)H.append("to",T.to.toString());let L=H.toString()?`?${H.toString()}`:"";return _.get(`${N}/v2/history/earnings${L}`)}}function SH(N){return function(T,H){let L=new URLSearchParams;if(H?.interval)L.append("interval",H.interval);if(H?.count)L.append("count",H.count.toString());if(H?.from)L.append("from",H.from.toString());if(H?.to)L.append("to",H.to.toString());let O=L.toString()?`?${L.toString()}`:"",R=T?`/swaps/${T}`:"/swaps";return _.get(`${N}/v2/history${R}${O}`)}}function DH(N){return function(T){let H=new URLSearchParams;if(T?.interval)H.append("interval",T.interval);if(T?.count)H.append("count",T.count.toString());if(T?.from)H.append("from",T.from.toString());if(T?.to)H.append("to",T.to.toString());let L=H.toString()?`?${H.toString()}`:"";return _.get(`${N}/v2/history/tvl${L}`)}}function UH(N){if(!N)return"";let A=new URLSearchParams,T=(H,L)=>{if(L!==void 0)A.append(H,typeof L==="number"?L.toString():L)};return T("address",N.address),T("txid",N.txid),T("asset",N.asset),T("type",N.type),T("affiliate",N.affiliate),T("limit",N.limit),T("offset",N.offset),A.toString()?`?${A.toString()}`:""}function XH(N){return function(T){let H=UH(T);return _.get(`${N}/v2/actions${H}`)}}function uH(N){return function(T){return _.get(`${N}/v2/member/${T}`)}}function gH(N){return function(T){let H=T?`/${T}`:"";return _.get(`${N}/v2/members${H}`)}}function WH(N){return function(T,H){let L=H?`&asset=${H}`:"";return _.get(`${N}/v2/saver/${T}${L?`?${L.substring(1)}`:""}`)}}function EH(N){return function(T){return _.get(`${N}/v2/savers/${T}`)}}function bH(N){return function(T,H){let L=new URLSearchParams;if(H?.interval)L.append("interval",H.interval);if(H?.count)L.append("count",H.count.toString());if(H?.from)L.append("from",H.from.toString());if(H?.to)L.append("to",H.to.toString());let O=L.toString()?`?${L.toString()}`:"",R=T?`/savers/${T}`:"/savers";return _.get(`${N}/v2/history${R}${O}`)}}function zH(N){return function(T){return _.get(`${N}/v2/balance/${T}`)}}function JH(N){return async function(T){let H=(L)=>{if(L?.cause?.status===404)return;throw L};return await _.get(`${N}/lookup/${T}`,{onError:H,retry:{maxRetries:1}})}}function QH(N){return async function(T){let H=(L)=>{if(L?.cause?.status===404)return[];throw L};return await _.get(`${N}/rlookup/${T}`,{onError:H,retry:{maxRetries:1}})}}function ZH(N){return async function(T){let H=(L)=>{if(L?.cause?.status===404)return[];throw L};return await _.get(`${N}/owner/${T}`,{onError:H,retry:{maxRetries:1}})}}function e({asset:N,value:A}){return n.from({asset:N,fromBaseDecimal:AH(bN.THORChain).baseDecimal,value:A})}function wH({liquidityPositionGetter:N,isThorchain:A}){return async function(H){let L=await N(H),O=A?"rune":"cacao";return L.pools.map((R)=>({[`${O}Pending`]:e({asset:"THOR.RUNE",value:R.runePending}),[`${O}RegisteredAddress`]:R.runeAddress,[`${O}Withdrawn`]:e({asset:"THOR.RUNE",value:R.runeWithdrawn}),[O]:e({asset:"THOR.RUNE",value:R.runeAdded}),asset:e({asset:R.pool,value:R.assetAdded}),assetPending:e({asset:R.pool,value:R.assetPending}),assetRegisteredAddress:R.assetAddress,assetWithdrawn:e({asset:R.pool,value:R.assetWithdrawn}),dateFirstAdded:R.dateFirstAdded,dateLastAdded:R.dateLastAdded,poolShare:new EN(R.liquidityUnits).div(R.pool)}))}}function zA(N){let A=N===bN.THORChain,T=bA(A),H=TH(A),L=uH(T);return{getActions:XH(T),getBalance:zH(T),getConstants:YH(T),getEarningsHistory:_H(T),getHealth:IH(T),getLiquidityPosition:wH({isThorchain:A,liquidityPositionGetter:L}),getLiquidityPositionRaw:L,getMembers:gH(T),getMimir:$H(T),getMimirVotes:GH(T),getNameDetails:JH(H),getNamesByAddress:QH(H),getNamesByOwner:ZH(H),getNetworkInfo:OH(T),getNode:BH(T),getNodes:RH(T),getPool:LH(T),getPoolDepthHistory:FH(T),getPoolStats:PH(T),getPools:HH(T),getSaverDetails:WH(T),getSavers:EH(T),getSaversHistory:bH(T),getStats:MH(T),getSwapHistory:SH(T),getTVLHistory:DH(T)}}var JA=zA(bN.THORChain),QA=zA(bN.Maya);var oN={};lN(oN,{searchTokens:()=>uL,getTrackerDetails:()=>YL,getTokenListProviders:()=>UL,getTokenList:()=>XL,getTokenApproval:()=>DL,getSwapTo:()=>wL,getSwapQuote:()=>ML,getRouteWithTx:()=>_L,getPrice:()=>gL,getNearDepositChannel:()=>bL,getGasRate:()=>WL,getChainflipDepositChannel:()=>EL,getChainBalance:()=>SL,SKRequestClient:()=>q});import{EVMChains as yN}from"@swapkit/types";import{match as $L,P as GN}from"ts-pattern";import{Chain as zN,ChainId as RN}from"@swapkit/types";import{array as W,boolean as k,coerce as VA,number as S,object as Y,optional as G,string as F,union as mN,unknown as tN,z as P}from"zod";var xA;((H)=>{H.CHEAPEST="CHEAPEST";H.FASTEST="FASTEST";H.RECOMMENDED="RECOMMENDED"})(xA||={});var JN;((X)=>{X.PSBT="PSBT";X.EVM="EVM";X.COSMOS="COSMOS";X.RADIX="RADIX";X.NEAR="NEAR";X.STELLAR="STELLAR";X.TON="TON";X.TRON="TRON";X.EIP_712_HYPE_SEND_ASSET="EIP_712_HYPE_SEND_ASSET";X.EIP_712_HYPE_WITHDRAW="EIP_712_HYPE_WITHDRAW"})(JN||={});var qA;((Z)=>{Z.approve="approve";Z.claim="claim";Z.deposit="deposit";Z.donate="donate";Z.lending="lending";Z.lp_action="lp_action";Z.native_contract_call="native_contract_call";Z.native_send="native_send";Z.stake="stake";Z.streaming_swap="streaming_swap";Z.swap="swap";Z.thorname_action="thorname_action";Z.token_contract_call="token_contract_call";Z.token_transfer="token_transfer";Z.unknown="unknown";Z.unstake="unstake"})(qA||={});var nA;((E)=>{E.swap="swap";E.aggregation="aggregation";E.addLiquidity="addLiquidity";E.withdrawLiquidity="withdrawLiquidity";E.addSavers="addSavers";E.withdrawSavers="withdrawSavers";E.borrow="borrow";E.repay="repay";E.name="name";E.donate="donate";E.claim="claim";E.stake="stake";E.unstake="unstake"})(nA||={});var vA;(($)=>{$.unknown="unknown";$.not_started="not_started";$.pending="pending";$.swapping="swapping";$.completed="completed";$.refunded="refunded";$.failed="failed"})(vA||={});var KA;((Q)=>{Q.not_started="not_started";Q.starting="starting";Q.broadcasted="broadcasted";Q.mempool="mempool";Q.inbound="inbound";Q.outbound="outbound";Q.swapping="swapping";Q.completed="completed";Q.refunded="refunded";Q.partially_refunded="partially_refunded";Q.dropped="dropped";Q.reverted="reverted";Q.replaced="replaced";Q.retries_exceeded="retries_exceeded";Q.parsing_error="parsing_error"})(KA||={});var IF=Y({address:G(F()),chain:P.enum(zN).optional(),chainId:P.enum(RN),coingeckoId:G(F()),decimals:VA.number(),extensions:G(P.looseObject({})),identifier:F(),logoURI:G(F()),name:G(F()),shortCode:G(F()),symbol:G(F()),ticker:F()}),RF=P.object({block:P.optional(P.number().describe("Block number. Required for Polkadot chain. e.g. `123456`")),chainId:P.optional(P.string().describe("ChainId for the hash. e.g. `thorchain-1`")),depositChannelId:P.optional(P.string().describe("Deposit channel ID, required for Chainflip if tx was broadcasted without wallet connection")),hash:P.optional(P.string().describe("Hash for the first transaction broadcasted by the end user. e.g. `88D1819378ECD09E5284C54937CDC1E99B52F253C007617A02DD1200710CE677`"))}).refine((N)=>N.hash&&N.chainId||N.depositChannelId,{message:"Either `hash` and `chainId` or `depositChannelId` must be provided"}),BF=P.object({forceUpdate:P.string().toLowerCase().transform((N)=>N==="true").pipe(P.boolean()).optional()}),GF=Y({error:F(),message:F()}),NN=Y({address:G(F()),chain:P.enum(zN),decimal:G(S()),isGasAsset:k(),isSynthetic:k(),symbol:F(),tax:G(Y({buy:S(),sell:S()})),ticker:F()}),kA=Y({id:F(),market_cap:S(),name:F(),price_change_24h_usd:S(),price_change_percentage_24h_usd:S(),sparkline_in_7d:W(S()),timestamp:F(),total_volume:S()}).partial(),$F=Y({cg:G(kA),identifier:F(),price_usd:S(),provider:F(),timestamp:S()}),mA=W(Y({cg:G(kA),identifier:F(),price_usd:S(),provider:F(),timestamp:S()}).partial()),YF=Y({affiliate:G(F().describe("Affiliate thorname")),affiliateFee:G(S().describe("Affiliate fee in basis points").refine((N)=>N===Math.floor(N)&&N>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:G(k().describe("Allow smart contract as recipient")),allowSmartContractSender:G(k().describe("Allow smart contract as sender")),buyAsset:F().describe("Asset to buy"),cfBoost:G(k().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:G(F().describe("Address to send asset to")),disableSecurityChecks:G(k().describe("Disable security checks")),includeTx:G(k().describe("Set to true to include an transaction object (EVM only)")),providers:G(W(F().describe("List of providers to use").refine((N)=>j[N]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:G(F().describe("Referrer address (referral program)")),sellAmount:F().describe("Amount of asset to sell").refine((N)=>+N>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:F().describe("Asset to sell"),slippage:G(S().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:G(F().describe("Address to send asset from"))}).refine((N)=>N.sellAsset!==N.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),MF=Y({metadata:k(),tokens:W(Y({identifier:F()}))}),tA=Y({destinationAddress:F()}),jH=tA.extend({affiliateFees:W(Y({brokerAddress:F(),feeBps:S()})).optional(),brokerCommissionBps:S().optional(),buyAsset:Y({asset:F(),chain:F()}),channelMetadata:Y({cfParameters:F().optional(),gasBudget:F().optional(),message:F().optional()}).optional(),dcaParameters:Y({chunkInterval:S().optional(),numberOfChunks:S().optional()}).optional(),maxBoostFeeBps:S().optional(),refundParameters:Y({minPrice:F().optional(),refundAddress:F().optional(),retryDuration:S().optional()}).optional(),sellAsset:Y({asset:F(),chain:F()})}),fA=Y({channelId:F(),depositAddress:F()}),ZA=tA.extend({affiliateFees:Y({feeBps:S(),nearId:F()}).optional(),buyAsset:F(),sellAmount:F(),sellAsset:F(),slippage:VA.number(),sourceAddress:F()}),wA=Y({amountIn:F(),amountInFormatted:F(),amountInUsd:F(),amountOut:F(),amountOutFormatted:F(),amountOutUsd:F(),deadline:F().optional(),minAmountIn:F(),minAmountOut:F(),timeEstimate:S().optional(),timeWhenInactive:F().optional()}),_F=wA.extend({depositAddress:F(),quote:wA,signature:F(),timestamp:F(),tx:tN()}),pA=Y({buyAsset:F(),buyAssetAmount:F(),buyAssetAmountMaxSlippage:F(),deadline:F().optional(),depositAddress:F(),depositAmount:F(),depositAsset:F(),tx:tN()}),VH=Y({evmCalldata:P.optional(P.string()),intentHash:P.optional(P.string()),logs:P.optional(P.unknown()),manifest:P.optional(P.unknown()),memo:P.optional(P.string()),spender:P.optional(P.string()),thorname:P.optional(P.string())}),xH=Y({currentStage:F(),inboundConfirmation:S(),inboundObservation:S(),outboundDelay:S(),outboundObservation:S(),streamingSwap:S()}),qH=Y({count:G(S()),interval:G(S()),quantity:G(S()),subSwapsMap:G(W(S()))}),nH=P.object({currentLegIndex:P.optional(P.number()),estimatedTimeToComplete:P.number(),estimates:P.optional(xH),providerDetails:P.optional(P.object({streamingDetails:P.optional(qH)}))}),vH=Y({affiliate:G(NN),liquidity:G(NN),network:G(NN),protocol:G(NN),tax:G(NN)}),KH=Y({affiliate:F(),bps:F(),isReferrer:k()}),kH=Y({affiliate:G(F()),affiliateFees:G(W(KH)),broadcastedAt:G(S()),explorerUrl:G(F()),fees:G(vH),images:G(Y({chain:G(F()),from:G(F()),provider:G(F()),to:G(F())})),provider:G(P.enum(j)),providerAction:P.optional(P.enum(nA)),quoteId:G(F()),wallet:G(F())}),AN=P.object({block:P.number(),chainId:P.enum(RN),finalAddress:P.optional(P.string()),finalAsset:P.optional(NN),finalisedAt:P.number(),fromAddress:P.string(),fromAmount:P.string(),fromAsset:P.string(),hash:P.string(),meta:P.optional(kH),payload:P.optional(VH),status:P.enum(vA),toAddress:P.string(),toAmount:P.string(),toAsset:P.string(),trackingStatus:P.optional(P.enum(KA)),transient:P.optional(nH),type:P.enum(qA)}),yA=AN.extend({legs:P.array(AN)}),SF=AN.extend({legs:W(AN)}),DF=AN.extend({legs:W(AN)}),fN=W(Y({amount:F(),asset:F(),chain:F(),protocol:P.enum(j),type:P.enum(wN)})),pN=P.object({inbound:P.optional(P.number().describe("Time to receive inbound asset in seconds")),outbound:P.optional(P.number().describe("Time to receive outbound asset in seconds")),swap:P.optional(P.number().describe("Time to swap assets in seconds")),total:P.number().describe("Total time in seconds")}),mH=/^(?:0x[0-9a-fA-F]+|[0-9]+)$/;function tH(N){return N===""||mH.test(N)}function UF(N){return N?BigInt(N):0n}function XF(N){let A=typeof N==="bigint"?N:BigInt(N);return A>0n?`0x${A.toString(16)}`:"0x0"}var BN=F().refine(tH,{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"),fH=Y({data:F().describe("Data to send"),from:F().describe("Address of the sender"),to:F().describe("Address of the recipient"),value:BN}),pH=P.object({data:P.string().optional(),raw_data:P.object({contract:P.any(),data:P.string().optional(),expiration:P.number(),fee_limit:P.number().optional(),ref_block_bytes:P.string(),ref_block_hash:P.string(),timestamp:P.number()}).passthrough(),raw_data_hex:P.string(),txID:P.string(),value:BN.optional(),visible:P.boolean()}),yH=W(mN([F(),S(),W(F()),Y({from:F(),value:BN}).describe("Parameters to pass to the contract method")])),uF=Y({approvalSpender:G(F().describe("Address of the spender to approve")),approvalToken:G(F().describe("Address of the token to approve spending of")),contractAddress:F().describe("Address of the contract to interact with"),contractMethod:F().describe("Name of the method to call"),contractParamNames:W(F().describe("Names of the parameters to pass to the contract method")),contractParams:yH}),oH=Y({typeUrl:F("/types.MsgDeposit"),value:Y({coins:W(Y({amount:F(),asset:Y({chain:F(),symbol:F(),synth:k(),ticker:F()})})),memo:F(),signer:F()})}),CH=Y({typeUrl:F("/types.MsgSend"),value:Y({amount:W(Y({amount:F(),denom:F()})),fromAddress:F(),toAddress:F()})}),dH=Y({typeUrl:F(),value:CH.shape.value.or(oH.shape.value)}),hH=Y({amount:W(Y({amount:F(),denom:F()})),gas:F()}),cH=Y({accountNumber:S(),chainId:P.enum(RN),fee:hH,memo:F(),msgs:W(dH),sequence:S()}),lH=P.array(P.object({calldata:P.array(P.string()),contractAddress:P.string(),entrypoint:P.string()})),rH=P.object({address:P.string().describe("Destination address in friendly format"),amount:P.string().describe("Amount in nanotons"),payload:P.string().optional().describe("Base64 BOC of body cell"),stateInit:P.string().optional().describe("Base64 BOC of state init")}),iH=P.object({messages:P.array(rH),sendMode:P.number().describe("TON wallet send mode for the whole transfer")}),gF="USDC:0x6d1e7cde53ba9467b783cb7c530ce054",sH=P.looseObject({domain:P.looseObject({chainId:G(mN([S(),F()])),name:G(F()),verifyingContract:G(F()),version:G(F())}),message:P.record(F(),tN()),primaryType:F(),types:P.record(F(),W(P.looseObject({name:F(),type:F()})))}),aH=P.looseObject({amount:F(),destination:F(),destinationDex:F(),fromSubAccount:F(),hyperliquidChain:F(),nonce:S().int(),signatureChainId:F(),sourceDex:F(),token:F(),type:P.literal("sendAsset")}),oA=P.looseObject({action:P.looseObject({type:F()}),submitTo:F(),typedData:sH}),WF=oA.extend({action:aH}),CA=mN([fH,cH,pH,iH,oA,F()]),eH=CA.or(lH),NL=Y({affiliate:F().describe("Affiliate address").optional(),affiliateFee:S().describe("Affiliate fee").optional(),buyAsset:F().describe("Asset to buy"),destinationAddress:F().describe("Destination address"),estimatedTime:pN.optional(),provider:P.enum(j),sellAsset:F().describe("Asset to sell"),slipPercentage:S().describe("Slippage as a percentage"),sourceAddress:F().describe("Source address")}),EF=NL.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),AL=Y({asset:F().describe("Asset name"),image:F().describe("Asset image"),price:S().describe("Price in USD")}),TL=jH,dA=Y({assets:G(W(AL)),maxStreamingQuantity:S().optional(),referrer:F().optional(),streamingInterval:S().optional(),tags:W(P.enum(xA))}),hA=dA.extend({affiliate:G(F()),affiliateFee:G(F()),approvalAddress:G(F().describe("Approval address for swap")),chainflip:TL.optional(),garden:ZA.optional(),near:ZA.optional(),priceImpact:G(S().describe("Price impact")),referrer:G(F()),txType:G(P.enum(JN))}),cA=W(Y({code:P.enum(ZN),display:F(),tooltip:F().optional()})),HL=Y({buyAmount:F().describe("Buy amount"),buyAmountMaxSlippage:F().describe("Buy amount max slippage"),buyAsset:F().describe("Asset to buy"),fees:G(fN),provider:P.enum(j),sellAmount:F().describe("Sell amount"),sellAsset:F().describe("Asset to sell")}),LL=Y({buyAsset:F().describe("Asset to buy"),destinationAddress:G(F().describe("Destination address")),estimatedTime:G(pN),expectedBuyAmount:F().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:F().describe("Expected Buy amount max slippage"),expiration:G(F().describe("Expiration")),fees:fN,inboundAddress:G(F().describe("Inbound address")),legs:W(HL),memo:G(F().describe("Memo")),meta:hA,providers:W(P.enum(j)),routeId:F().describe("Route ID"),sellAmount:F().describe("Sell amount"),sellAsset:F().describe("Asset to sell"),sourceAddress:G(F().describe("Source address")),targetAddress:G(F().describe("Target address")),totalSlippageBps:S().describe("Total slippage in bps"),tx:G(eH),txType:G(P.enum(JN)),warnings:cA}),lA=Y({error:G(F().describe("Error message")),providerErrors:G(W(Y({errorCode:G(P.enum(LN)),message:G(F()),provider:P.enum(j).optional()}))),quoteId:F().describe("Quote ID"),routes:W(LL)}),rA=P.object({chainId:P.enum(RN),createdAt:P.date(),id:P.number(),unit:P.string(),value:P.string()}),PL=P.array(rA),iA=P.union([rA,PL]),bF=W(Y({chain:P.enum(zN),decimal:S(),identifier:F(),symbol:F(),ticker:F(),value:F()})),zF=P.union([P.object({amount:P.string(),spender:P.string(),tokenIdentifier:P.string(),userWalletAddress:P.string()}),P.object({amount:P.string(),chainId:P.enum(RN),spender:P.string(),tokenContractAddress:P.string(),userWalletAddress:P.string()}),P.object({routeId:P.string()})]),JF=P.object({approvalTransaction:P.optional(P.object({data:P.string(),from:P.string(),gasLimit:P.optional(P.string()),gasPrice:P.optional(P.string()),to:P.string(),value:BN})),approvedAmount:P.string(),isApproved:P.boolean()}),FL=P.object({data:P.string().describe("Encoded approval call data"),from:P.string().describe("User wallet address"),gasLimit:P.string().optional().describe("Estimated gas limit"),gasPrice:P.string().optional().describe("Current gas price"),to:P.string().describe("Token contract address"),value:BN.describe("ETH value (always '0' for approvals)")}),OL=P.object({tx:P.string(),txType:P.literal("STELLAR")}),IL=P.union([FL,OL]),jA=P.object({buyAmount:P.string().describe("Buy amount").optional(),buyAmountMaxSlippage:P.string().describe("Buy amount max slippage").optional(),buyAsset:P.string().describe("Asset to buy"),expectedBuyAmount:P.string().describe("Expected Buy amount").optional(),expectedBuyAmountMaxSlippage:P.string().describe("Expected Buy amount max slippage").optional(),fees:fN,provider:P.enum(j),sellAmount:P.string().describe("Sell amount"),sellAsset:P.string().describe("Asset to sell")}),sA=jA.extend({estimatedTime:P.optional(pN),expiration:P.optional(P.string().describe("Expiration")),legs:P.array(jA),providers:P.array(P.enum(j)),routeId:P.string().describe("Route ID"),totalSlippageBps:P.number().describe("Total slippage in bps"),warnings:cA}).omit({provider:!0}),aA=P.object({method:P.string(),payload:P.optional(P.unknown()),url:P.string()}),RL=sA.extend({meta:dA,nextActions:P.optional(P.array(aA))}),QF=P.object({error:P.optional(P.string().describe("Error message")),providerErrors:P.optional(P.array(P.object({errorCode:P.optional(P.enum(LN)),message:P.optional(P.string()),provider:P.enum(j).optional()}))),quoteId:P.string().describe("Quote ID"),routes:P.array(RL)}),ZF=P.object({providers:P.array(P.enum(j)).optional().describe("Optional list of providers to query for trading pairs"),sellAsset:P.string().describe("Asset identifier to sell (e.g., 'BTC.BTC' or 'ETH.ETH')")}),BL=P.object({chain:P.enum(zN).describe("Chain the asset is on"),identifier:P.string().describe("Asset identifier (e.g., 'ETH.USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')"),providers:P.array(P.enum(j)).describe("Providers that support this trading pair"),symbol:P.string().describe("Asset symbol"),ticker:P.string().describe("Asset ticker")}),wF=P.object({buyAssets:P.array(BL).describe("List of assets that can be swapped to"),sellAsset:P.string().describe("The input sell asset identifier")}),eA=sA.extend({destinationAddress:P.string().describe("Destination address"),inboundAddress:P.optional(P.string().describe("Inbound address")),memo:P.optional(P.string().describe("Memo to include in the transaction")),meta:hA,sourceAddress:P.string().describe("Source address"),targetAddress:P.optional(P.string().describe("Target address")),tx:G(CA),txType:P.optional(P.enum(JN))}),GL=P.object({data:P.optional(P.record(P.string(),P.string().optional())),errorCode:P.enum(LN),message:P.string().optional(),provider:P.enum(j).optional()}),jF=P.object({error:P.optional(P.string().describe("Error message")),providerErrors:P.optional(P.array(GL)),quoteId:P.string().describe("Quote ID"),routes:P.array(eA)}),NT=eA.extend({approvalTx:IL.optional().describe("Optional approval transaction required before swap execution"),nextActions:P.optional(P.array(aA)),swapId:P.string().describe("The unique swap ID for tracking")});var q=_.extend({dynamicHeader:async()=>{let N=g.get("widgetId"),A=g.get("widgetKey");if(N&&A&&typeof window<"u"){let H=Math.floor(Date.now()/1000),L=window.location.origin,O=await HA(A,N,L,H);return{Origin:L,"X-Signature":O,"X-Timestamp":H.toString(),"x-widget-id":N}}let{swapKit:T}=g.get("apiKeys");return T?{"x-api-key":T}:{}}});async function YL(N){let A=await q.post(x("/track"),{json:N});try{let T=yA.safeParse(A);if(!T.success)throw new U("api_v2_invalid_response",T.error);return T.data}catch(T){return A}}async function ML(N){let{getQuote:A}=g.get("endpoints");if(A)return A(N);let H=g.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",L=await q.post(x(H),{json:N});if(L.error)throw new U("api_v2_server_error",{message:L.error});try{let O=lA.safeParse(L);if(!O.success)throw new U("api_v2_invalid_response",O.error);return O.data}catch{return L}}async function _L(N){let{getRouteWithTx:A}=g.get("endpoints");if(A)return A(N);let H=g.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",L=await q.post(x(H),{json:N});try{let O=NT.safeParse(L);if(!O.success)throw new U("api_v2_invalid_response",O.error);return O.data}catch(O){return console.error(new U("api_v2_invalid_response",O)),L}}async function SL({chain:N,address:A,scamFilter:T=!0}){let{getBalance:H}=g.get("endpoints");if(H)return H({address:A,chain:N});let L=x(`/balance?chain=${N}&address=${A}`),O=await q.get(L),R=Array.isArray(O)?O:[];return T?ZL(R):R}function DL(N){let A=$L(N).with({routeId:GN.string,spender:GN.string},({routeId:T,spender:H})=>x(`/approve?routeId=${T}&sourceAddress=${H}`)).with({assetValue:GN.instanceOf(n),spender:GN.string,userWallet:GN.string},({spender:T,userWallet:H,assetValue:L})=>x(`/approve?tokenIdentifier=${L.toString()}&userWalletAddress=${H}&spender=${T}&amount=${L.getValue("string")}`)).exhaustive();return q.get(A)}function UL(){let N=x("/providers");return q.get(N)}function XL(N){let A=x(`/tokens?provider=${N}`);return q.get(A)}function uL({query:N,chain:A,page:T,limit:H}){let L=new URLSearchParams({query:N});if(A!==void 0)L.set("chain",A);if(T!==void 0)L.set("page",T.toString());if(H!==void 0)L.set("limit",H.toString());let O=x(`/tokens/search?${L.toString()}`);return q.get(O)}async function gL(N){let A=x("/price"),T=await q.post(A,{json:N});try{let H=mA.safeParse(T);if(!H.success)throw new U("api_v2_invalid_response",H.error);return H.data}catch(H){throw new U("api_v2_invalid_response",H)}}async function WL(){let N=x("/gas"),A=await q.get(N);try{let T=iA.safeParse(A);if(!T.success)throw new U("api_v2_invalid_response",T.error);return Array.isArray(T)?T:[T]}catch(T){throw new U("api_v2_invalid_response",T)}}async function EL(N){let{destinationAddress:A}=N;if(!A)throw new U("chainflip_broker_invalid_params");let T=g.get("integrations").chainflip?.brokerUrl||x("/chainflip/broker/channel"),H=await q.post(T,{json:N});try{let L=fA.safeParse(H);if(!L.success)throw new U("api_v2_invalid_response",L.error);return L.data}catch(L){throw new U("api_v2_invalid_response",L)}}async function bL(N){let{destinationAddress:A}=N;if(!A)throw new U("chainflip_broker_invalid_params");let T=x("/near/channel"),H=await q.post(T,{json:N});try{let L=pA.safeParse(H);if(!L.success)throw new U("api_v2_invalid_response",L.error);return L.data}catch(L){throw new U("api_v2_invalid_response",L)}}function x(N){let{isDev:A,apiUrl:T,devApiUrl:H}=g.get("envs"),{enabled:L,quoteUrl:O,swapUrl:R}=g.get("localMode");if(L&&N){let[M]=N.split("?");if(M==="/quote"||M==="/v3/quote")return`${O}${N}`;if(M==="/swap"||M==="/v3/swap")return`${R}${N}`}return`${A?H:T}${N}`}function zL(N){try{return n.from({asset:N.identifier})}catch{return}}var JL=new Set(["OP.OP"]),QL=/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/im;function ZL(N){return N.filter((A)=>{let T=zL(A);if(!T)return!1;if(JL.has(T.toString().toUpperCase()))return!0;return(!yN.includes(T.chain)||T.isGasAsset||!!T.address)&&!QL.test(T.ticker)})}async function wL(N){let{getSwapTo:A}=g.get("endpoints");if(A)return A(N);let T=new URLSearchParams({sellAsset:N.sellAsset});if(N.providers?.length)for(let R of N.providers)T.append("providers",R);let H=x(`/swapTo?${T.toString()}`),L=await q.get(H);if(!Array.isArray(L))return{buyAssets:[],sellAsset:N.sellAsset};let O=[];for(let R of L)try{let $=n.from({asset:R});O.push({chain:$.chain,identifier:$.toString(),providers:[],symbol:$.symbol,ticker:$.ticker})}catch{}return{buyAssets:O,sellAsset:N.sellAsset}}var CN={};lN(CN,{getThorchainQueue:()=>qL,getTcyStakers:()=>pL,getTcyStaker:()=>fL,getTcyClaimers:()=>oL,getTcyClaimer:()=>yL,getTNSPreferredAsset:()=>kL,getTHORNodeTNSDetails:()=>AT,getRunePoolProviderInfo:()=>tL,getRunePoolInfo:()=>mL,getNodes:()=>nL,getMimirInfo:()=>vL,getLastBlock:()=>xL,getInboundAddresses:()=>KL});import{match as jL}from"ts-pattern";function v(N){let{isStagenet:A}=g.get("envs"),T=g.get("thornodeUrls");return`${jL({isStagenet:A,type:N}).with({type:"mayachain"},({isStagenet:L})=>L?T.MAYA_STAGENET:T.MAYA).otherwise(({isStagenet:L})=>L?T.THOR_STAGENET:T.THOR)}/${N??"thorchain"}`}function VL(N){let A=N==="mayachain"?"mayaname":"thorname";return`${v(N)}/${A}`}function xL(N="thorchain"){return _.get(`${v(N)}/lastblock`)}function qL(N){return _.get(`${v(N)}/queue`)}function nL(N){return _.get(`${v(N)}/nodes`)}function vL(N){return _.get(`${v(N)}/mimir`)}function KL(N){return _.get(`${v(N)}/inbound_addresses`)}async function AT({type:N,name:A}){try{return await _.get(`${VL(N)}/${A}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:A,owner:"",preferred_asset:""}}}async function kL({type:N,tns:A}){let T=await AT({name:A,type:N});if(!T.preferred_asset||T.preferred_asset===".")return;return n.from({asset:T.preferred_asset,asyncTokenLookup:!0})}function mL(N){return _.get(`${v(N)}/runepool`)}function tL({type:N,thorAddress:A}){return _.get(`${v(N)}/rune_provider/${A}`)}function fL({type:N,address:A}){return _.get(`${v(N)}/tcy_staker/${A}`)}function pL(N){return _.get(`${v(N)}/tcy_stakers`)}function yL({type:N,address:A}){return _.get(`${v(N)}/tcy_claimer/${A}`)}function oL(N){return _.get(`${v(N)}/tcy_claimers`)}var CF={...oN,mayachainMidgard:QA,thorchainMidgard:JA,thornode:CN};
|
|
5
|
+
export{hL as a,LN as b,ZN as c,j as d,wN as e,IT as f,RT as g,BT as h,U as i,iL as j,MN as k,sN as l,eL as m,GT as n,V as o,g as p,_ as q,HA as r,_P as s,c as t,xN as u,ZT as v,l as w,WP as x,EP as y,bP as z,zP as A,KP as B,vT as C,DA as D,UA as E,XA as F,XN as G,qN as H,y as I,FN as J,kP as K,mP as L,C as M,t as N,dT as O,n as P,iP as Q,EN as R,xA as S,JN as T,qA as U,nA as V,vA as W,KA as X,IF as Y,RF as Z,BF as _,GF as $,NN as aa,kA as ba,$F as ca,mA as da,YF as ea,MF as fa,tA as ga,jH as ha,fA as ia,ZA as ja,_F as ka,pA as la,yA as ma,SF as na,DF as oa,fN as pa,pN as qa,tH as ra,UF as sa,XF as ta,fH as ua,pH as va,yH as wa,uF as xa,cH as ya,lH as za,rH as Aa,iH as Ba,gF as Ca,sH as Da,aH as Ea,oA as Fa,WF as Ga,NL as Ha,EF as Ia,AL as Ja,TL as Ka,dA as La,hA as Ma,cA as Na,LL as Oa,lA as Pa,rA as Qa,iA as Ra,zF as Sa,JF as Ta,FL as Ua,OL as Va,IL as Wa,QF as Xa,ZF as Ya,BL as Za,wF as _a,eA as $a,GL as ab,jF as bb,NT as cb,CF as db};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as QJ,$a as QQ,A as TG,Aa as kJ,B as OG,Ba as TJ,C as vG,Ca as OJ,D as AG,Da as vJ,E as fG,Ea as AJ,F as yG,Fa as fJ,G as wG,Ga as yJ,H as bG,Ha as wJ,I as cG,Ia as bJ,J as hG,Ja as cJ,K as mG,Ka as hJ,L as uG,La as mJ,M as dG,Ma as uJ,N as lG,Na as dJ,O as pG,Oa as lJ,P as oG,Pa as pJ,Q as rG,Qa as oJ,R,Ra as rJ,S as sG,Sa as sJ,T as nG,Ta as nJ,U as iG,Ua as iJ,V as aG,Va as aJ,W as tG,Wa as tJ,X as eG,Xa as eJ,Y as zJ,Ya as zQ,Z as GJ,Za as GQ,_ as JJ,_a as JQ,a as F,aa as ZJ,ab as ZQ,b as LG,ba as $J,bb as $Q,c as RG,ca as XJ,cb as XQ,d as YG,da as HJ,db as HQ,e as FG,ea as VJ,f as A,fa as jJ,g as xG,ga as _J,h as l,ha as BJ,i as L,ia as LJ,j as WG,ja as RJ,k as j,ka as YJ,l as qG,la as FJ,m as IG,ma as xJ,n as KG,na as WJ,o as MG,oa as qJ,p as N,pa as IJ,q as EG,qa as KJ,r as NG,ra as MJ,s as PG,sa as EJ,t as C,ta as NJ,u as SG,ua as PJ,v as CG,va as SJ,w as DG,wa as CJ,x as gG,xa as DJ,y as UG,ya as gJ,z as kG,za as UJ}from"./chunk-sht0fjw7.js";export*from"@swapkit/tokens";export*from"@swapkit/types";var f={average:1,fast:1.5,fastest:2};function P(z="average"){let G=N.get("feeMultipliers");if(G&&G[z]!==void 0)return G[z];return f[z]}function y(z="average"){let G=P(z),Q=10n,J=BigInt(Math.round(G*10));return{denominator:Q,numerator:J}}function zz(z,G="average"){let{numerator:Q,denominator:J}=y(G);return z*Q/J}function Gz(z,G="average",Q=!1){let J=P(G),Z=z*J;return Q?Math.floor(Z):Z}import{Chain as S,EVMChains as w}from"@swapkit/types";function K(z,G){if("index"in G)return[...z.slice(0,z.length-1),G.index];if("change"in G){let[Q,J,Z,,$]=z;return[Q,J,Z,G.change,$]}if("account"in G){let[Q,J,,Z,$]=z;return[Q,J,G.account,Z,$]}return z}function b([z,G,Q,J,Z],{allHardened:$}={}){let H=$?"'":"",V=typeof Z!=="number";if(typeof J!=="number")return`m/${z}'/${G}'/${Q}'`;return`m/${z}'/${G}'/${Q}'/${J}${H}${V?"":`/${Z}${H}`}`}function $z({chain:z,index:G,addressIndex:Q=0,type:J}){if(w.includes(z)){if(J&&["legacy","account"].includes(J))return[44,60,0,G];if(J==="ledgerLive")return[44,60,G,0,Q];return K(F[z],{index:G})}if(z===S.Solana){if(J==="account")return[44,501,0,G];return K(F[z],{index:G})}let Z=z===S.Litecoin?2:0;switch(J){case"nativeSegwitMiddleAccount":return[84,Z,G,0,Q];case"segwit":return[49,Z,0,0,G];case"legacy":return[44,Z,0,0,G];default:return K(F[z],{index:G})}}function Xz(z){let[G,Q,J]=z.split("/").map((Z)=>Number.parseInt(Z,10));switch(Q){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var Hz=Object.keys(F).reduce((z,G)=>{return z[G]=b(F[G]),z},{});import{Chain as c,getChainConfig as h}from"@swapkit/types";function m({liquidityUnits:z,poolUnits:G,runeDepth:Q}){let J=_(z),Z=_(G),$=_(Q),H=J.mul($),V=Z.mul(Z).mul(2),X=Z.mul(J).mul(2),B=J.mul(J),Y=Z.mul(Z).mul(Z);return H.mul(V.sub(X).add(B)).div(Y)}function u({liquidityUnits:z,poolUnits:G,assetDepth:Q}){let J=_(z),Z=_(G),$=_(Q),H=J.mul($),V=Z.mul(Z).mul(2),X=Z.mul(J).mul(2),B=J.mul(J),Y=H.mul(V.sub(X).add(B)),x=Z.mul(Z).mul(Z);return Y.div(x)}function Bz({percent:z,runeDepth:G,liquidityUnits:Q,poolUnits:J}){return m({liquidityUnits:Q,poolUnits:J,runeDepth:G}).mul(z)}function Lz({percent:z,assetDepth:G,liquidityUnits:Q,poolUnits:J}){return u({assetDepth:G,liquidityUnits:Q,poolUnits:J}).mul(z)}function _(z){return R.fromBigInt(BigInt(z),h(c.THORChain).baseDecimal)}function d({liquidityUnits:z,poolUnits:G,runeDepth:Q,assetDepth:J}){return{assetAmount:_(J).mul(z).div(G),runeAmount:_(Q).mul(z).div(G)}}function Rz({liquidityUnits:z,poolUnits:G,runeDepth:Q,assetDepth:J,percent:Z}){return Object.fromEntries(Object.entries(d({assetDepth:J,liquidityUnits:z,poolUnits:G,runeDepth:Q})).map(([$,H])=>[$,H.mul(Z)]))}function Yz({runeDepth:z,poolUnits:G,assetDepth:Q,liquidityUnits:J,runeAmount:Z,assetAmount:$}){let H=new R({decimal:8,value:z}),V=new R({decimal:8,value:Q}),X=new R({decimal:8,value:G}),B=new R({decimal:8,value:Z}),Y=new R({decimal:8,value:$}),x=B.mul(V),M=Y.mul(H),U=B.mul(Y),k=H.mul(V),T=X.mul(x.add(M.add(U.mul(2)))),O=x.add(M.add(k.mul(2))),E=T.div(O),I=_(J).add(E);if(E.getBaseValue("number")===0)return I.div(X).getBaseValue("number");let v=X.add(I);return I.div(v).getBaseValue("number")}function Fz({runeAmount:z,assetAmount:G,runeDepth:Q,assetDepth:J}){if(z==="0"||G==="0"||Q==="0"||J==="0")return 0;let Z=_(Q),$=_(J),H=_(G),V=_(z),X=H.mul(Z).sub($.mul(V)),B=$.mul(V).add(Z.mul($));return Math.abs(X.div(B).getBaseValue("number"))}import{Chain as W}from"@swapkit/types";import{match as p}from"ts-pattern";function Mz({type:z,address:G}){return`${z}:${G}`}function Ez({address:z,unbondAmount:G}){return`${"UNBOND"}:${z}:${G}`}function Nz(z){return q("POOL+",z)}function Pz({chain:z,symbol:G,address:Q,...J}){let Z=o({chain:z,symbol:G}),$=Q?`:${Q}:`:":";return q(`${"+"}:${Z}${$}`,J)}function Sz({chain:z,symbol:G,ticker:Q,basisPoints:J,targetAsset:Z}){let $=z==="ETH"&&Q!=="ETH"?`${Q}-${G.slice(-3)}`:G,H=Z?`:${Z}`:"";return`${"-"}:${z}.${$}:${J}${H}`}function Cz({basisPoints:z,...G}){return q(`${"POOL-"}:${z}`,G)}function Dz({name:z,chain:G,address:Q,owner:J}){let Z=`${"~"}:${z}:${G}:${Q}`,$=J?`:${J}`:"";return`${Z}${$}`}function gz({name:z,chain:G,asset:Q,payout:J,owner:Z}){return`${"~"}:${z}:${G}:${J}:${Z}:${Q}`}function Uz(z,{address:G}){return`${z}:${G}`}function kz(z,{unstakeBps:G,...Q}){let J=G?`:${G}`:"",Z=`${z}${J}`;return q(`${Z}`,Q)}function q(z,{affiliateAddress:G,affiliateBasisPoints:Q}={}){let J=`${z}${G?`:${G}:${Q||0}`:""}`;return J.endsWith(":")?J.slice(0,-1):J}function o({chain:z,symbol:G}){return p(z).with(W.Bitcoin,W.Dogecoin,W.Litecoin,()=>z.slice(0,1).toLowerCase()).with(W.BitcoinCash,()=>"c").otherwise(()=>`${z}.${G}`)}function Tz(z){if(z<0)throw new L({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:z}});return 10+z}function Oz(z){if(z<0)throw new L({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:z}});return Math.round((10+z*1.0512)*10000000000)/10000000000}function vz(z){if(z.length>30)return!1;let G=/^[a-zA-Z0-9+_-]+$/g;return!!z.match(G)}import{getChainConfig as D}from"@swapkit/types";function cz(){return typeof window.ethereum<"u"}function hz(z){return r().includes(z)}function r(){let z=window?.ethereum&&!window.ethereum?.isBraveWallet,G=window?.ctrl||window?.ethereum?.__XDEFI,Q=window?.vultisig,J=window?.ethereum?.isBraveWallet,Z=window?.ethereum?.isTrust||window?.trustwallet,$=window?.ethereum?.overrideIsMetaMask&&window?.ethereum?.selectedProvider?.isCoinbaseWallet||window?.coinbaseWalletExtension,H=window?.bitkeep?.ethereum,V=window?.$onekey?.ethereum,X=[];if(z)X.push(j.METAMASK);if(G)X.push(j.CTRL);if(Q)X.push(j.VULTISIG);if(J)X.push(j.BRAVE);if(Z)X.push(j.TRUSTWALLET_WEB);if($)X.push(j.COINBASE_WEB);if(a())X.push(j.OKX_MOBILE);if(H)X.push(j.BITGET);if(V)X.push(j.ONEKEY);return X}async function s(z,G,Q){let J=D(G);try{await g({method:"wallet_switchEthereumChain",params:[{chainId:J.chainIdHex}],provider:z})}catch(Z){if(!Q)throw new L("helpers_failed_to_switch_network",{error:Z,reason:"networkParams not provided"});await i(z,Q)}}function mz({chains:z,supportedChains:G,walletType:Q}){let J=z.filter(($)=>!$||G.includes($));if(J.length===0)throw new L("wallet_chain_not_supported",{chain:z.join(", "),wallet:Q});let Z=z.filter(($)=>!G.includes($));return C({condition:Z.length>0,id:`wallet_chain_not_supported_${Q}`,warning:`${Q} wallet does not support the following chains: ${Z.join(", ")}. These chains will be ignored.`}),J}function n(z,G,Q){return async(...J)=>{let{chainIdHex:Z}=D(Q);if((await G.getNetwork()).chainId.toString()===Z)return z(...J);try{await s(G,Q)}catch($){throw new L({errorKey:"helpers_failed_to_switch_network",info:{error:$}})}return z(...J)}}function uz({toolbox:z,chain:G,provider:Q,methodNames:J=[]}){let $=[...J,"approve","approvedAmount","call","sendTransaction","transfer","isApproved","approvedAmount","EIP1193SendTransaction","getFeeData","broadcastTransaction","estimateCall","estimateGasLimit","estimateGasPrices","createContractTxObject"].reduce((H,V)=>{if(!z[V])return H;let X=z[V];if(typeof X!=="function")return H;let B=n(X,Q,G);return{...H,[V]:B}},{});return{...z,...$}}function i(z,G){return g({method:"wallet_addEthereumChain",params:[G],provider:z})}function dz(z){window.ethereum?.on("accountsChanged",()=>z()),window.ctrl?.ethereum.on("accountsChanged",()=>z())}function lz(){let{isTrust:z,isBraveWallet:G,__XDEFI:Q,overrideIsMetaMask:J,selectedProvider:Z}=window?.ethereum||{};if(z)return j.TRUSTWALLET_WEB;if(G)return j.BRAVE;if(J&&Z?.isCoinbaseWallet)return j.COINBASE_WEB;if(Q)return j.CTRL;if(window?.$onekey?.ethereum)return j.ONEKEY;return j.METAMASK}function pz(){let z=[];function G(J){if(z.map((Z)=>Z.info.uuid).includes(J.detail.info.uuid))return;z.push(J.detail)}window.addEventListener("eip6963:announceProvider",G),window.dispatchEvent(new Event("eip6963:requestProvider"));function Q(){window.removeEventListener("eip6963:announceProvider",G)}return{providers:z,removeEIP6963EventListener:Q}}function a(){let z=navigator.userAgent,G=/iphone|ipad|ipod|ios/i.test(z),Q=/android|XiaoMi|MiuiBrowser/i.test(z),J=G||Q,Z=/OKApp/i.test(z);return J&&Z}function g({provider:z,params:G,method:Q}){if(!z?.send)throw new L("helpers_not_found_provider");let J=G?Array.isArray(G)?G:[G]:[];return z.send(Q,J)}export{PG as wrapWithThrow,n as wrapMethodWithNetworkSwitch,C as warnOnce,vz as validateTNS,pG as validateIdentifier,K as updateDerivationPath,NJ as toHexTransactionValue,s as switchEVMWalletNetwork,MG as swapKitConfigStore,qG as subscribeWalletOptionRegistration,NG as signWidgetRequest,IG as registerWalletOption,WG as registerErrorCodes,g as providerRequest,uz as prepareNetworkSwitch,EJ as parseTransactionValue,hG as parseSymbolForAddress,a as okxMobileEnabled,r as listWeb3EVMWallets,cz as isWeb3Detected,MJ as isTransactionValue,yG as isGasAsset,hz as isDetected,gG as initializeRPCUrlsWithFallback,Xz as getWalletFormatFor,mG as getTokenLogoURI,Tz as getTHORNameCost,Rz as getSymmetricWithdraw,d as getSymmetricPoolShare,CG as getRPCUrlSync,DG as getRPCUrl,rG as getMinAmountByChain,Sz as getMemoForWithdraw,Ez as getMemoForUnbond,kz as getMemoForTcyStake,Uz as getMemoForTcyClaim,Cz as getMemoForRunePoolWithdraw,Nz as getMemoForRunePoolDeposit,Dz as getMemoForNameRegister,gz as getMemoForNamePreferredAssetRegister,Mz as getMemoForLeaveAndBond,Pz as getMemoForDeposit,Oz as getMAYANameCost,Fz as getLiquiditySlippage,y as getFeeMultiplierAsBigInt,P as getFeeMultiplier,UG as getExplorerTxUrl,kG as getExplorerAddressUrl,Yz as getEstimatedPoolShare,lz as getETHDefaultWallet,pz as getEIP6963Wallets,$z as getDerivationPathFor,wG as getCommonAssetInfo,TG as getChainIdentifier,Bz as getAsymmetricRuneWithdrawAmount,m as getAsymmetricRuneShare,Lz as getAsymmetricAssetWithdrawAmount,u as getAsymmetricAssetShare,bG as getAssetType,dG as formatBigIntToSafeValue,uG as findAssetBy,mz as filterSupportedChains,fG as fetchTokenInfo,b as derivationPathToString,vG as decodeABIString,AG as decodeABIDynamicString,cG as assetFromString,zz as applyFeeMultiplierToBigInt,Gz as applyFeeMultiplier,i as addEVMWalletNetwork,dz as addAccountsChangedCallback,SG as _rpcCache,RG as WarningCodeEnum,j as WalletOption,iG as TxnType,tG as TxnStatus,SJ as TronTransactionSchema,WJ as TransactionSchema,qJ as TransactionDTOSchema,eG as TrackingStatus,GJ as TrackingRequestSchema,JJ as TrackingRequestQuerySchema,xJ as TrackerResponseSchema,zJ as TokenSchema,XJ as TokenDetailsMetadataSchema,TJ as TONTransactionSchema,kJ as TONTransactionMessageSchema,JQ as SwapToResponseSchema,zQ as SwapToRequestSchema,GQ as SwapToAssetSchema,XQ as SwapRouteV2ResponseSchema,R as SwapKitNumber,L as SwapKitError,HQ as SwapKitApi,tJ as SwapApprovalTransactionSchema,aJ as StellarApprovalTransactionSchema,UJ as StarknetTransactionSchema,N as SKConfig,dJ as RouteQuoteWarningSchema,nG as RouteQuoteTxType,ZQ as RouteQuoteProviderErrorSchema,uJ as RouteQuoteMetadataV2Schema,mJ as RouteQuoteMetadataSchema,cJ as RouteQuoteMetadataAssetSchema,bJ as RouteLegWithoutAddressesSchema,wJ as RouteLegSchema,EG as RequestClient,eJ as QuoteV3ResponseSchema,$Q as QuoteV2ResponseSchema,QQ as QuoteRouteV2Response,pJ as QuoteResponseSchema,lJ as QuoteResponseRouteItem,VJ as QuoteRequestSchema,YG as ProviderName,aG as ProviderAction,sG as PriorityLabel,HJ as PriceResponseSchema,jJ as PriceRequestSchema,F as NetworkDerivationPath,FJ as NearSwapResponseSchema,YJ as NearDepositChannelResultSchema,RJ as NearDepositChannelParamsSchema,l as MemoType,KG as LedgerErrorCode,fJ as HyperCoreTypedDataTransactionSchema,yJ as HyperCoreSendAssetTransactionSchema,AJ as HyperCoreSendAssetActionSchema,vJ as HyperCoreEip712TypedDataSchema,OJ as HYPERCORE_USDC_TOKEN_ID,oJ as GasSchema,rJ as GasResponseSchema,IJ as FeesSchema,FG as FeeTypeEnum,A as FeeOption,KJ as EstimatedTimeSchema,LG as ErrorCode,PJ as EVMTransactionSchema,DJ as EVMTransactionDetailsSchema,CJ as EVMTransactionDetailsParamsSchema,Hz as DerivationPath,LJ as DepositChannelResponseSchema,_J as DepositChannelParamsSchema,f as DEFAULT_FEE_MULTIPLIERS,gJ as CosmosTransactionSchema,OG as CommonAssetStrings,$J as CoinGeckoMetadataSchema,hJ as ChainflipMetadataSchema,BJ as BrokerDepositChannelParamsSchema,lG as BigIntArithmetics,ZJ as AssetValueSchema,oG as AssetValue,nJ as ApproveResponseSchema,sJ as ApproveRequestParams,xG as ApproveMode,iJ as ApprovalTransactionSchema,QJ as ApiV2ErrorSchema};
|
|
1
|
+
import{$ as jJ,$a as jQ,A as wG,Aa as fJ,B as bG,Ba as wJ,C as cG,Ca as bJ,D as mG,Da as cJ,E as hG,Ea as mJ,F as uG,Fa as hJ,G as dG,Ga as uJ,H as pG,Ha as dJ,I as lG,Ia as pJ,J as rG,Ja as lJ,K as oG,Ka as rJ,L as sG,La as oJ,M as nG,Ma as sJ,N as iG,Na as nJ,O as aG,Oa as iJ,P as tG,Pa as aJ,Q as eG,Qa as tJ,R,Ra as eJ,S as zJ,Sa as zQ,T as GJ,Ta as GQ,U as JJ,Ua as JQ,V as QJ,Va as QQ,W as ZJ,Wa as ZQ,X as $J,Xa as $Q,Y as HJ,Ya as HQ,Z as VJ,Za as VQ,_ as XJ,_a as XQ,a as W,aa as BJ,ab as BQ,b as WG,ba as _J,bb as _Q,c as qG,ca as LJ,cb as LQ,d as KG,da as RJ,db as RQ,e as MG,ea as YJ,f as A,fa as FJ,g as EG,ga as xJ,h as s,ha as IJ,i as L,ia as WJ,j as kG,ja as qJ,k as j,ka as KJ,l as NG,la as MJ,m as SG,ma as EJ,n as gG,na as kJ,o as DG,oa as NJ,p as S,pa as SJ,q as CG,qa as gJ,r as PG,ra as DJ,s as UG,sa as CJ,t as D,ta as PJ,u as TG,ua as UJ,v as OG,va as TJ,w as vG,wa as OJ,x as yG,xa as vJ,y as AG,ya as yJ,z as fG,za as AJ}from"./chunk-q0s1vae8.js";export*from"@swapkit/tokens";export*from"@swapkit/types";var f={average:1,fast:1.5,fastest:2};function g(z="average"){let G=S.get("feeMultipliers");if(G&&G[z]!==void 0)return G[z];return f[z]}function w(z="average"){let G=g(z),Q=10n,J=BigInt(Math.round(G*10));return{denominator:Q,numerator:J}}function Zz(z,G="average"){let{numerator:Q,denominator:J}=w(G);return z*Q/J}function $z(z,G="average",Q=!1){let J=g(G),Z=z*J;return Q?Math.floor(Z):Z}import{Chain as I,EVMChains as b}from"@swapkit/types";import{match as c}from"ts-pattern";function F(z,G){let Q=z.length-1;return z.map((Z,$)=>{if($===Q&&G.index!==void 0)return G.index;if($===0&&G.purpose!==void 0)return G.purpose;if($===2&&G.account!==void 0)return G.account;if($===3&&G.change!==void 0)return G.change;return Z})}var E={bech32:84,legacy:44,p2sh:49,taproot:86},m=Object.freeze([I.Near,I.Stellar,I.Sui]),Bz=Object.freeze([I.Ton]);function h({chain:z,derivationPath:G,index:Q=0}){if(G)return G;return F(W[z],m.includes(z)?{account:Q}:{index:Q})}function u([z,G,Q,J,Z],{allHardened:$}={}){let V=$?"'":"",X=typeof Z!=="number";if(typeof J!=="number")return`m/${z}'/${G}'/${Q}'`;return`m/${z}'/${G}'/${Q}'/${J}${V}${X?"":`/${Z}${V}`}`}function _z({chain:z,index:G,addressIndex:Q=0,type:J}){let Z=W[z],$=b.includes(z)?"evm":z===I.Solana?"solana":"other";return c([$,J]).with(["evm","legacy"],["evm","account"],()=>[44,60,0,G]).with(["evm","ledgerLive"],()=>[44,60,G,0,Q]).with(["evm","nativeSegwitMiddleAccount"],["evm","segwit"],["evm",void 0],()=>F(Z,{index:G})).with(["solana","account"],()=>[44,501,0,G]).with(["solana","legacy"],["solana","ledgerLive"],["solana","nativeSegwitMiddleAccount"],["solana","segwit"],["solana",void 0],()=>F(Z,{index:G})).with(["other","nativeSegwitMiddleAccount"],()=>F(Z,{account:G,index:Q,purpose:E.bech32})).with(["other","segwit"],()=>F(Z,{account:0,index:G,purpose:E.p2sh})).with(["other","legacy"],()=>F(Z,{account:0,index:G,purpose:E.legacy})).with(["other","account"],["other","ledgerLive"],["other",void 0],()=>h({chain:z,index:G})).exhaustive()}function Lz(z){let[G,Q]=z.split("/").map((J)=>Number.parseInt(J,10));switch(Q){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var Rz=Object.freeze(Object.fromEntries(Object.keys(W).map((z)=>[z,u(W[z])])));import{Chain as d,getChainConfig as p}from"@swapkit/types";function l({liquidityUnits:z,poolUnits:G,runeDepth:Q}){let J=B(z),Z=B(G),$=B(Q),V=J.mul($),X=Z.mul(Z).mul(2),H=Z.mul(J).mul(2),_=J.mul(J),Y=Z.mul(Z).mul(Z);return V.mul(X.sub(H).add(_)).div(Y)}function r({liquidityUnits:z,poolUnits:G,assetDepth:Q}){let J=B(z),Z=B(G),$=B(Q),V=J.mul($),X=Z.mul(Z).mul(2),H=Z.mul(J).mul(2),_=J.mul(J),Y=V.mul(X.sub(H).add(_)),x=Z.mul(Z).mul(Z);return Y.div(x)}function Iz({percent:z,runeDepth:G,liquidityUnits:Q,poolUnits:J}){return l({liquidityUnits:Q,poolUnits:J,runeDepth:G}).mul(z)}function Wz({percent:z,assetDepth:G,liquidityUnits:Q,poolUnits:J}){return r({assetDepth:G,liquidityUnits:Q,poolUnits:J}).mul(z)}function B(z){return R.fromBigInt(BigInt(z),p(d.THORChain).baseDecimal)}function o({liquidityUnits:z,poolUnits:G,runeDepth:Q,assetDepth:J}){return{assetAmount:B(J).mul(z).div(G),runeAmount:B(Q).mul(z).div(G)}}function qz({liquidityUnits:z,poolUnits:G,runeDepth:Q,assetDepth:J,percent:Z}){return Object.fromEntries(Object.entries(o({assetDepth:J,liquidityUnits:z,poolUnits:G,runeDepth:Q})).map(([$,V])=>[$,V.mul(Z)]))}function Kz({runeDepth:z,poolUnits:G,assetDepth:Q,liquidityUnits:J,runeAmount:Z,assetAmount:$}){let V=new R({decimal:8,value:z}),X=new R({decimal:8,value:Q}),H=new R({decimal:8,value:G}),_=new R({decimal:8,value:Z}),Y=new R({decimal:8,value:$}),x=_.mul(X),k=Y.mul(V),U=_.mul(Y),T=V.mul(X),O=H.mul(x.add(k.add(U.mul(2)))),v=x.add(k.add(T.mul(2))),N=O.div(v),M=B(J).add(N);if(N.getBaseValue("number")===0)return M.div(H).getBaseValue("number");let y=H.add(M);return M.div(y).getBaseValue("number")}function Mz({runeAmount:z,assetAmount:G,runeDepth:Q,assetDepth:J}){if(z==="0"||G==="0"||Q==="0"||J==="0")return 0;let Z=B(Q),$=B(J),V=B(G),X=B(z),H=V.mul(Z).sub($.mul(X)),_=$.mul(X).add(Z.mul($));return Math.abs(H.div(_).getBaseValue("number"))}import{Chain as q}from"@swapkit/types";import{match as n}from"ts-pattern";function Dz({type:z,address:G}){return`${z}:${G}`}function Cz({address:z,unbondAmount:G}){return`${"UNBOND"}:${z}:${G}`}function Pz(z){return K("POOL+",z)}function Uz({chain:z,symbol:G,address:Q,...J}){let Z=i({chain:z,symbol:G}),$=Q?`:${Q}:`:":";return K(`${"+"}:${Z}${$}`,J)}function Tz({chain:z,symbol:G,ticker:Q,basisPoints:J,targetAsset:Z}){let $=z==="ETH"&&Q!=="ETH"?`${Q}-${G.slice(-3)}`:G,V=Z?`:${Z}`:"";return`${"-"}:${z}.${$}:${J}${V}`}function Oz({basisPoints:z,...G}){return K(`${"POOL-"}:${z}`,G)}function vz({name:z,chain:G,address:Q,owner:J}){let Z=`${"~"}:${z}:${G}:${Q}`,$=J?`:${J}`:"";return`${Z}${$}`}function yz({name:z,chain:G,asset:Q,payout:J,owner:Z}){return`${"~"}:${z}:${G}:${J}:${Z}:${Q}`}function Az(z,{address:G}){return`${z}:${G}`}function fz(z,{unstakeBps:G,...Q}){let J=G?`:${G}`:"",Z=`${z}${J}`;return K(`${Z}`,Q)}function K(z,{affiliateAddress:G,affiliateBasisPoints:Q}={}){let J=`${z}${G?`:${G}:${Q||0}`:""}`;return J.endsWith(":")?J.slice(0,-1):J}function i({chain:z,symbol:G}){return n(z).with(q.Bitcoin,q.Dogecoin,q.Litecoin,()=>z.slice(0,1).toLowerCase()).with(q.BitcoinCash,()=>"c").otherwise(()=>`${z}.${G}`)}function wz(z){if(z<0)throw new L({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:z}});return 10+z}function bz(z){if(z<0)throw new L({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:z}});return Math.round((10+z*1.0512)*10000000000)/10000000000}function cz(z){if(z.length>30)return!1;let G=/^[a-zA-Z0-9+_-]+$/g;return!!z.match(G)}import{getChainConfig as C}from"@swapkit/types";function lz(){return typeof window.ethereum<"u"}function rz(z){return a().includes(z)}function a(){let z=window?.ethereum&&!window.ethereum?.isBraveWallet,G=window?.ctrl||window?.ethereum?.__XDEFI,Q=window?.vultisig,J=window?.ethereum?.isBraveWallet,Z=window?.ethereum?.isTrust||window?.trustwallet,$=window?.ethereum?.overrideIsMetaMask&&window?.ethereum?.selectedProvider?.isCoinbaseWallet||window?.coinbaseWalletExtension,V=window?.bitkeep?.ethereum,X=window?.$onekey?.ethereum,H=[];if(z)H.push(j.METAMASK);if(G)H.push(j.CTRL);if(Q)H.push(j.VULTISIG);if(J)H.push(j.BRAVE);if(Z)H.push(j.TRUSTWALLET_WEB);if($)H.push(j.COINBASE_WEB);if(Gz())H.push(j.OKX_MOBILE);if(V)H.push(j.BITGET);if(X)H.push(j.ONEKEY);return H}async function t(z,G,Q){let J=C(G);try{await P({method:"wallet_switchEthereumChain",params:[{chainId:J.chainIdHex}],provider:z})}catch(Z){if(!Q)throw new L("helpers_failed_to_switch_network",{error:Z,reason:"networkParams not provided"});await zz(z,Q)}}function oz({chains:z,supportedChains:G,walletType:Q}){let J=z.filter(($)=>!$||G.includes($));if(J.length===0)throw new L("wallet_chain_not_supported",{chain:z.join(", "),wallet:Q});let Z=z.filter(($)=>!G.includes($));return D({condition:Z.length>0,id:`wallet_chain_not_supported_${Q}`,warning:`${Q} wallet does not support the following chains: ${Z.join(", ")}. These chains will be ignored.`}),J}function e(z,G,Q){return async(...J)=>{let{chainIdHex:Z}=C(Q);if((await G.getNetwork()).chainId.toString()===Z)return z(...J);try{await t(G,Q)}catch($){throw new L({errorKey:"helpers_failed_to_switch_network",info:{error:$}})}return z(...J)}}function sz({toolbox:z,chain:G,provider:Q,methodNames:J=[]}){let $=[...J,"approve","approvedAmount","call","sendTransaction","transfer","isApproved","approvedAmount","EIP1193SendTransaction","getFeeData","broadcastTransaction","estimateCall","estimateGasLimit","estimateGasPrices","createContractTxObject"].reduce((V,X)=>{if(!z[X])return V;let H=z[X];if(typeof H!=="function")return V;let _=e(H,Q,G);return{...V,[X]:_}},{});return{...z,...$}}function zz(z,G){return P({method:"wallet_addEthereumChain",params:[G],provider:z})}function nz(z){window.ethereum?.on("accountsChanged",()=>z()),window.ctrl?.ethereum.on("accountsChanged",()=>z())}function iz(){let{isTrust:z,isBraveWallet:G,__XDEFI:Q,overrideIsMetaMask:J,selectedProvider:Z}=window?.ethereum||{};if(z)return j.TRUSTWALLET_WEB;if(G)return j.BRAVE;if(J&&Z?.isCoinbaseWallet)return j.COINBASE_WEB;if(Q)return j.CTRL;if(window?.$onekey?.ethereum)return j.ONEKEY;return j.METAMASK}function az(){let z=[];function G(J){if(z.map((Z)=>Z.info.uuid).includes(J.detail.info.uuid))return;z.push(J.detail)}window.addEventListener("eip6963:announceProvider",G),window.dispatchEvent(new Event("eip6963:requestProvider"));function Q(){window.removeEventListener("eip6963:announceProvider",G)}return{providers:z,removeEIP6963EventListener:Q}}function Gz(){let z=navigator.userAgent,G=/iphone|ipad|ipod|ios/i.test(z),Q=/android|XiaoMi|MiuiBrowser/i.test(z),J=G||Q,Z=/OKApp/i.test(z);return J&&Z}function P({provider:z,params:G,method:Q}){if(!z?.send)throw new L("helpers_not_found_provider");let J=G?Array.isArray(G)?G:[G]:[];return z.send(Q,J)}export{UG as wrapWithThrow,e as wrapMethodWithNetworkSwitch,D as warnOnce,cz as validateTNS,aG as validateIdentifier,F as updateDerivationPath,PJ as toHexTransactionValue,t as switchEVMWalletNetwork,DG as swapKitConfigStore,NG as subscribeWalletOptionRegistration,PG as signWidgetRequest,h as resolveDerivationPath,SG as registerWalletOption,kG as registerErrorCodes,P as providerRequest,sz as prepareNetworkSwitch,CJ as parseTransactionValue,rG as parseSymbolForAddress,Gz as okxMobileEnabled,a as listWeb3EVMWallets,lz as isWeb3Detected,DJ as isTransactionValue,uG as isGasAsset,rz as isDetected,yG as initializeRPCUrlsWithFallback,Lz as getWalletFormatFor,oG as getTokenLogoURI,wz as getTHORNameCost,qz as getSymmetricWithdraw,o as getSymmetricPoolShare,OG as getRPCUrlSync,vG as getRPCUrl,eG as getMinAmountByChain,Tz as getMemoForWithdraw,Cz as getMemoForUnbond,fz as getMemoForTcyStake,Az as getMemoForTcyClaim,Oz as getMemoForRunePoolWithdraw,Pz as getMemoForRunePoolDeposit,vz as getMemoForNameRegister,yz as getMemoForNamePreferredAssetRegister,Dz as getMemoForLeaveAndBond,Uz as getMemoForDeposit,bz as getMAYANameCost,Mz as getLiquiditySlippage,w as getFeeMultiplierAsBigInt,g as getFeeMultiplier,AG as getExplorerTxUrl,fG as getExplorerAddressUrl,Kz as getEstimatedPoolShare,iz as getETHDefaultWallet,az as getEIP6963Wallets,_z as getDerivationPathFor,dG as getCommonAssetInfo,wG as getChainIdentifier,Iz as getAsymmetricRuneWithdrawAmount,l as getAsymmetricRuneShare,Wz as getAsymmetricAssetWithdrawAmount,r as getAsymmetricAssetShare,pG as getAssetType,nG as formatBigIntToSafeValue,sG as findAssetBy,oz as filterSupportedChains,hG as fetchTokenInfo,u as derivationPathToString,cG as decodeABIString,mG as decodeABIDynamicString,lG as assetFromString,Zz as applyFeeMultiplierToBigInt,$z as applyFeeMultiplier,zz as addEVMWalletNetwork,nz as addAccountsChangedCallback,TG as _rpcCache,qG as WarningCodeEnum,j as WalletOption,E as UTXOPurpose,JJ as TxnType,ZJ as TxnStatus,TJ as TronTransactionSchema,kJ as TransactionSchema,NJ as TransactionDTOSchema,$J as TrackingStatus,VJ as TrackingRequestSchema,XJ as TrackingRequestQuerySchema,EJ as TrackerResponseSchema,HJ as TokenSchema,LJ as TokenDetailsMetadataSchema,wJ as TONTransactionSchema,fJ as TONTransactionMessageSchema,XQ as SwapToResponseSchema,HQ as SwapToRequestSchema,VQ as SwapToAssetSchema,LQ as SwapRouteV2ResponseSchema,R as SwapKitNumber,L as SwapKitError,RQ as SwapKitApi,ZQ as SwapApprovalTransactionSchema,QQ as StellarApprovalTransactionSchema,AJ as StarknetTransactionSchema,S as SKConfig,Bz as SINGLE_WALLET_CHAINS,nJ as RouteQuoteWarningSchema,GJ as RouteQuoteTxType,BQ as RouteQuoteProviderErrorSchema,sJ as RouteQuoteMetadataV2Schema,oJ as RouteQuoteMetadataSchema,lJ as RouteQuoteMetadataAssetSchema,pJ as RouteLegWithoutAddressesSchema,dJ as RouteLegSchema,CG as RequestClient,$Q as QuoteV3ResponseSchema,_Q as QuoteV2ResponseSchema,jQ as QuoteRouteV2Response,aJ as QuoteResponseSchema,iJ as QuoteResponseRouteItem,YJ as QuoteRequestSchema,KG as ProviderName,QJ as ProviderAction,zJ as PriorityLabel,RJ as PriceResponseSchema,FJ as PriceRequestSchema,W as NetworkDerivationPath,MJ as NearSwapResponseSchema,KJ as NearDepositChannelResultSchema,qJ as NearDepositChannelParamsSchema,s as MemoType,gG as LedgerErrorCode,hJ as HyperCoreTypedDataTransactionSchema,uJ as HyperCoreSendAssetTransactionSchema,mJ as HyperCoreSendAssetActionSchema,cJ as HyperCoreEip712TypedDataSchema,bJ as HYPERCORE_USDC_TOKEN_ID,tJ as GasSchema,eJ as GasResponseSchema,SJ as FeesSchema,MG as FeeTypeEnum,A as FeeOption,gJ as EstimatedTimeSchema,WG as ErrorCode,UJ as EVMTransactionSchema,vJ as EVMTransactionDetailsSchema,OJ as EVMTransactionDetailsParamsSchema,Rz as DerivationPath,WJ as DepositChannelResponseSchema,xJ as DepositChannelParamsSchema,f as DEFAULT_FEE_MULTIPLIERS,yJ as CosmosTransactionSchema,bG as CommonAssetStrings,_J as CoinGeckoMetadataSchema,rJ as ChainflipMetadataSchema,IJ as BrokerDepositChannelParamsSchema,iG as BigIntArithmetics,BJ as AssetValueSchema,tG as AssetValue,GQ as ApproveResponseSchema,zQ as ApproveRequestParams,EG as ApproveMode,JQ as ApprovalTransactionSchema,jJ as ApiV2ErrorSchema,m as ACCOUNT_INDEXED_CHAINS};
|
|
@@ -486,6 +486,7 @@ declare const errorCodes: {
|
|
|
486
486
|
readonly toolbox_not_supported: 59901;
|
|
487
487
|
readonly toolbox_fee_estimation_failed: 59902;
|
|
488
488
|
readonly toolbox_sweep_amount_too_low: 59903;
|
|
489
|
+
readonly toolbox_derivation_slot_unsupported: 59904;
|
|
489
490
|
/**
|
|
490
491
|
* NEAR Plugin
|
|
491
492
|
*/
|
|
@@ -1031,6 +1032,7 @@ export declare class SwapKitError extends Error {
|
|
|
1031
1032
|
readonly toolbox_not_supported: 59901;
|
|
1032
1033
|
readonly toolbox_fee_estimation_failed: 59902;
|
|
1033
1034
|
readonly toolbox_sweep_amount_too_low: 59903;
|
|
1035
|
+
readonly toolbox_derivation_slot_unsupported: 59904;
|
|
1034
1036
|
/**
|
|
1035
1037
|
* NEAR Plugin
|
|
1036
1038
|
*/
|
|
@@ -1,3 +1,13 @@
|
|
|
1
1
|
import { type Chain, getChainConfig } from "@swapkit/types";
|
|
2
2
|
export type DerivationPathArray = ReturnType<typeof getChainConfig>["networkDerivationPath"];
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* The process-wide source of truth every derivation reads, so it is frozen twice over: the table
|
|
5
|
+
* itself and each tuple in it.
|
|
6
|
+
*
|
|
7
|
+
* `getChainConfig` hands back the chain config by reference and every EVM chain spreads one shared
|
|
8
|
+
* `networkDerivationPath` object, so a single stray `NetworkDerivationPath[chain][2] = n` would
|
|
9
|
+
* silently re-point every wallet derived afterwards — on every EVM chain at once. Freezing the
|
|
10
|
+
* tuples also freezes `getChainConfig(chain).networkDerivationPath` in `@swapkit/types`, which is
|
|
11
|
+
* intentional: nothing may rewrite a chain's derivation path at runtime.
|
|
12
|
+
*/
|
|
13
|
+
export declare const NetworkDerivationPath: Readonly<Record<Chain, readonly [44, 118, 0, 0, 0] | readonly [44, 931, 0, 0, 0] | readonly [number, number, number, number, number] | readonly [44, 683, 0, 0] | readonly [44, 637, 0, 0, 0] | readonly [44, 60, 0, 0, 0] | readonly [44, 397, 0, 0, 0] | readonly [0, 0, 0, 0, 0] | readonly [44, 144, 0, 0, 0] | readonly [44, 501, 0, 0, 0] | readonly [8797555, 1, 0, 0, 0] | readonly [44, 607, 0, 0, 0] | readonly [44, 195, 0, 0, 0] | readonly [44, 148, 0, 0, 0] | readonly [44, 784, 0, 0, 0] | readonly [1852, 1815, 0, 0, 0] | readonly [44, 9004, 0, 0, 0] | readonly [number, number, number, number, (number | undefined)?] | readonly [44, 145, 0, 0, 0] | readonly [84, 2, 0, 0, 0] | readonly [44, 3, 0, 0, 0] | readonly [44, 5, 0, 0, 0] | readonly [44, 133, 0, 0, 0]>>;
|
|
@@ -1,22 +1,109 @@
|
|
|
1
1
|
import { Chain } from "@swapkit/types";
|
|
2
2
|
import { type DerivationPathArray } from "../types";
|
|
3
|
+
type DerivationType = "legacy" | "ledgerLive" | "nativeSegwitMiddleAccount" | "segwit" | "account";
|
|
3
4
|
type Params = {
|
|
4
5
|
chain: Chain;
|
|
5
6
|
index: number;
|
|
6
7
|
addressIndex?: number;
|
|
7
|
-
type?:
|
|
8
|
+
type?: DerivationType;
|
|
8
9
|
};
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
10
|
+
/**
|
|
11
|
+
* Any derivation path the helpers accept: 3 to 5 slots, read-only so the frozen
|
|
12
|
+
* `NetworkDerivationPath` entries pass straight through.
|
|
13
|
+
*/
|
|
14
|
+
export type ReadonlyDerivationPath = readonly [number, number, number, number?, number?];
|
|
15
|
+
/**
|
|
16
|
+
* The read-only counterpart of `DerivationPathArray`: the 4- and 5-slot shapes only.
|
|
17
|
+
*
|
|
18
|
+
* `updateDerivationPath` addresses slots positionally, so a 3-slot account path has no slot for
|
|
19
|
+
* `change` to land in. Accepting one would mean either fabricating a slot or silently dropping the
|
|
20
|
+
* caller's value; refusing it at the type level is the only answer that cannot mis-derive.
|
|
21
|
+
*/
|
|
22
|
+
export type UpdatableDerivationPath = readonly [number, number, number, number, number?];
|
|
23
|
+
export type DerivationSlots = {
|
|
24
|
+
/** BIP43 purpose, slot 0. UTXO script type: 44 legacy, 49 nested-segwit, 84 native-segwit, 86 taproot. */
|
|
25
|
+
purpose?: number;
|
|
26
|
+
/** BIP44 account', slot 2. */
|
|
27
|
+
account?: number;
|
|
28
|
+
/** BIP44 change, slot 3. 5-slot paths only. */
|
|
29
|
+
change?: number;
|
|
30
|
+
/** Last slot: address_index on a 5-slot path; the 4th hardened slot on the Solana/Aleo 4-slot shape. */
|
|
31
|
+
index?: number;
|
|
32
|
+
};
|
|
33
|
+
interface ResolveDerivationPathParams {
|
|
34
|
+
chain: Chain;
|
|
35
|
+
derivationPath?: DerivationPathArray;
|
|
36
|
+
index?: number;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Returns a copy of `path` with the requested BIP44 slots replaced.
|
|
40
|
+
*
|
|
41
|
+
* Slots that are not passed are left untouched and the path length is preserved, so the
|
|
42
|
+
* 4-slot Solana/Aleo shape (`m/44'/501'/0'/0'`) stays 4 slots. On that 4-slot shape `change` and
|
|
43
|
+
* `index` address the same slot and `index` wins, matching the historical write order.
|
|
44
|
+
*
|
|
45
|
+
* `change` targets slot 3, which is the last slot of a 4-slot path, so it is only independently
|
|
46
|
+
* meaningful on a 5-slot path. 3-slot account paths are not accepted at all — see
|
|
47
|
+
* `UpdatableDerivationPath`.
|
|
48
|
+
*/
|
|
49
|
+
export declare function updateDerivationPath(path: UpdatableDerivationPath, slots: DerivationSlots): DerivationPathArray;
|
|
50
|
+
/** BIP43 purpose values for the UTXO script types. */
|
|
51
|
+
export declare const UTXOPurpose: {
|
|
52
|
+
readonly bech32: 84;
|
|
53
|
+
readonly legacy: 44;
|
|
54
|
+
readonly p2sh: 49;
|
|
55
|
+
readonly taproot: 86;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Chains where a wallet index selects the BIP44 **account** slot rather than the address-index
|
|
59
|
+
* slot. Wallet indexes within one seed map onto `{ account: index }` for these.
|
|
60
|
+
*
|
|
61
|
+
* - **NEAR** and **Stellar** derive at `m/44'/{coin}'/{account}'` and have no change or
|
|
62
|
+
* address-index level below it (SEP-0005 for Stellar); `m/44'/148'/3'` genuinely is wallet 3 in
|
|
63
|
+
* Ledger, Lobstr and Freighter.
|
|
64
|
+
* - **Sui** has all five slots, but the ecosystem enumerates wallets on the account slot: the
|
|
65
|
+
* official wallet specification recommends incrementing `account_index`, and Keystone and Ledger
|
|
66
|
+
* export `m/44'/784'/{n}'/0'/0'`. Using the address slot would mint addresses no other Sui
|
|
67
|
+
* wallet can reproduce from the same seed.
|
|
68
|
+
*
|
|
69
|
+
* Putting a wallet index in the address-index slot for these chains makes their toolboxes throw
|
|
70
|
+
* `toolbox_derivation_slot_unsupported` rather than silently derive a different wallet.
|
|
71
|
+
*/
|
|
72
|
+
export declare const ACCOUNT_INDEXED_CHAINS: readonly Chain[];
|
|
73
|
+
/**
|
|
74
|
+
* Chains that can only ever serve their single default wallet, so no wallet index other than 0 is
|
|
75
|
+
* derivable for them.
|
|
76
|
+
*
|
|
77
|
+
* **TON** has no BIP44 derivation: one mnemonic is exactly one key pair via `mnemonicToWalletKey`,
|
|
78
|
+
* and wallets such as Tonkeeper express "more accounts" as different wallet contract versions or
|
|
79
|
+
* as separate seed phrases, not as derivation-path slots. A wallet index therefore cannot be
|
|
80
|
+
* honoured at all — there is no slot it could select — and the TON toolbox throws
|
|
81
|
+
* `toolbox_derivation_slot_unsupported` rather than returning the default wallet under a different
|
|
82
|
+
* index. Multi-chain connectors can isolate that rejection while connecting supported siblings.
|
|
83
|
+
*/
|
|
84
|
+
export declare const SINGLE_WALLET_CHAINS: readonly Chain[];
|
|
85
|
+
export declare function resolveDerivationPath({ chain, derivationPath, index }: ResolveDerivationPathParams): readonly [44, 118, 0, 0, 0] | readonly [44, 931, 0, 0, 0] | readonly [number, number, number, number, number] | readonly [44, 683, 0, 0] | readonly [44, 637, 0, 0, 0] | readonly [44, 60, 0, 0, 0] | readonly [44, 397, 0, 0, 0] | readonly [0, 0, 0, 0, 0] | readonly [44, 144, 0, 0, 0] | readonly [44, 501, 0, 0, 0] | readonly [8797555, 1, 0, 0, 0] | readonly [44, 607, 0, 0, 0] | readonly [44, 195, 0, 0, 0] | readonly [44, 148, 0, 0, 0] | readonly [44, 784, 0, 0, 0] | readonly [1852, 1815, 0, 0, 0] | readonly [44, 9004, 0, 0, 0] | readonly [number, number, number, number, (number | undefined)?] | readonly [44, 145, 0, 0, 0] | readonly [84, 2, 0, 0, 0] | readonly [44, 3, 0, 0, 0] | readonly [44, 5, 0, 0, 0] | readonly [44, 133, 0, 0, 0];
|
|
86
|
+
export declare function derivationPathToString([network, chainId, account, change, index]: ReadonlyDerivationPath, { allHardened }?: {
|
|
17
87
|
allHardened?: boolean;
|
|
18
88
|
}): string;
|
|
19
|
-
|
|
89
|
+
/**
|
|
90
|
+
* Builds the named hardware-wallet derivation paths.
|
|
91
|
+
*
|
|
92
|
+
* The chain family and the named type are one decision, matched exhaustively so that adding a
|
|
93
|
+
* `type` variant is a compile error rather than a silent fall-through to the default path.
|
|
94
|
+
*
|
|
95
|
+
* - EVM: `ledgerLive` walks the account' slot (`m/44'/60'/{index}'/0/{addressIndex}`) while
|
|
96
|
+
* `legacy`/`account` return the 4-slot legacy MEW/Ledger shape (`m/44'/60'/0'/{index}`).
|
|
97
|
+
* - UTXO: `legacy`, `segwit` (nested P2SH) and `nativeSegwitMiddleAccount` select the BIP43
|
|
98
|
+
* purpose, keeping the chain's own coin type from `NetworkDerivationPath`.
|
|
99
|
+
* - Other default/account paths use the chain's network path, applying the wallet index to the
|
|
100
|
+
* account slot for account-indexed chains and the address slot otherwise.
|
|
101
|
+
*
|
|
102
|
+
* The UTXO-shaped types are not rejected on non-UTXO chains: they rewrite the purpose slot of
|
|
103
|
+
* whatever path the chain declares. That is long-standing behaviour and callers rely on nothing
|
|
104
|
+
* throwing here.
|
|
105
|
+
*/
|
|
106
|
+
export declare function getDerivationPathFor({ chain, index, addressIndex, type }: Params): readonly [44, 118, 0, 0, 0] | readonly [44, 931, 0, 0, 0] | readonly [number, number, number, number, number] | readonly [44, 683, 0, 0] | readonly [44, 637, 0, 0, 0] | readonly [44, 60, 0, 0, 0] | readonly [44, 397, 0, 0, 0] | readonly [0, 0, 0, 0, 0] | readonly [44, 144, 0, 0, 0] | readonly [44, 501, 0, 0, 0] | readonly [8797555, 1, 0, 0, 0] | readonly [44, 607, 0, 0, 0] | readonly [44, 195, 0, 0, 0] | readonly [44, 148, 0, 0, 0] | readonly [44, 784, 0, 0, 0] | readonly [1852, 1815, 0, 0, 0] | readonly [44, 9004, 0, 0, 0] | readonly [number, number, number, number, (number | undefined)?] | readonly [44, 145, 0, 0, 0] | readonly [84, 2, 0, 0, 0] | readonly [44, 3, 0, 0, 0] | readonly [44, 5, 0, 0, 0] | readonly [44, 133, 0, 0, 0] | number[];
|
|
20
107
|
export declare function getWalletFormatFor(path: string): "legacy" | "p2sh" | "bech32";
|
|
21
|
-
export declare const DerivationPath: Record<Chain, string
|
|
108
|
+
export declare const DerivationPath: Readonly<Record<Chain, string>>;
|
|
22
109
|
export {};
|
package/package.json
CHANGED
|
@@ -3,11 +3,11 @@
|
|
|
3
3
|
"dependencies": {
|
|
4
4
|
"@noble/hashes": "2.2.0",
|
|
5
5
|
"@swapkit/contracts": "5.0.0",
|
|
6
|
-
"@swapkit/tokens": "5.0.
|
|
7
|
-
"@swapkit/types": "1.0
|
|
6
|
+
"@swapkit/tokens": "5.0.5",
|
|
7
|
+
"@swapkit/types": "1.1.0"
|
|
8
8
|
},
|
|
9
9
|
"description": "SwapKit - Helpers",
|
|
10
|
-
"devDependencies": { "@swapkit/toolboxes": "5.1
|
|
10
|
+
"devDependencies": { "@swapkit/toolboxes": "5.2.1" },
|
|
11
11
|
"exports": {
|
|
12
12
|
".": { "default": "./dist/index.js", "types": "./dist/types/index.d.ts" },
|
|
13
13
|
"./api": { "default": "./dist/api/index.js", "types": "./dist/types/api/index.d.ts" },
|
|
@@ -30,5 +30,5 @@
|
|
|
30
30
|
"type-check:go": "tsgo"
|
|
31
31
|
},
|
|
32
32
|
"type": "module",
|
|
33
|
-
"version": "5.1
|
|
33
|
+
"version": "5.2.1"
|
|
34
34
|
}
|
package/dist/chunk-sht0fjw7.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
var HT=Object.defineProperty;var PT=(N)=>N;function LT(N,A){this[N]=PT.bind(null,A)}var lN=(N,A)=>{for(var T in A)HT(N,T,{get:A[T],enumerable:!0,configurable:!0,set:LT.bind(A,T)})};var rN=((N)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(N,{get:(A,T)=>(typeof require<"u"?require:A)[T]}):N)(function(N){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+N+'" is not supported')});import{Chain as bN,getChainConfig as AH}from"@swapkit/types";import{AllChains as oT,Chain as b,EVMChains as CT,getChainConfig as RN}from"@swapkit/types";import{match as tN}from"ts-pattern";import{Chain as B,EVMChains as jT,getChainConfig as p,UTXOChains as VT}from"@swapkit/types";import{match as LN}from"ts-pattern";import{AllChains as aN,Chain as eN,getChainConfig as $T,MAYAConfig as YT,StagenetChain as _N,StagenetMAYAConfig as NA,StagenetTHORConfig as AA,THORConfig as MT}from"@swapkit/types";import{createStore as _T}from"zustand/vanilla";import{AllChains as FT,getChainConfig as OT}from"@swapkit/types";var dP=FT.reduce((N,A)=>{return N[A]=OT(A).networkDerivationPath,N},{});var PN;((R)=>{R.unknownError="unknownError";R.test_error="test_error";R.providerDetailsError="providerDetailsError";R.blockHeaderNotFound="blockHeaderNotFound";R.blockHashNotFoundAtHeight="blockHashNotFoundAtHeight";R.blockHashNotFoundAtHash="blockHashNotFoundAtHash";R.txHashMissing="txHashMissing";R.assetValueMissingInfo="assetValueMissingInfo";R.invalidAsset="invalidAsset";R.blockIsRequired="blockIsRequired";R.currentBlockHeaderNotFound="currentBlockHeaderNotFound";R.failedToRetrieveBalance="failedToRetrieveBalance";R.failedToRetrieveBlock="failedToRetrieveBlock";R.failedToRetrieveFees="failedToRetrieveFees";R.notImplementedBCH="notImplementedBCH";R.notImplementedDoge="notImplementedDoge";R.noPoolsFound="noPoolsFound";R.noVaultsFound="noVaultsFound";R.noTxFound="noTxFound";R.noInputCoinFound="noInputCoinFound";R.noBlockDataFound="noBlockDataFound";R.multipleCosmosMessages="multipleCosmosMessages";R.heightOrHashNotProvided="heightOrHashNotProvided";R.unknownDenom="unknownDenom";R.invalidBlockHeight="invalidBlockHeight";R.timestampExtrinsicNoArgumentsForBlock="timestampExtrinsicNoArgumentsForBlock";R.timestampExtrinsicNoTimestampForBlock="timestampExtrinsicNoTimestampForBlock";R.noTimestampExtrinsicForHash="noTimestampExtrinsicForHash";R.timestampExtrinsicNoArgumentsForHash="timestampExtrinsicNoArgumentsForHash";R.txMemoUndefined="txMemoUndefined";R.txMemoIncorrect="txMemoIncorrect";R.txTypeNotFound="txTypeNotFound";R.txNoMessage="txNoMessage";R.txNotFound="txNotFound";R.txReceiptNotFound="txReceiptNotFound";R.txParsingError="txParsingError";R.txLogsParsingError="txLogsParsingError";R.blockNotFound="blockNotFound";R.balanceNotFound="balanceNotFound";R.configError="configError";R.synthSwapDisallowed="synthSwapDisallowed";R.providerQuoteTimeout="providerQuoteTimeout";R.noQuoteResponse="noQuoteResponse";R.noPoolAssetsFound="noPoolAssetsFound";R.noThorchainPools="noThorchainPools";R.noMayachainPools="noMayachainPools";R.noThorchainNetworkInfo="noThorchainNetworkInfo";R.invalidAffiliateFee="invalidAffiliateFee";R.invalidBuyAssetAddress="invalidBuyAssetAddress";R.invalidSellAssetAddress="invalidSellAssetAddress";R.invalidSourceAddress="invalidSourceAddress";R.invalidDestinationAddress="invalidDestinationAddress";R.sourceAddressIsSmartContract="sourceAddressIsSmartContract";R.destinationAddressIsSmartContract="destinationAddressIsSmartContract";R.invalidChainId="invalidChainId";R.unsupportedChainId="unsupportedChainId";R.unsupportedEVMChainId="unsupportedEVMChainId";R.unsupportedMethod="unsupportedMethod";R.unsupportedProvider="unsupportedProvider";R.invalidParamsForMethod="invalidParamsForMethod";R.unsupportedAdapter="unsupportedAdapter";R.noWhitelistTokens="noWhitelistTokens";R.failedFetchGasPrice="failedFetchGasPrice";R.failedToCreateDepositChannel="failedToCreateDepositChannel";R.noProviderDetailsFound="noProviderDetailsFound";R.noTokenListsFound="noTokenListsFound";R.tokenNotFound="tokenNotFound";R.tokenPriceNotFound="tokenPriceNotFound";R.tokenPriceFailedToUpdate="tokenPriceFailedToUpdate";R.swapAmountTooSmall="swapAmountTooSmall";R.legsArrayIsEmpty="legsArrayIsEmpty";R.failedToFetchQuoteForLeg="failedToFetchQuoteForLeg";R.noBlockHeaderFound="noBlockHeaderFound";R.failedToSimulateSwap="failedToSimulateSwap";R.addressScreeningFailed="addressScreeningFailed";R.noLiquidtyProvidersFound="noLiquidtyProvidersFound";R.insufficientLiquidity="insufficientLiquidity";R.noInboundDataFound="noInbounDataFound";R.noInboundAddressesFound="noInboundAddressesFound";R.noInboundAddressFoundForChain="noInboundAddressFoundForChain";R.noLastBlocksFound="noLastBlocksFound";R.noVersionFound="noVersionFound";R.noConstantsFound="noConstantsFound";R.noMimirsFound="noMimirsFound";R.noRoutesFound="noRoutesFound";R.quoteNotFound="quoteNotFound";R.ledgerSignFailed="ledgerSignFailed";R.ledgerWrongPayload="ledgerWrongPayload";R.ledgerFetchSwapFailed="ledgerFetchSwapFailed";R.failedToFetchTx="failedToFetchTx";R.failedBuildTransactionDetails="failedBuildTransactionDetails";R.noLegsForRoute="noLegsForRoute";R.noRouterAddressFound="noRouterAddressFound";R.noAggregatorAddressFound="noAggregatorAddressFound";R.noContractInstanceFound="noContractInstanceFound";R.noContractAddressFound="noContractAddressFound";R.invalidAffiliate="invalidAffiliate";R.thornameAffiliate="thornameAffiliate";R.providerNotfound="No provider found";R.noRecordFound="No Record found";R.slippageTooLow="Slippage too low";R.tradingHalted="tradingHalted";R.noWrappedGasAsset="noWrappedGasAsset";R.aggregatorAddressNotFound="aggregatorAddressNotFound";R.routerAddressNotFound="routerAddressNotFound";R.dummyAddressNotFound="dummyAddressNotFound";R.trackerError="trackerError";R.thorchainPoolUnavailable="thorchainPoolUnavailable";R.noOhlcvDataFound="noOhlcvDataFound";R.noTradingPairs="noTradingPairs";R.noLendingAvailability="noLendingAvailability";R.lendingRepayTooSmall="lendingRepayTooSmall";R.missingState="missingState";R.ledgerSwapNotFound="ledgerSwapNotFound";R.ledgerSwapNotReadyForTracking="ledgerSwapNotReadyForTracking";R.errorEstimatingGas="errorEstimatingGas";R.apiKeyInvalid="apiKeyInvalid";R.apiKeyFailedToUpdate="apiKeyFailedToUpdate";R.apiKeyExpired="apiKeyExpired";R.unauthorized="unauthorized";R.failedToCreateMemo="failedToCreateMemo";R.radixIncorrectInstructions="radixIncorrectInstructions";R.radixTxMissedParam="radixTxMissedParam";R.radixTxMissedAccount="radixTxMissedAccount";R.radixManifestParseError="radixManifestParseError";R.radixManifestBuildError="radixManifestBuildError";R.invalidAddressForChain="invalidAddressForChain";R.riskyAddress="riskyAddress";R.noRoutesToProcess="noRoutesToProcess";R.sellAssetAmountTooSmall="sellAssetAmountTooSmall";R.missingPrivateKey="missingPrivateKey";R.noMemoPriceProtection="noMemoPriceProtection"})(PN||={});var JN;((H)=>{H.highSlippage="highSlippage";H.highPriceImpact="highPriceImpact";H.insufficientBalance="insufficientBalance"})(JN||={});var Z;((n)=>{n.CHAINFLIP="CHAINFLIP";n.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";n.JUPITER="JUPITER";n.MAYACHAIN="MAYACHAIN";n.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";n.ONEINCH="ONEINCH";n.PANCAKESWAP="PANCAKESWAP";n.SUSHISWAP_V2="SUSHISWAP_V2";n.THORCHAIN="THORCHAIN";n.THORCHAIN_STREAMING="THORCHAIN_STREAMING";n.TRADERJOE_V2="TRADERJOE_V2";n.UNISWAP_V2="UNISWAP_V2";n.UNISWAP_V3="UNISWAP_V3";n.NEAR="NEAR";n.GARDEN="GARDEN";n.OKX="OKX";n.HARBOR="HARBOR";n.FLASHNET="FLASHNET";n.MAYAN="MAYAN"})(Z||={});var QN;((M)=>{M.LIQUIDITY="liquidity";M.NETWORK="network";M.INBOUND="inbound";M.OUTBOUND="outbound";M.AFFILIATE="affiliate";M.TAX="tax";M.PRIORITY="priority";M.SERVICE="service"})(QN||={});var RT;((H)=>{H.Average="average";H.Fast="fast";H.Fastest="fastest"})(RT||={});var IT;((T)=>{T.Approve="approve";T.CheckOnly="checkOnly"})(IT||={});var BT;((X)=>{X.NAME_REGISTER="~";X.BOND="BOND";X.DEPOSIT="+";X.LEAVE="LEAVE";X.UNBOND="UNBOND";X.WITHDRAW="-";X.RUNEPOOL_DEPOSIT="POOL+";X.RUNEPOOL_WITHDRAW="POOL-";X.CLAIM_TCY="tcy";X.STAKE_TCY="tcy+";X.UNSTAKE_TCY="tcy-"})(BT||={});var iN={core_estimated_max_spendable_chain_not_supported:10001,core_extend_error:10002,core_inbound_data_not_found:10003,core_approve_asset_address_or_from_not_found:10004,core_plugin_not_found:10005,core_plugin_swap_not_found:10006,core_approve_asset_target_invalid:10007,core_explorer_unsupported_chain:10008,core_verify_message_not_supported:10009,core_chain_halted:10010,core_wallet_connection_not_found:10101,core_wallet_ctrl_not_installed:10102,core_wallet_evmwallet_not_installed:10103,core_wallet_walletconnect_not_installed:10104,core_wallet_keystore_not_installed:10105,core_wallet_ledger_not_installed:10106,core_wallet_trezor_not_installed:10107,core_wallet_keplr_not_installed:10108,core_wallet_okx_not_installed:10109,core_wallet_keepkey_not_installed:10110,core_wallet_talisman_not_installed:10111,core_wallet_not_keypair_wallet:10112,core_wallet_sign_message_not_supported:10113,core_wallet_connection_failed:10114,core_wallet_create_not_supported:10115,core_wallet_sign_typed_data_not_supported:10116,core_swap_invalid_params:10201,core_swap_route_not_complete:10202,core_swap_asset_not_recognized:10203,core_swap_contract_not_found:10204,core_swap_route_transaction_not_found:10205,core_swap_contract_not_supported:10206,core_swap_transaction_error:10207,core_swap_quote_mode_not_supported:10208,core_transaction_deposit_error:10301,core_transaction_create_liquidity_base_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_base_address:10306,core_transaction_add_liquidity_base_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_invalid_sender_address:10313,core_transaction_deposit_server_error:10314,core_transaction_user_rejected:10315,core_transaction_failed:10316,core_transaction_invalid_recipient_address:10317,wallet_connection_rejected_by_user:20001,wallet_missing_api_key:20002,wallet_chain_not_supported:20003,wallet_missing_params:20004,wallet_provider_not_found:20005,wallet_failed_to_add_or_switch_network:20006,wallet_ledger_connection_error:20101,wallet_ledger_connection_claimed:20102,wallet_ledger_get_address_error:20103,wallet_ledger_device_not_found:20104,wallet_ledger_device_locked:20105,wallet_ledger_transport_error:20106,wallet_ledger_public_key_error:20107,wallet_ledger_derivation_path_error:20108,wallet_ledger_signing_error:20109,wallet_ledger_app_not_open:20110,wallet_ledger_invalid_response:20111,wallet_ledger_method_not_supported:20112,wallet_ledger_invalid_params:20113,wallet_ledger_invalid_signature:20114,wallet_ledger_no_provider:20115,wallet_ledger_pubkey_not_found:20116,wallet_ledger_transport_not_defined:20117,wallet_ledger_webusb_not_supported:20118,wallet_ledger_chain_not_supported:20119,wallet_ledger_invalid_asset:20120,wallet_ledger_invalid_account:20121,wallet_ledger_address_not_found:20122,wallet_ledger_failed_to_get_address:20123,wallet_ledger_webhid_not_supported:20124,wallet_phantom_not_found:20201,wallet_ctrl_not_found:20301,wallet_ctrl_send_transaction_no_address:20302,wallet_ctrl_contract_address_not_provided:20303,wallet_ctrl_asset_not_defined:20304,wallet_walletconnect_project_id_not_specified:20401,wallet_walletconnect_connection_not_established:20402,wallet_walletconnect_namespace_not_supported:20403,wallet_walletconnect_chain_not_supported:20404,wallet_walletconnect_invalid_method:20405,wallet_walletconnect_method_not_supported:20406,wallet_trezor_failed_to_sign_transaction:20501,wallet_trezor_derivation_path_not_supported:20502,wallet_trezor_failed_to_get_address:20503,wallet_trezor_transport_error:20504,wallet_trezor_method_not_supported:20505,wallet_trezor_failed_to_get_public_key:20506,wallet_talisman_not_enabled:20601,wallet_talisman_not_found:20602,wallet_polkadot_not_found:20701,wallet_radix_not_found:20801,wallet_radix_transaction_failed:20802,wallet_radix_invalid_manifest:20803,wallet_radix_method_not_supported:20804,wallet_radix_no_account:20805,wallet_keepkey_not_found:20901,wallet_keepkey_asset_not_defined:20902,wallet_keepkey_contract_address_not_provided:20903,wallet_keepkey_send_transaction_no_address:20904,wallet_keepkey_derivation_path_error:20905,wallet_keepkey_signing_error:20906,wallet_keepkey_transport_error:20907,wallet_keepkey_unsupported_chain:20908,wallet_keepkey_invalid_response:20909,wallet_keepkey_chain_not_supported:20910,wallet_keepkey_signer_not_found:20911,wallet_keepkey_no_accounts:20912,wallet_keepkey_method_not_supported:20913,wallet_keepkey_invalid_params:20914,wallet_keepkey_config_not_found:20915,wallet_keepkey_no_provider:20916,wallet_keepkey_account_not_found:20917,wallet_keepkey_failed_to_get_public_key:20918,wallet_bitkeep_not_found:21001,wallet_bitkeep_failed_to_switch_network:21002,wallet_bitkeep_no_accounts:21003,wallet_passkeys_sign_transaction_error:21101,wallet_passkeys_not_found:21102,wallet_passkeys_no_address:21103,wallet_passkeys_request_canceled:21104,wallet_passkeys_signature_canceled:21105,wallet_passkeys_failed_to_switch_network:21106,wallet_passkeys_chain_not_supported:21107,wallet_passkeys_instance_missing:21108,wallet_onekey_not_found:21201,wallet_onekey_sign_transaction_error:21202,wallet_okx_not_found:21301,wallet_okx_chain_not_supported:21302,wallet_okx_failed_to_switch_network:21303,wallet_okx_no_accounts:21304,wallet_keplr_not_found:21401,wallet_keplr_chain_not_supported:21402,wallet_keplr_signer_not_found:21403,wallet_keplr_no_accounts:21404,wallet_cosmostation_not_found:21501,wallet_cosmostation_chain_not_supported:21502,wallet_cosmostation_evm_provider_not_found:21503,wallet_cosmostation_keplr_provider_not_found:21504,wallet_cosmostation_no_accounts:21505,wallet_cosmostation_no_evm_accounts:21506,wallet_cosmostation_no_evm_address:21507,wallet_cosmostation_signer_not_found:21508,wallet_passkey_not_supported:21601,wallet_passkey_connection_failed:21602,wallet_coinbase_not_found:21701,wallet_coinbase_chain_not_supported:21702,wallet_coinbase_method_not_supported:21703,wallet_coinbase_no_accounts:21704,wallet_evm_extensions_failed_to_switch_network:21801,wallet_evm_extensions_no_provider:21802,wallet_evm_extensions_not_found:21803,wallet_keystore_invalid_password:21901,wallet_keystore_unsupported_version:21902,wallet_near_extensions_failed_to_switch_network:22001,wallet_near_extensions_no_provider:22002,wallet_near_extensions_not_found:22003,wallet_near_method_not_supported:22004,wallet_petra_not_found:22201,wallet_vultisig_not_found:22101,wallet_vultisig_contract_address_not_provided:22102,wallet_vultisig_asset_not_defined:22103,wallet_vultisig_send_transaction_no_address:22104,wallet_xaman_not_configured:23001,wallet_xaman_not_connected:23002,wallet_xaman_auth_failed:23003,wallet_xaman_connection_failed:23004,wallet_xaman_transaction_failed:23005,wallet_xaman_monitoring_failed:23006,wallet_tronlink_request_accounts_failed:24001,wallet_tronlink_locked:24002,chainflip_channel_error:30001,chainflip_unknown_asset:30002,chainflip_broker_invalid_params:30101,chainflip_broker_recipient_error:30102,chainflip_broker_register:30103,chainflip_broker_tx_error:30104,chainflip_broker_withdraw:30105,chainflip_broker_fund_only_flip_supported:30106,chainflip_broker_fund_invalid_address:30107,thorchain_chain_halted:40001,thorchain_trading_halted:40002,thorchain_asset_is_not_tcy:40003,thorchain_swapin_router_required:40101,thorchain_swapin_vault_required:40102,thorchain_swapin_memo_required:40103,thorchain_swapin_token_required:40104,thorchain_preferred_asset_payout_required:40105,toolbox_cosmos_account_not_found:50101,toolbox_cosmos_invalid_fee:50102,toolbox_cosmos_invalid_params:50103,toolbox_cosmos_no_signer:50104,toolbox_cosmos_not_supported:50105,toolbox_cosmos_signer_not_defined:50106,toolbox_cosmos_validate_address_prefix_not_found:50107,toolbox_cosmos_verify_signature_no_pubkey:50108,toolbox_evm_error_estimating_gas_limit:50201,toolbox_evm_error_sending_transaction:50202,toolbox_evm_gas_estimation_error:50203,toolbox_evm_invalid_gas_asset_address:50204,toolbox_evm_invalid_params:50205,toolbox_evm_invalid_transaction:50206,toolbox_evm_no_abi_fragment:50207,toolbox_evm_no_contract_address:50208,toolbox_evm_no_fee_data:50209,toolbox_evm_no_from_address:50210,toolbox_evm_no_gas_price:50211,toolbox_evm_no_signer_address:50212,toolbox_evm_no_signer:50213,toolbox_evm_no_to_address:50214,toolbox_evm_not_supported:50215,toolbox_evm_provider_not_eip1193_compatible:50216,toolbox_evm_invalid_eip7702_authorization:50217,toolbox_utxo_api_error:50301,toolbox_utxo_broadcast_failed:50302,toolbox_utxo_insufficient_balance:50303,toolbox_utxo_invalid_address:50304,toolbox_utxo_invalid_params:50305,toolbox_utxo_invalid_transaction:50306,toolbox_utxo_no_signer:50307,toolbox_utxo_not_supported:50308,toolbox_utxo_tx_not_found:50309,toolbox_utxo_rbf_not_supported:50310,toolbox_utxo_tx_not_replaceable:50311,toolbox_utxo_tx_already_confirmed:50312,toolbox_utxo_rbf_fee_too_low:50313,toolbox_utxo_rbf_insufficient_change:50314,toolbox_solana_no_signer:50401,toolbox_substrate_not_supported:50501,toolbox_substrate_transfer_error:50502,toolbox_radix_method_not_supported:50601,toolbox_ripple_get_balance_error:50701,toolbox_ripple_rpc_not_configured:50702,toolbox_ripple_signer_not_found:50703,toolbox_ripple_asset_not_supported:50704,toolbox_ripple_broadcast_error:50705,toolbox_ripple_get_trust_lines_error:50706,toolbox_ripple_invalid_trust_line_limit:50707,toolbox_tron_no_signer:50801,toolbox_tron_invalid_token_identifier:50802,toolbox_tron_token_transfer_failed:50803,toolbox_tron_transaction_creation_failed:50804,toolbox_tron_trongrid_api_error:50805,toolbox_tron_approve_failed:50806,toolbox_tron_invalid_token_contract:50807,toolbox_tron_allowance_check_failed:50808,toolbox_tron_invalid_transaction_integrity:50809,toolbox_tron_broadcast_failed:50810,toolbox_hypercore_no_signer:51001,toolbox_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,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 ZN(N){return JSON.stringify(N,(A,T)=>typeof T==="bigint"?T.toString():T)}class u extends Error{static ErrorCode=iN;errorKey;info;constructor(N,A){let T=typeof N==="string",H=T?N:N.errorKey,P=T?void 0:N.info,O=`${H}${P?`: ${ZN(P)}`:""}`;super(O);if(Object.setPrototypeOf(this,u.prototype),this.name="SwapKitError",this.errorKey=H,this.info=P,this.cause=A,A){let I=A instanceof Error?`${A.message}${A.cause?` (${A.cause})`:""}`:ZN(A);console.error(`SwapKitError [${H}]: ${I}`)}else if(P)console.error(`SwapKitError [${H}]: ${ZN(P)}`)}}function iP(N){let A=iN;for(let[T,H]of Object.entries(N)){if(Object.hasOwn(A,T)){if(A[T]===H)continue;throw new u({errorKey:"helpers_invalid_params",info:{code:H,existingCode:A[T],key:T}})}let P=Object.keys(A).find((O)=>A[O]===H);if(P)throw new u({errorKey:"helpers_invalid_params",info:{code:H,existingKey:P,key:T}});A[T]=H}}var MN={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"},jN=new Set;function sN(N){return jN.add(N),()=>jN.delete(N)}function aP(N,A){let T=MN;if(Object.hasOwn(T,N)){if(T[N]===A)return;throw new u({errorKey:"helpers_invalid_params",info:{existingValue:T[N],key:N,value:A}})}T[N]=A;for(let H of jN)H(A)}var GT;((H)=>{H[H.NoError=36864]="NoError";H[H.LockedDevice=21781]="LockedDevice";H[H.TC_NotFound=65535]="TC_NotFound"})(GT||={});var DT=aN.reduce((N,A)=>{if(!N.THOR_STAGENET)N[_N.Maya]=NA.rpcUrls,N[_N.THORChain]=AA.rpcUrls;return N[A]=$T(A).rpcUrls,N},{}),ST={[eN.THORChain]:MT.nodeUrl,[eN.Maya]:YT.nodeUrl,[_N.THORChain]:AA.nodeUrl,[_N.Maya]:NA.nodeUrl},TA={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:aN,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:DT,thornodeUrls:ST,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(MN),widgetId:"",widgetKey:""},j=_T((N)=>({...TA,setApiKey:(A,T)=>N((H)=>({apiKeys:{...H.apiKeys,[A]:T}})),setConfig:(A)=>N((T)=>({apiKeys:{...T.apiKeys,...A?.apiKeys},chains:T.chains.concat(A?.chains||[]),endpoints:{...T.endpoints,...A?.endpoints},envs:{...T.envs,...A?.envs},feeMultipliers:A?.feeMultipliers||T.feeMultipliers,integrations:{...T.integrations,...A?.integrations},localMode:{...T.localMode,...A?.localMode},rpcUrls:{...T.rpcUrls,...A?.rpcUrls},thornodeUrls:{...T.thornodeUrls,...A?.thornodeUrls},v3SwapFlow:{...T.v3SwapFlow,...A?.v3SwapFlow},wallets:T.wallets.concat(A?.wallets||[]),widgetId:A?.widgetId||T.widgetId,widgetKey:A?.widgetKey||T.widgetKey})),setEndpoint:(A,T)=>N((H)=>({endpoints:{...H.endpoints,[A]:T}})),setEnv:(A,T)=>N((H)=>({envs:{...H.envs,[A]:T}})),setFeeMultipliers:(A)=>N(()=>({feeMultipliers:A})),setIntegrationConfig:(A,T)=>N((H)=>({integrations:{...H.integrations,[A]:T}})),setRequestOptions:(A)=>N((T)=>({requestOptions:{retry:{...T.requestOptions.retry,...A.retry},timeoutMs:A.timeoutMs||T.requestOptions.timeoutMs}})),setRpcUrl:(A,T)=>N((H)=>({rpcUrls:{...H.rpcUrls,[A]:T}})),setThornodeUrl:(A,T)=>N((H)=>({thornodeUrls:{...H.thornodeUrls,[A]:T}})),setWidgetId:(A)=>N({widgetId:A}),setWidgetKey:(A)=>N({widgetKey:A})}));sN((N)=>{j.setState((A)=>A.wallets.includes(N)?A:{wallets:[...A.wallets,N]})});var g={get:(N)=>j.getState()[N],getState:j.getState,reinitialize:()=>j.setState({...TA,wallets:Object.values(MN)}),set:(N)=>j.getState().setConfig(N),setApiKey:(N,A)=>j.getState().setApiKey(N,A),setEndpoint:(N,A)=>j.getState().setEndpoint(N,A),setEnv:(N,A)=>j.getState().setEnv(N,A),setFeeMultipliers:(N)=>j.getState().setFeeMultipliers(N),setIntegrationConfig:(N,A)=>j.getState().setIntegrationConfig(N,A),setRequestOptions:(N)=>j.getState().setRequestOptions(N),setRpcUrl:(N,A)=>j.getState().setRpcUrl(N,A),setThornodeUrl:(N,A)=>j.getState().setThornodeUrl(N,A),setWidgetId:(N)=>j.getState().setWidgetId(N),setWidgetKey:(N)=>j.getState().setWidgetKey(N)};var uT=(N)=>new Promise((A)=>setTimeout(A,N)),UT=(N,{baseDelay:A,backoffMultiplier:T,maxDelay:H})=>Math.min(A*T**N,H);function XT(N,A){if(N instanceof Error&&N.name==="AbortError")return!0;if(N instanceof TypeError)return!0;if(A===429)return!0;if(A&&A>=500&&A<600)return!0;return!1}var gT=async(N,A)=>{let T=await fetch(N,A),H;try{H=await T.json()}catch{if(!T.ok)throw new u({errorKey:"helpers_invalid_response",info:{status:T.status,statusText:T.statusText}},{status:T.status,statusText:T.statusText});return{}}if(!T.ok){let O={data:H?.data,error:H?.error,message:H?.message,status:T.status};throw new u({errorKey:H?.error||"helpers_invalid_response",info:O},O)}let P=H?.routes?.length||H?.result||H?.data&&!H?.error;if(H?.error&&!P){let O={data:H.data,error:H.error,message:H.message,status:T.status};throw new u({errorKey:H.error,info:O},O)}if(H?.providerErrors?.length||H?.error&&P)console.warn("[SwapKit] Partial errors in response:",H.providerErrors||H.error);return H};function DN(N,A={}){return async function(H,P={}){let{searchParams:O,json:I,body:$,headers:M,dynamicHeader:w,retry:U,timeoutMs:X,abortController:Q,onError:E,onSuccess:t,responseHandler:z,...J}={...A,...P},TN=g.get("requestOptions"),h={...TN.retry,...U},n=!!I||H.endsWith(".json"),$N=ET(H,O),hN=w?await w():{},HN=WT(n,{...M,...hN}),d=n?JSON.stringify(I):$,zN;for(let YN=0;YN<=h.maxRetries;YN++){let dN=Q||new AbortController,cN=setTimeout(()=>dN.abort(),X||TN.timeoutMs);try{let k=await gT($N,{...J,body:d,headers:HN,method:N,signal:dN.signal});return clearTimeout(cN),t?.(k)||z?.(k)||k}catch(k){clearTimeout(cN),zN=k;let TT=k?.cause?.status;if(YN>=h.maxRetries||!XT(k,TT))return E?E(k):Promise.reject(k);await uT(UT(YN,h))}}return E?E(zN):Promise.reject(zN)}}function WT(N,A){return{...A,...N&&{"Content-Type":"application/json"}}}function ET(N,A){let T=new URL(N);if(A)T.search=new URLSearchParams(A).toString();return T.toString()}var _={extend:(N)=>({extend:(A)=>_.extend({...N,...A}),get:DN("GET",N),post:DN("POST",N)}),get:DN("GET"),post:DN("POST")};async function HA(N,A,T,H){let P=`${A}:${T}:${H}`,O=new TextEncoder,I=await crypto.subtle.importKey("raw",O.encode(N),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),$=await crypto.subtle.sign("HMAC",I,O.encode(P));return Array.from(new Uint8Array($)).map((M)=>M.toString(16).padStart(2,"0")).join("")}import{Chain as S,CosmosChains as OA,EVMChains as RA,getChainConfig as IA,StagenetChains as bT,SubstrateChains as nT,UTXOChains as BA}from"@swapkit/types";import{match as SN}from"ts-pattern";function _L(N,A){try{return N()}catch(T){if(A)throw new u(A,T);return}}var PA=new Set;function c({condition:N,id:A,warning:T}){if(N){if(PA.has(A))return;console.warn(T),PA.add(A)}}function wT(N){return SN(N).with(...RA,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...BA,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...OA,...bT,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(S.Polkadot,S.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(S.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(S.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(S.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(S.Aleo,S.Aptos,S.Tron,S.Radix,S.Stellar,()=>"").with(S.Hype,()=>({type:"meta"})).with(S.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(S.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(S.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new u("helpers_chain_not_supported",{chain:N})})}function LA(N){return SN(N).with(S.Aptos,()=>"/-/healthy").with(S.Aleo,()=>"/mainnet/block/height/latest").with(S.Hype,()=>"/info").with(S.Radix,()=>"/status/network-configuration").with(S.Stellar,()=>"").with(S.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function FA(N,A){try{let T=A.startsWith("wss")?A.replace("wss","https"):A;if(N===S.Aleo||N===S.Stellar)return(await fetch(`${T}${LA(N)}`,{cache:"no-store",method:"GET",signal:AbortSignal.timeout(3000)})).ok;return(await fetch(`${T}${LA(N)}`,{body:JSON.stringify(wT(N)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var VN=new Map,zT=120000;function JT(N){let[A=""]=g.get("rpcUrls")[N];if(!A)throw c({condition:!0,id:"helpers_chain_no_public_or_set_rpc_url",warning:`No public or set RPC URL found for chain. Please ensure you configured rpcUrls for ${N}.`}),new u("helpers_chain_no_public_or_set_rpc_url",{chain:N});let T=VN.get(N);if(T&&Date.now()-T.timestamp<zT)return T.url;return VN.set(N,{timestamp:Date.now(),url:A}),A}async function l(N){let A=JT(N),[,...T]=g.get("rpcUrls")[N];if(await FA(N,A))return A;for(let P of T)if(await FA(N,P))return VN.set(N,{timestamp:Date.now(),url:P}),P;throw new u("helpers_chain_rpc_connection_failed",{chain:N,fallbackUrls:T,primaryRpcUrl:A})}function WL(N){c({condition:!0,id:"initializeRPCUrlsWithFallback",warning:"initializeRPCUrlsWithFallback is deprecated. Use static { rpcUrls, fallbackRpcUrls } SwapKit init config or dynamic SKConfig.setRpcUrl/setFallbackRpcUrl to configure RPC endpoints."})}function EL({chain:N,txHash:A}){let{explorerUrl:T}=IA(N);return SN(N).with(...OA,S.Solana,()=>`${T}/tx/${A.startsWith("0x")?A.slice(2):A}`).with(...RA,...nT,()=>`${T}/tx/${A.startsWith("0x")?A:`0x${A}`}`).with(...BA,S.Radix,S.Tron,()=>`${T}/transaction/${A.toLowerCase()}`).with(S.Near,()=>`${T}/txns/${A}`).with(S.Ripple,()=>`${T}/transactions/${A}`).with(S.Stellar,()=>`${T}/explorer/public/tx/${A}`).with(S.Sui,()=>`${T}/txblock/${A}`).with(S.Cardano,S.Hype,S.Spark,S.Ton,()=>`${T}/tx/${A}`).otherwise(()=>"")}function bL({chain:N,address:A}){let{explorerUrl:T}=IA(N);return SN(N).with(S.Solana,S.Sui,S.Radix,()=>`${T}/account/${A}`).with(S.Stellar,()=>`${T}/explorer/public/account/${A}`).otherwise(()=>`${T}/address/${A}`)}function nL(N){switch(N){case S.THORChain:return`${N}.RUNE`;case S.Cosmos:return`${N}.ATOM`;case S.BinanceSmartChain:return`${N}`;default:return`${N}.${N}`}}import{keccak_256 as QT}from"@noble/hashes/sha3.js";import{bytesToHex as ZT}from"@noble/hashes/utils.js";var GA=/^(0x)?[0-9a-fA-F]{40}$/;function uN(N){if(typeof N!=="string"||!GA.test(N))throw Error(`invalid address: ${N}`);let A=N.toLowerCase().replace(/^0x/,""),T=ZT(QT(new TextEncoder().encode(A))),H=[...A].map((O,I)=>Number.parseInt(T[I]??"0",16)>=8?O.toUpperCase():O).join(""),P=N.replace(/^0x/,"");if(/[A-F]/.test(P)&&/[a-f]/.test(P)&&P!==H)throw Error(`bad address checksum: ${N}`);return`0x${H}`}function $A(N){if(typeof N!=="string"||!GA.test(N))return!1;try{return uN(N),!0}catch{return!1}}var tL=[`${B.Maya}.MAYA`,`${B.Maya}.CACAO`,`${B.Ethereum}.THOR`,`${B.Ethereum}.vTHOR`,`${B.Kujira}.USK`,`${B.Ethereum}.FLIP`,`${B.Radix}.XRD`],_A=[B.Arbitrum,B.Aurora,B.Base,B.Ethereum,B.Optimism,B.Robinhood];async function xT(N){let{baseDecimal:A}=p(B.Radix);try{let T=await l(B.Radix),{manager:H}=await _.post(`${T}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:N}),headers:{Accept:"*/*","Content-Type":"application/json"}});return H?.divisibility?.value?.divisibility}catch(T){let H=T instanceof Error?T.message:String(T);return console.warn(`Failed to fetch Radix asset decimals for ${N}: ${H}`),A}}async function qT(N){try{let A=await l(B.Radix);return(await _.post(`${A}/state/entity/details`,{body:JSON.stringify({addresses:[N],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((P)=>P.key==="symbol")?.value.typed.value||void 0}catch(A){let T=A instanceof Error?A.message:String(A);return console.warn(`Failed to fetch Radix asset symbol for ${N}: ${T}`),""}}async function DA({chain:N,address:A,methodHex:T,id:H}){let P=await l(N);return _.post(P,{body:JSON.stringify({id:H,jsonrpc:"2.0",method:"eth_call",params:[{data:T,to:A.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}function vT(N){if(!N||N==="0x")return"UNKNOWN";try{return SA(N.replace(/^0x/,""))?.trim()||"UNKNOWN"}catch(A){return console.warn(`Failed to decode ABI string from ${N}: ${A}`),"UNKNOWN"}}function tT(N,A){if(!N||N==="0x")return A;try{return Number(N)}catch(T){return console.warn(`Failed to decode ABI uint8 from ${N}: ${T}`),A}}async function KT({chain:N,address:A}){let{baseDecimal:T}=p(N),H=A.toLowerCase();if(A===""||!H.startsWith("0x"))return T;let P=await DA({address:A,chain:N,id:2,methodHex:"0x313ce567"}).catch((I)=>{return console.warn(`Could not fetch decimals for ${A} on ${N}: ${I.message}`),{result:""}});return tT(P.result,T)}async function kT({chain:N,address:A}){let T=A.toLowerCase();if(T===""||!T.startsWith("0x"))return;let H=await DA({address:A,chain:N,id:1,methodHex:"0x95d89b41"}).catch((O)=>{return console.warn(`Could not fetch symbol for ${A} on ${N}: ${O.message}`),{result:""}});return vT(H.result)}async function YA({rpcUrl:N,contractAddress:A,functionSelector:T}){return(await _.post(`${N}/wallet/triggerconstantcontract`,{body:JSON.stringify({contract_address:A,function_selector:T,owner_address:A,parameter:"",visible:!0}),headers:{accept:"application/json","content-type":"application/json"}}).catch(()=>{return}))?.constant_result?.[0]}function MA(N){let A=N.match(/.{2}/g)?.map((T)=>Number.parseInt(T,16))??[];return new TextDecoder().decode(new Uint8Array(A))}function SA(N){return LN(N).with(void 0,()=>{return}).when((A)=>A.length>=128,(A)=>{let T=Number.parseInt(A.slice(64,128),16),H=A.slice(128,128+T*2).replace(/(00)+$/,"");return H?MA(H):void 0}).when((A)=>A.length===64,(A)=>{let T=A.replace(/(00)+$/,"");if(T.length>0&&T.length%2===0)return MA(T);return}).otherwise(()=>{return})}function uA({chain:N,address:A}){let{baseDecimal:T}=p(N),H={decimals:T,ticker:void 0};return LN(N).with(...jT,async()=>{try{if(!$A(A.replace(/^0X/,"0x")))return H;let[P,O]=await Promise.all([kT({address:A,chain:N}),KT({address:A,chain:N})]);return{decimals:O,ticker:P}}catch(P){return console.warn(`Failed to fetch token info for ${A} on ${N}: ${P?.code} ${P?.message}`),H}}).with(B.Solana,async()=>{if(!A)return H;try{let P=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${A}`);if(P.ok){let O=await P.json(),I=Array.isArray(O)?O[0]:O;if(I)return{decimals:I.decimals??T,ticker:I.symbol||void 0}}}catch(P){console.warn(`Failed to fetch Solana token info for ${A}: ${P?.code} ${P?.message}`)}return H}).with(B.Tron,async()=>{if(!A)return H;try{let P=await l(B.Tron),[O,I]=await Promise.all([YA({contractAddress:A,functionSelector:"symbol()",rpcUrl:P}),YA({contractAddress:A,functionSelector:"decimals()",rpcUrl:P})]),$=SA(O);return{decimals:O!==void 0&&I?Number(BigInt(`0x${I}`)):T,ticker:$}}catch(P){let O=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Tron token info for ${A}: ${O}`),H}}).with(B.Near,async()=>{if(!A)return H;try{let P=await l(B.Near),O=await _.post(P,{body:JSON.stringify({id:"dontcare",jsonrpc:"2.0",method:"query",params:{account_id:A,args_base64:"e30=",finality:"final",method_name:"ft_metadata",request_type:"call_function"}}),headers:{accept:"application/json","content-type":"application/json"}});if(!O.result?.result)throw Error("NEAR ft_metadata returned no result");let I=JSON.parse(new TextDecoder().decode(new Uint8Array(O.result.result)));return{decimals:I?.decimals||T,ticker:I?.symbol}}catch(P){let O=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Near token info for ${A}: ${O}`),H}}).with(B.Radix,async()=>{if(!A)return H;try{let[P,O]=await Promise.all([qT(A),xT(A)]);return{decimals:O,ticker:P}}catch(P){let O=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Radix token info for ${A}: ${O}`),H}}).otherwise(async()=>H)}function UA({chain:N,symbol:A}){return LN(N).with(..._A,()=>A==="ETH").with(B.Avalanche,()=>A==="AVAX").with(B.Berachain,()=>A==="BERA").with(B.Hyperevm,()=>A==="HYPE").with(B.Hype,()=>A==="HYPE").with(B.Spark,()=>A==="BTC").with(B.BinanceSmartChain,()=>A==="BNB").with(B.Gnosis,()=>A==="xDAI"||A==="XDAI").with(B.Monad,()=>A==="MON").with(B.XLayer,()=>A==="OKB").with(B.Maya,()=>A==="CACAO").with(B.Cosmos,()=>A==="ATOM").with(B.THORChain,()=>A==="RUNE").with(B.Tron,()=>A==="TRX").with(B.Ripple,()=>A==="XRP").with(B.Radix,()=>`${N}.${A}`===UN(N).identifier).otherwise(()=>A===N)}var UN=(N)=>{let{baseDecimal:A}=p(N);return LN(N.toUpperCase()).with(..._A,(H)=>({decimal:A,identifier:`${H}.ETH`})).with(B.THORChain,(H)=>({decimal:A,identifier:`${H}.RUNE`})).with(B.Cosmos,(H)=>({decimal:A,identifier:`${H}.ATOM`})).with(B.Maya,(H)=>({decimal:10,identifier:`${H}.CACAO`})).with(B.BinanceSmartChain,(H)=>({decimal:A,identifier:`${H}.BNB`})).with(B.Monad,(H)=>({decimal:A,identifier:`${H}.MON`})).with(B.Avalanche,(H)=>({decimal:A,identifier:`${H}.AVAX`})).with(B.Gnosis,(H)=>({decimal:A,identifier:`${H}.xDAI`})).with(B.XLayer,(H)=>({decimal:A,identifier:`${H}.OKB`})).with(B.Berachain,(H)=>({decimal:A,identifier:`${H}.BERA`})).with(B.Hyperevm,(H)=>({decimal:A,identifier:`${H}.HYPE`})).with(B.Hype,(H)=>({decimal:A,identifier:`${H}.HYPE`})).with(B.Spark,(H)=>({decimal:A,identifier:`${H}.BTC`})).with(B.Tron,(H)=>({decimal:A,identifier:`${H}.TRX`})).with(B.Solana,B.Chainflip,B.Kujira,B.Ripple,B.Polkadot,B.Near,...VT,(H)=>({decimal:A,identifier:`${H}.${H}`})).with(B.Radix,"XRD.XRD",()=>({decimal:A,identifier:"XRD.XRD"})).with(B.Polygon,"POL.POL",()=>({decimal:A,identifier:"POL.POL"})).with("KUJI.USK",(H)=>({decimal:6,identifier:H})).with("ETH.FLIP",()=>({decimal:p(B.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:p(B.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:p(B.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(H)=>({decimal:10,identifier:H})).with("MAYA.MAYA",(H)=>({decimal:4,identifier:H})).otherwise(()=>({decimal:A,identifier:N}))};function xN({chain:N,symbol:A}){if(A.includes("/"))return"Synth";if(A.includes("~"))return"Trade";return LN(N).with(B.Radix,()=>A===B.Radix||`${N}.${A}`===UN(N).identifier).with(B.Arbitrum,B.Optimism,B.Base,B.Aurora,B.Robinhood,()=>A===B.Ethereum).with(B.Cosmos,()=>A==="ATOM").with(B.BinanceSmartChain,()=>A==="BNB").with(B.Maya,()=>A==="CACAO").with(B.Monad,()=>A==="MON").with(B.THORChain,()=>A==="RUNE").with(B.Tron,()=>A==="TRX").with(B.Hyperevm,()=>A==="HYPE").with(B.Hype,()=>A==="HYPE").with(B.Spark,()=>A==="BTC").with(B.XLayer,()=>A==="OKB").otherwise(()=>A===N)?"Native":N}var y=(N)=>{let[A,...T]=N.split("."),H=N.includes("/"),P=T.join("."),O=P?.split("-"),I=O?.length?O.length===1?O[0]:O.slice(0,-1).join("-"):void 0;return{chain:A,symbol:P,synth:H,ticker:I}};function FN(N,A){let H=A===B.Near?N.indexOf("-"):N.lastIndexOf("-");if(H===-1)return{address:void 0,ticker:N};return{address:N.slice(H+1),ticker:N.slice(0,H)}}function KL(N){return`https://storage.googleapis.com/token-list-swapkit-dev/images/${N.toLowerCase()}.png`}async function kL(N){let{loadTokenLists:A}=await import("./tokens.js"),T=await A(void 0,{source:g.get("envs").isDev?"dev":"prod"}),H=Object.values(T).flatMap((O)=>O.tokens);if("identifier"in N)return H.find((O)=>O.identifier===N.identifier)?.identifier;let P=N.contract.toLowerCase();for(let O of H){let{chain:I,symbol:$}=y(O.identifier);if(I!==N.chain)continue;let{address:M}=FN($,I);if(M?.toLowerCase()===P)return O.identifier}return}import{match as XN}from"ts-pattern";var r=8,mT=10,fT=64;function C({value:N,bigIntDecimal:A=r,decimal:T=r}){if(T===0)return N.toString();let H=N<0n,P=N.toString().substring(H?1:0),O=T-(P.length-1);if(O>0)P="0".repeat(O)+P;let I=P.length-T,$=P.slice(-T);if(Number.parseInt($[A]||"0",10)>=5){let w=Number.parseInt($[A-1]||"0",10);$=`${$.substring(0,A-1)}${w+1}`}else $=$.substring(0,A);return`${H?"-":""}${P.slice(0,I)}.${$}`.replace(/\.?0*$/,"")}class m{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(N,A){return new m({decimal:A,value:C({bigIntDecimal:A,decimal:A,value:N})})}static shiftDecimals({value:N,from:A,to:T}){return m.fromBigInt(N.getBaseValue("bigint")*o(T)/o(A),T)}constructor(N){let A=qN(N),T=typeof N==="object";this.decimal=T?N.decimal:void 0,this.decimalMultiplier=T&&"decimalMultiplier"in N?N.decimalMultiplier:o(Math.max(XA(gN(A)),this.decimal||0)),this.#P(A)}set(N){return new this.constructor({decimal:this.decimal,identifier:this.toString?.({includeSynthProtocol:!0}),value:N})}add(...N){return this.#A("add",...N)}sub(...N){return this.#A("sub",...N)}mul(...N){return this.#A("mul",...N)}div(...N){return this.#A("div",...N)}gt(N){return this.#N("gt",N)}gte(N){return this.#N("gte",N)}lt(N){return this.#N("lt",N)}lte(N){return this.#N("lte",N)}eqValue(N){return this.#N("eqValue",N)}getValue(N,A){let T=ON(this.decimalMultiplier),H=A!==void 0?A:this.decimal,P=H!==void 0?H:T;if(H!==void 0&&H<T){if(this.formatBigIntToSafeValue(this.bigIntValue,H)==="0"&&this.bigIntValue!==0n)P=T}let O=this.formatBigIntToSafeValue(this.bigIntValue,P);return XN(N).with("number",()=>Number(O)).with("string",()=>O).with("bigint",()=>{return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}).otherwise(()=>O)}getBaseValue(N,A){let T=this.decimalMultiplier/o(A||this.decimal||r),H=yT(this.bigIntValue,T);return XN(N).with("number",()=>Number(H)).with("string",()=>H.toString()).otherwise(()=>H)}getBigIntValue(N,A){if(!A&&typeof N==="object")return N.bigIntValue;let T=qN(N),H=gN(T);if(H==="0"||H==="undefined")return 0n;return this.#H(H,A)}toSignificant(N=6){let A=this.getValue("string"),[T="",H=""]=A.split("."),P=Number.parseInt(T,10)>0;if((P?T.length+H.length:H.length)<=N)return A;if(T.length>=N)return T.slice(0,N).padEnd(T.length,"0");if(P)return`${T}.${H.slice(0,N-T.length)}`;let I=H.replace(/^0+/,"")||"0",$=I.slice(0,N),M=H.length-I.length;return`0.${$.padStart(M+$.length,"0")}`}toFixed(N=6){let A=this.getValue("string"),T=A.startsWith("-"),[H="0",P=""]=(T?A.slice(1):A).split("."),O=H==="0"&&Number.parseInt(P.slice(0,N),10)===0,I=T&&!O?"-":"";if(N===0){if(H==="0"&&!P)return"0";return P&&Number.parseInt(P[0]||"0",10)>=5?`${I}${BigInt(H)+1n}.0`:`${I}${H}.0`}if(!P)return`${I}${H}.${"0".repeat(N)}`;let $=P[N];if(!($&&Number.parseInt($,10)>=5))return`${I}${H}.${P.slice(0,N).padEnd(N,"0")}`;let w=BigInt(P.slice(0,N).padEnd(N,"0"))+1n,U=10n**BigInt(N);if(w>=U)return`${I}${BigInt(H)+1n}.${"0".repeat(N)}`;return`${I}${H}.${w.toString().padStart(N,"0")}`}toAbbreviation(N=2){let A=this.getValue("string"),T=Number(A),H=["","K","M","B","T","Q","Qi","S"],P=Math.floor(Math.log10(Math.abs(T))/3);if(P===0||!H[P])return A;return`${(T/10**(P*3)).toFixed(N)}${H[P]}`}toCurrency(N="$",{currencyPosition:A="start",decimal:T=2,decimalSeparator:H=".",thousandSeparator:P=",",trimTrailingZeros:O=!0}={}){let I=this.toFixed(T),$=A==="end",[M="0",w=""]=I.split("."),U=M.replace(/\B(?=(\d{3})+(?!\d))/g,P),X=w&&Number.parseInt(w,10)>0,Q=X?`${U}${H}${w}`:U,t=Q.length<100&&O&&X?Q.replace(/\.?0*$/,""):Q;return $?`${t}${N}`:`${N}${t}`}formatBigIntToSafeValue(N,A){let T=A||this.decimal||r,H=Math.max(T,ON(this.decimalMultiplier));return C({bigIntDecimal:T,decimal:H,value:N})}#A(N,...A){let T=this.#T(this,...A),H=ON(this.decimalMultiplier),P=Math.max(T,H),O=Math.min(P+mT,fT),I=o(O),$=A.reduce((U,X)=>{let Q=this.getBigIntValue(X,O);return XN(N).with("add",()=>U+Q).with("sub",()=>U-Q).with("mul",()=>U*Q/I).with("div",()=>{if(Q===0n)throw RangeError("Division by zero");return U*I/Q}).otherwise(()=>U)},this.bigIntValue*I/this.decimalMultiplier),M=C({bigIntDecimal:O,decimal:O,value:$}),w=this.decimal===void 0?void 0:Math.min(this.decimal,O);return new this.constructor({decimal:w,decimalMultiplier:o(O),identifier:this.toString(),value:M})}#N(N,...A){let T=this.#T(this,...A),H=this.getBigIntValue(A[0]||"0",T),P=this.getBigIntValue(this,T);return XN(N).with("gt",()=>P>H).with("gte",()=>P>=H).with("lt",()=>P<H).with("lte",()=>P<=H).with("eqValue",()=>P===H).otherwise(()=>!1)}#P(N){let A=gN(N)||"0";this.bigIntValue=this.#H(A)}#T(...N){let A=N.map((T)=>{return typeof T==="object"?T.decimal||ON(T.decimalMultiplier):XA(gN(T))}).filter(Boolean);return Math.max(...A,r)}#H(N,A){let T=A?o(A):this.decimalMultiplier,H=ON(T),[P="",O=""]=N.split(".");return BigInt(`${P}${O.padEnd(H,"0")}`)}}var pT=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function gN(N){let T=`${typeof N==="number"?pT.format(N):qN(N)}`.replaceAll(",",".").split(".");return T.length>1?`${T.slice(0,-1).join("")}.${T.at(-1)}`:T[0]||"0"}function XA(N){let A=N.split(".")[1]?.length||0;return Math.max(A,r)}function qN(N){return typeof N==="object"?"getValue"in N?N.getValue("string"):N.value:N}function yT(N,A){if(A===0n)throw Error("Cannot divide by zero");let T=A/2n;return N>=0n&&A>=0n||N<0n&&A<0n?(N+T)/A:(N-T)/A}function o(N){return 10n**BigInt(N)}function ON(N){return N.toString().length-1}function hT(N=""){let A=N.toUpperCase(),T=g.get("chains"),[H]=A.split(".");if(T.includes(H))return!0;let[P]=A.split("/");if(T.includes(P))return!0;throw new u({errorKey:"helpers_invalid_identifier",info:{identifier:N,message:`Invalid identifier: ${N}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}var f=[b.Hype,b.Near,b.Ripple,b.Solana,b.Stellar,b.Sui,b.Ton,b.Tron],KN=[b.THORChain,b.Maya],i=new Map,WN=new Map,s=new Map,dT=3600000;function cT(N){let A=s.get(N);if(A?.timestamp&&Date.now()-A.timestamp>dT){s.delete(N);return}return A}function lT(N,A){if(s.size>1000){let T=s.keys().next().value;if(T)s.delete(T)}s.set(N,{...A,timestamp:Date.now()})}class q extends m{address;chain;isGasAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:N,decimal:A,tax:T,chain:H,symbol:P,identifier:O}){super(typeof N==="object"?N:{decimal:A,value:N});let I=gA(O||`${H}.${P}`);this.type=xN(I),this.tax=T,this.chain=I.chain,this.ticker=I.ticker,this.symbol=I.symbol,this.address=I.address,this.isSynthetic=I.isSynthetic,this.isTradeAsset=I.isTradeAsset,this.isGasAsset=I.isGasAsset,this.chainId=RN(I.chain).chainId}toString({includeSynthProtocol:N}={}){return(this.isSynthetic||this.isTradeAsset)&&!N?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){if(this.isSynthetic)return`${this.chain}.${this.symbol.replace(/\//g,".")}`;if(this.isTradeAsset)return`${this.chain}.${this.symbol.replace(/~/g,"..")}`;let N=this.symbol.replace(/\./g,"__");return`${this.chain}.${N}`}getIconUrl(){return i.get(this.toString())?.logoURI}eqAsset({chain:N,symbol:A}){return this.chain===N&&this.symbol===A}eq(N){return this.eqAsset(N)&&this.eqValue(N)}static fromUrl(N,A=0){let T=N.indexOf(".");if(T===-1)throw new u({errorKey:"helpers_invalid_asset_url",info:{urlAsset:N}});let H=N.slice(0,T),P=N.slice(T+1),O=tN({chain:H,rest:P}).when(({rest:I})=>I.includes(".."),({chain:I,rest:$})=>`${I}.${$.replace(/\.\./g,"~")}`).when(({chain:I,rest:$})=>KN.includes(I)&&$.includes("."),({chain:I,rest:$})=>`${I}.${$.replace(/\./g,"/")}`).otherwise(({chain:I,rest:$})=>`${I}.${$.replace(/__/g,".")}`);return q.from({asset:O,value:A})}static from({value:N=0,fromBaseDecimal:A,asyncTokenLookup:T,...H}){let P=N instanceof m?N.getValue("string"):N,O="address"in H&&"chain"in H,I=eT(H);if(I===null&&T&&O){let{chain:HN,address:d}=H;return iT({address:d,chain:HN,fromBaseDecimal:A,parsedValue:P})}let $=O&&!I?`${H.chain}.UNKNOWN-${H.address}`:I,{identifier:M,decimal:w}=UN($),{chain:U,isSynthetic:X,isTradeAsset:Q,address:E}=gA(M),{baseDecimal:t}=RN(U),z=i.get(f.includes(U)?M:M.toUpperCase());if(!z&&T&&!X&&!Q)return(async()=>{let{ticker:HN}=y(M),d=await WA({address:E,chain:U,ticker:HN});return vN({decimal:d.decimals,identifier:d.identifier,value:A?e(BigInt(P),A):P})})();let J=z?.decimal||w;c({condition:!J&&!T,id:`assetValue_static_decimal_not_found_${U}`,warning:`Couldn't find static decimal for one or more tokens on ${U} (Using default ${t} 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:TN,identifier:h,tax:n}=z||{decimal:J||t,identifier:M},$N=A?e(BigInt(P),A):e(P,TN);return X||Q?rT(h,$N):vN({decimal:TN,identifier:h,tax:n,value:$N})}static async loadStaticAssets(N){let{loadTokenLists:A}=await import("@swapkit/tokens"),T=await A(N,{source:g.get("envs").isDev?"dev":"prod"});for(let{tokens:H}of Object.values(T))for(let P of H){let{identifier:O}=P,{chain:I,symbol:$}=y(O),{address:M}=FN($,I),{baseDecimal:w}=RN(I),U=f.includes(I)?O:O.toUpperCase(),X="decimals"in P&&P.decimals!==void 0?P.decimals:w,Q="logoURI"in P&&P.logoURI?P.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${O.toLowerCase()}.png`,E={decimal:X,identifier:O,logoURI:Q,tax:"tax"in P?P.tax:void 0};if(i.set(U,E),M){let t=f.includes(I)?`${I}:${M}`:`${I}:${M.toUpperCase()}`;WN.set(t,O)}}return!0}static setStaticAssets(N){i.clear(),WN.clear();for(let[A,T]of N.entries()){let{identifier:H}=T,{chain:P,symbol:O}=y(H),{address:I}=FN(O,P),{baseDecimal:$}=RN(P),M=T.chain??P,w=T.address??I,U=f.includes(M)?H:H.toUpperCase(),X=T.decimals??T.decimal??$,Q=T.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${H.toLowerCase()}.png`,E={decimal:X,identifier:U,logoURI:Q,tax:T.tax};if(i.set(U,E),w){let t=f.includes(M)?`${M}:${w}`:`${M}:${w.toUpperCase()}`;WN.set(t,H)}}return!0}static get staticAssets(){return i}}function iL(N){let A=q.from({chain:N});return tN(N).with(b.Bitcoin,b.Litecoin,b.BitcoinCash,b.Dash,()=>A.set(0.00010001)).with(b.Dogecoin,()=>A.set(1.00000001)).with(b.Avalanche,b.Ethereum,b.Arbitrum,b.BinanceSmartChain,()=>A.set(0.00000001)).with(b.THORChain,b.Maya,()=>A.set(0)).with(b.Cosmos,b.Kujira,()=>A.set(0.000001)).otherwise(()=>A.set(0.00000001))}async function WA({chain:N,address:A,ticker:T}){let P=f.includes(N)?`${N}:${A||T}`:`${N}:${A||T}`.toUpperCase(),O=cT(P);if(O)return O;if(!A){let{baseDecimal:M}=RN(N);return{decimals:M,identifier:`${N}.${T||"UNKNOWN"}`}}let I=await uA({address:A,chain:N}),$=`${N}.${I.ticker||T||"UNKNOWN"}-${A}`;return c({condition:!!(!I.ticker&&T),id:`async_token_lookup_failed_${N}_${A}`,warning:`Could not fetch token metadata for ${N}:${A} from chain. Using user-provided ticker (${T}) with baseDecimal (${I.decimals}).`}),I.ticker&&lT(P,{decimals:I.decimals,identifier:$}),{decimals:I.decimals,identifier:$}}function vN({identifier:N,decimal:A,value:T,tax:H}){return hT(N),new q({decimal:A,identifier:N,tax:H,value:e(T,A)})}function rT(N,A=0){let T=N.includes(".")?N.split(".")?.[0]?.toUpperCase():void 0,H=T?KN.includes(T):!1,P=N.slice(0,14).includes("~")?"~":"/",[O,I]=H?N.split(".").slice(1).join().split(P):N.split(P);if(!(O&&I))throw new u({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});return new q({decimal:8,identifier:`${T||b.THORChain}.${O}${P}${I}`,value:e(A,8)})}async function iT({address:N,chain:A,fromBaseDecimal:T,parsedValue:H}){let{decimals:P,identifier:O}=await WA({address:N,chain:A}),I=T?e(BigInt(H),T):H;return vN({decimal:P,identifier:O,value:I})}function e(N,A){return typeof N==="bigint"?C({bigIntDecimal:A,decimal:A,value:N}):N}function sT(N){let A=tN(N).when((T)=>("chain"in T)&&T.chain!==void 0,({chain:T})=>T).otherwise((T)=>{let H=y(T.asset);return H.synth?b.THORChain:H.chain});if(!oT.includes(A.toUpperCase())){let T="asset"in N?N.asset:A;throw new u({errorKey:"helpers_invalid_asset_identifier",info:{identifier:T,message:`Unsupported chain "${A}" - use the AssetValue constructor directly`}})}}function eT(N){if(sT(N),"chain"in N){let{chain:P,address:O}=N;if(O){let I=f.includes(P)?`${P}:${O}`:`${P}:${O.toUpperCase()}`,$=WN.get(I);if($)return $;return null}return P}let{chain:A,symbol:T}=y(N.asset);return xN({chain:A,symbol:T})==="Native"?A:N.asset}function aT(N,A,T){let H=N.split("."),P=H[0]?.toUpperCase(),O=KN.includes(P),I=T?"~":"/",[$,M=""]=O?H.slice(1).join(".").split(I):N.split(I);if(!($&&M))throw new u({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});let{ticker:w,address:U}=EA({chain:$,symbol:M}),X=`${$}${I}${M}`;return{address:U,chain:P,isGasAsset:!1,isSynthetic:A,isTradeAsset:T,symbol:X,ticker:w}}function NH(N){let A=N.indexOf("."),T=(A===-1?N:N.slice(0,A)).toUpperCase(),H=A===-1?N:N.slice(A+1),{address:P,ticker:O}=EA({chain:T,symbol:H}),I;try{I=P&&CT.includes(T)&&uN(P)?uN(P):P}catch{I=P}let $=I?`${O}-${I}`:H;return{address:I,chain:T,isGasAsset:UA({chain:T,symbol:H}),isSynthetic:!1,isTradeAsset:!1,symbol:$,ticker:O}}function gA(N){let A=N.slice(0,14),T=A.includes("/"),H=A.includes("~");if(T||H)return aT(N,T,H);return NH(N)}function EA({symbol:N,chain:A}){let{ticker:T,address:H}=FN(N,A);return{address:H&&!f.includes(A)?H.toLowerCase():H,ticker:T}}class EN extends m{eq(N){return this.eqValue(N)}static fromBigInt(N,A){return new EN({decimal:A,value:C({bigIntDecimal:A,decimal:A,value:N})})}}function bA(N=!0){return N?"https://gateway.liquify.com/chain/thorchain_midgard":"https://midgard.mayachain.info"}function TH(N=!0){let A=bA(N);return N?`${A}/v2/thorname`:`${A}/v2/mayaname`}function HH(N){return function(T){let H=T?`?status=${T}`:"";return _.get(`${N}/v2/pools${H}`)}}function PH(N){return function(T){return _.get(`${N}/v2/pool/${T}`)}}function LH(N){return function(T,H){let P=H?`?period=${H}`:"";return _.get(`${N}/v2/pool/${T}/stats${P}`)}}function FH(N){return function(T,H){let P=new URLSearchParams;if(H?.interval)P.append("interval",H.interval);if(H?.count)P.append("count",H.count.toString());if(H?.from)P.append("from",H.from.toString());if(H?.to)P.append("to",H.to.toString());let O=P.toString()?`?${P.toString()}`:"";return _.get(`${N}/v2/history/depths/${T}${O}`)}}function OH(N){return function(){return _.get(`${N}/v2/network`)}}function RH(N){return function(){return _.get(`${N}/v2/health`)}}function IH(N){return function(){return _.get(`${N}/v2/nodes`)}}function BH(N){return function(T){return _.get(`${N}/v2/node/${T}`)}}function GH(N){return function(){return _.get(`${N}/v2/mimir/votes`)}}function $H(N){return function(){return _.get(`${N}/v2/mimir`)}}function YH(N){return function(){return _.get(`${N}/v2/constants`)}}function MH(N){return function(){return _.get(`${N}/v2/stats`)}}function _H(N){return function(T){let H=new URLSearchParams;if(T?.interval)H.append("interval",T.interval);if(T?.count)H.append("count",T.count.toString());if(T?.from)H.append("from",T.from.toString());if(T?.to)H.append("to",T.to.toString());let P=H.toString()?`?${H.toString()}`:"";return _.get(`${N}/v2/history/earnings${P}`)}}function DH(N){return function(T,H){let P=new URLSearchParams;if(H?.interval)P.append("interval",H.interval);if(H?.count)P.append("count",H.count.toString());if(H?.from)P.append("from",H.from.toString());if(H?.to)P.append("to",H.to.toString());let O=P.toString()?`?${P.toString()}`:"",I=T?`/swaps/${T}`:"/swaps";return _.get(`${N}/v2/history${I}${O}`)}}function SH(N){return function(T){let H=new URLSearchParams;if(T?.interval)H.append("interval",T.interval);if(T?.count)H.append("count",T.count.toString());if(T?.from)H.append("from",T.from.toString());if(T?.to)H.append("to",T.to.toString());let P=H.toString()?`?${H.toString()}`:"";return _.get(`${N}/v2/history/tvl${P}`)}}function uH(N){if(!N)return"";let A=new URLSearchParams,T=(H,P)=>{if(P!==void 0)A.append(H,typeof P==="number"?P.toString():P)};return T("address",N.address),T("txid",N.txid),T("asset",N.asset),T("type",N.type),T("affiliate",N.affiliate),T("limit",N.limit),T("offset",N.offset),A.toString()?`?${A.toString()}`:""}function UH(N){return function(T){let H=uH(T);return _.get(`${N}/v2/actions${H}`)}}function XH(N){return function(T){return _.get(`${N}/v2/member/${T}`)}}function gH(N){return function(T){let H=T?`/${T}`:"";return _.get(`${N}/v2/members${H}`)}}function WH(N){return function(T,H){let P=H?`&asset=${H}`:"";return _.get(`${N}/v2/saver/${T}${P?`?${P.substring(1)}`:""}`)}}function EH(N){return function(T){return _.get(`${N}/v2/savers/${T}`)}}function bH(N){return function(T,H){let P=new URLSearchParams;if(H?.interval)P.append("interval",H.interval);if(H?.count)P.append("count",H.count.toString());if(H?.from)P.append("from",H.from.toString());if(H?.to)P.append("to",H.to.toString());let O=P.toString()?`?${P.toString()}`:"",I=T?`/savers/${T}`:"/savers";return _.get(`${N}/v2/history${I}${O}`)}}function nH(N){return function(T){return _.get(`${N}/v2/balance/${T}`)}}function wH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return;throw P};return await _.get(`${N}/lookup/${T}`,{onError:H,retry:{maxRetries:1}})}}function zH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return[];throw P};return await _.get(`${N}/rlookup/${T}`,{onError:H,retry:{maxRetries:1}})}}function JH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return[];throw P};return await _.get(`${N}/owner/${T}`,{onError:H,retry:{maxRetries:1}})}}function a({asset:N,value:A}){return q.from({asset:N,fromBaseDecimal:AH(bN.THORChain).baseDecimal,value:A})}function QH({liquidityPositionGetter:N,isThorchain:A}){return async function(H){let P=await N(H),O=A?"rune":"cacao";return P.pools.map((I)=>({[`${O}Pending`]:a({asset:"THOR.RUNE",value:I.runePending}),[`${O}RegisteredAddress`]:I.runeAddress,[`${O}Withdrawn`]:a({asset:"THOR.RUNE",value:I.runeWithdrawn}),[O]:a({asset:"THOR.RUNE",value:I.runeAdded}),asset:a({asset:I.pool,value:I.assetAdded}),assetPending:a({asset:I.pool,value:I.assetPending}),assetRegisteredAddress:I.assetAddress,assetWithdrawn:a({asset:I.pool,value:I.assetWithdrawn}),dateFirstAdded:I.dateFirstAdded,dateLastAdded:I.dateLastAdded,poolShare:new EN(I.liquidityUnits).div(I.pool)}))}}function nA(N){let A=N===bN.THORChain,T=bA(A),H=TH(A),P=XH(T);return{getActions:UH(T),getBalance:nH(T),getConstants:YH(T),getEarningsHistory:_H(T),getHealth:RH(T),getLiquidityPosition:QH({isThorchain:A,liquidityPositionGetter:P}),getLiquidityPositionRaw:P,getMembers:gH(T),getMimir:$H(T),getMimirVotes:GH(T),getNameDetails:wH(H),getNamesByAddress:zH(H),getNamesByOwner:JH(H),getNetworkInfo:OH(T),getNode:BH(T),getNodes:IH(T),getPool:PH(T),getPoolDepthHistory:FH(T),getPoolStats:LH(T),getPools:HH(T),getSaverDetails:WH(T),getSavers:EH(T),getSaversHistory:bH(T),getStats:MH(T),getSwapHistory:DH(T),getTVLHistory:SH(T)}}var wA=nA(bN.THORChain),zA=nA(bN.Maya);var oN={};lN(oN,{searchTokens:()=>XP,getTrackerDetails:()=>YP,getTokenListProviders:()=>uP,getTokenList:()=>UP,getTokenApproval:()=>SP,getSwapTo:()=>QP,getSwapQuote:()=>MP,getRouteWithTx:()=>_P,getPrice:()=>gP,getNearDepositChannel:()=>bP,getGasRate:()=>WP,getChainflipDepositChannel:()=>EP,getChainBalance:()=>DP,SKRequestClient:()=>x});import{EVMChains as yN}from"@swapkit/types";import{match as $P,P as GN}from"ts-pattern";import{Chain as nN,ChainId as IN}from"@swapkit/types";import{array as W,boolean as K,coerce as jA,number as D,object as Y,optional as G,string as F,union as kN,unknown as mN,z as L}from"zod";var VA;((H)=>{H.CHEAPEST="CHEAPEST";H.FASTEST="FASTEST";H.RECOMMENDED="RECOMMENDED"})(VA||={});var wN;((U)=>{U.PSBT="PSBT";U.EVM="EVM";U.COSMOS="COSMOS";U.RADIX="RADIX";U.NEAR="NEAR";U.STELLAR="STELLAR";U.TON="TON";U.TRON="TRON";U.EIP_712_HYPE_SEND_ASSET="EIP_712_HYPE_SEND_ASSET";U.EIP_712_HYPE_WITHDRAW="EIP_712_HYPE_WITHDRAW"})(wN||={});var xA;((J)=>{J.approve="approve";J.claim="claim";J.deposit="deposit";J.donate="donate";J.lending="lending";J.lp_action="lp_action";J.native_contract_call="native_contract_call";J.native_send="native_send";J.stake="stake";J.streaming_swap="streaming_swap";J.swap="swap";J.thorname_action="thorname_action";J.token_contract_call="token_contract_call";J.token_transfer="token_transfer";J.unknown="unknown";J.unstake="unstake"})(xA||={});var qA;((E)=>{E.swap="swap";E.aggregation="aggregation";E.addLiquidity="addLiquidity";E.withdrawLiquidity="withdrawLiquidity";E.addSavers="addSavers";E.withdrawSavers="withdrawSavers";E.borrow="borrow";E.repay="repay";E.name="name";E.donate="donate";E.claim="claim";E.stake="stake";E.unstake="unstake"})(qA||={});var vA;(($)=>{$.unknown="unknown";$.not_started="not_started";$.pending="pending";$.swapping="swapping";$.completed="completed";$.refunded="refunded";$.failed="failed"})(vA||={});var tA;((z)=>{z.not_started="not_started";z.starting="starting";z.broadcasted="broadcasted";z.mempool="mempool";z.inbound="inbound";z.outbound="outbound";z.swapping="swapping";z.completed="completed";z.refunded="refunded";z.partially_refunded="partially_refunded";z.dropped="dropped";z.reverted="reverted";z.replaced="replaced";z.retries_exceeded="retries_exceeded";z.parsing_error="parsing_error"})(tA||={});var RF=Y({address:G(F()),chain:L.enum(nN).optional(),chainId:L.enum(IN),coingeckoId:G(F()),decimals:jA.number(),extensions:G(L.looseObject({})),identifier:F(),logoURI:G(F()),name:G(F()),shortCode:G(F()),symbol:G(F()),ticker:F()}),IF=L.object({block:L.optional(L.number().describe("Block number. Required for Polkadot chain. e.g. `123456`")),chainId:L.optional(L.string().describe("ChainId for the hash. e.g. `thorchain-1`")),depositChannelId:L.optional(L.string().describe("Deposit channel ID, required for Chainflip if tx was broadcasted without wallet connection")),hash:L.optional(L.string().describe("Hash for the first transaction broadcasted by the end user. e.g. `88D1819378ECD09E5284C54937CDC1E99B52F253C007617A02DD1200710CE677`"))}).refine((N)=>N.hash&&N.chainId||N.depositChannelId,{message:"Either `hash` and `chainId` or `depositChannelId` must be provided"}),BF=L.object({forceUpdate:L.string().toLowerCase().transform((N)=>N==="true").pipe(L.boolean()).optional()}),GF=Y({error:F(),message:F()}),NN=Y({address:G(F()),chain:L.enum(nN),decimal:G(D()),isGasAsset:K(),isSynthetic:K(),symbol:F(),tax:G(Y({buy:D(),sell:D()})),ticker:F()}),KA=Y({id:F(),market_cap:D(),name:F(),price_change_24h_usd:D(),price_change_percentage_24h_usd:D(),sparkline_in_7d:W(D()),timestamp:F(),total_volume:D()}).partial(),$F=Y({cg:G(KA),identifier:F(),price_usd:D(),provider:F(),timestamp:D()}),kA=W(Y({cg:G(KA),identifier:F(),price_usd:D(),provider:F(),timestamp:D()}).partial()),YF=Y({affiliate:G(F().describe("Affiliate thorname")),affiliateFee:G(D().describe("Affiliate fee in basis points").refine((N)=>N===Math.floor(N)&&N>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:G(K().describe("Allow smart contract as recipient")),allowSmartContractSender:G(K().describe("Allow smart contract as sender")),buyAsset:F().describe("Asset to buy"),cfBoost:G(K().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:G(F().describe("Address to send asset to")),disableSecurityChecks:G(K().describe("Disable security checks")),includeTx:G(K().describe("Set to true to include an transaction object (EVM only)")),providers:G(W(F().describe("List of providers to use").refine((N)=>Z[N]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:G(F().describe("Referrer address (referral program)")),sellAmount:F().describe("Amount of asset to sell").refine((N)=>+N>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:F().describe("Asset to sell"),slippage:G(D().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:G(F().describe("Address to send asset from"))}).refine((N)=>N.sellAsset!==N.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),MF=Y({metadata:K(),tokens:W(Y({identifier:F()}))}),mA=Y({destinationAddress:F()}),ZH=mA.extend({affiliateFees:W(Y({brokerAddress:F(),feeBps:D()})).optional(),brokerCommissionBps:D().optional(),buyAsset:Y({asset:F(),chain:F()}),channelMetadata:Y({cfParameters:F().optional(),gasBudget:F().optional(),message:F().optional()}).optional(),dcaParameters:Y({chunkInterval:D().optional(),numberOfChunks:D().optional()}).optional(),maxBoostFeeBps:D().optional(),refundParameters:Y({minPrice:F().optional(),refundAddress:F().optional(),retryDuration:D().optional()}).optional(),sellAsset:Y({asset:F(),chain:F()})}),fA=Y({channelId:F(),depositAddress:F()}),JA=mA.extend({affiliateFees:Y({feeBps:D(),nearId:F()}).optional(),buyAsset:F(),sellAmount:F(),sellAsset:F(),slippage:jA.number(),sourceAddress:F()}),QA=Y({amountIn:F(),amountInFormatted:F(),amountInUsd:F(),amountOut:F(),amountOutFormatted:F(),amountOutUsd:F(),deadline:F().optional(),minAmountIn:F(),minAmountOut:F(),timeEstimate:D().optional(),timeWhenInactive:F().optional()}),_F=QA.extend({depositAddress:F(),quote:QA,signature:F(),timestamp:F(),tx:mN()}),pA=Y({buyAsset:F(),buyAssetAmount:F(),buyAssetAmountMaxSlippage:F(),deadline:F().optional(),depositAddress:F(),depositAmount:F(),depositAsset:F(),tx:mN()}),jH=Y({evmCalldata:L.optional(L.string()),intentHash:L.optional(L.string()),logs:L.optional(L.unknown()),manifest:L.optional(L.unknown()),memo:L.optional(L.string()),spender:L.optional(L.string()),thorname:L.optional(L.string())}),VH=Y({currentStage:F(),inboundConfirmation:D(),inboundObservation:D(),outboundDelay:D(),outboundObservation:D(),streamingSwap:D()}),xH=Y({count:G(D()),interval:G(D()),quantity:G(D()),subSwapsMap:G(W(D()))}),qH=L.object({currentLegIndex:L.optional(L.number()),estimatedTimeToComplete:L.number(),estimates:L.optional(VH),providerDetails:L.optional(L.object({streamingDetails:L.optional(xH)}))}),vH=Y({affiliate:G(NN),liquidity:G(NN),network:G(NN),protocol:G(NN),tax:G(NN)}),tH=Y({affiliate:F(),bps:F(),isReferrer:K()}),KH=Y({affiliate:G(F()),affiliateFees:G(W(tH)),broadcastedAt:G(D()),explorerUrl:G(F()),fees:G(vH),images:G(Y({chain:G(F()),from:G(F()),provider:G(F()),to:G(F())})),provider:G(L.enum(Z)),providerAction:L.optional(L.enum(qA)),quoteId:G(F()),wallet:G(F())}),AN=L.object({block:L.number(),chainId:L.enum(IN),finalAddress:L.optional(L.string()),finalAsset:L.optional(NN),finalisedAt:L.number(),fromAddress:L.string(),fromAmount:L.string(),fromAsset:L.string(),hash:L.string(),meta:L.optional(KH),payload:L.optional(jH),status:L.enum(vA),toAddress:L.string(),toAmount:L.string(),toAsset:L.string(),trackingStatus:L.optional(L.enum(tA)),transient:L.optional(qH),type:L.enum(xA)}),yA=AN.extend({legs:L.array(AN)}),DF=AN.extend({legs:W(AN)}),SF=AN.extend({legs:W(AN)}),fN=W(Y({amount:F(),asset:F(),chain:F(),protocol:L.enum(Z),type:L.enum(QN)})),pN=L.object({inbound:L.optional(L.number().describe("Time to receive inbound asset in seconds")),outbound:L.optional(L.number().describe("Time to receive outbound asset in seconds")),swap:L.optional(L.number().describe("Time to swap assets in seconds")),total:L.number().describe("Total time in seconds")}),kH=/^(?:0x[0-9a-fA-F]+|[0-9]+)$/;function mH(N){return N===""||kH.test(N)}function uF(N){return N?BigInt(N):0n}function UF(N){let A=typeof N==="bigint"?N:BigInt(N);return A>0n?`0x${A.toString(16)}`:"0x0"}var BN=F().refine(mH,{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"),fH=Y({data:F().describe("Data to send"),from:F().describe("Address of the sender"),to:F().describe("Address of the recipient"),value:BN}),pH=L.object({data:L.string().optional(),raw_data:L.object({contract:L.any(),data:L.string().optional(),expiration:L.number(),fee_limit:L.number().optional(),ref_block_bytes:L.string(),ref_block_hash:L.string(),timestamp:L.number()}).passthrough(),raw_data_hex:L.string(),txID:L.string(),value:BN.optional(),visible:L.boolean()}),yH=W(kN([F(),D(),W(F()),Y({from:F(),value:BN}).describe("Parameters to pass to the contract method")])),XF=Y({approvalSpender:G(F().describe("Address of the spender to approve")),approvalToken:G(F().describe("Address of the token to approve spending of")),contractAddress:F().describe("Address of the contract to interact with"),contractMethod:F().describe("Name of the method to call"),contractParamNames:W(F().describe("Names of the parameters to pass to the contract method")),contractParams:yH}),oH=Y({typeUrl:F("/types.MsgDeposit"),value:Y({coins:W(Y({amount:F(),asset:Y({chain:F(),symbol:F(),synth:K(),ticker:F()})})),memo:F(),signer:F()})}),CH=Y({typeUrl:F("/types.MsgSend"),value:Y({amount:W(Y({amount:F(),denom:F()})),fromAddress:F(),toAddress:F()})}),hH=Y({typeUrl:F(),value:CH.shape.value.or(oH.shape.value)}),dH=Y({amount:W(Y({amount:F(),denom:F()})),gas:F()}),cH=Y({accountNumber:D(),chainId:L.enum(IN),fee:dH,memo:F(),msgs:W(hH),sequence:D()}),lH=L.array(L.object({calldata:L.array(L.string()),contractAddress:L.string(),entrypoint:L.string()})),rH=L.object({address:L.string().describe("Destination address in friendly format"),amount:L.string().describe("Amount in nanotons"),payload:L.string().optional().describe("Base64 BOC of body cell"),stateInit:L.string().optional().describe("Base64 BOC of state init")}),iH=L.object({messages:L.array(rH),sendMode:L.number().describe("TON wallet send mode for the whole transfer")}),gF="USDC:0x6d1e7cde53ba9467b783cb7c530ce054",sH=L.looseObject({domain:L.looseObject({chainId:G(kN([D(),F()])),name:G(F()),verifyingContract:G(F()),version:G(F())}),message:L.record(F(),mN()),primaryType:F(),types:L.record(F(),W(L.looseObject({name:F(),type:F()})))}),eH=L.looseObject({amount:F(),destination:F(),destinationDex:F(),fromSubAccount:F(),hyperliquidChain:F(),nonce:D().int(),signatureChainId:F(),sourceDex:F(),token:F(),type:L.literal("sendAsset")}),oA=L.looseObject({action:L.looseObject({type:F()}),submitTo:F(),typedData:sH}),WF=oA.extend({action:eH}),CA=kN([fH,cH,pH,iH,oA,F()]),aH=CA.or(lH),NP=Y({affiliate:F().describe("Affiliate address").optional(),affiliateFee:D().describe("Affiliate fee").optional(),buyAsset:F().describe("Asset to buy"),destinationAddress:F().describe("Destination address"),estimatedTime:pN.optional(),provider:L.enum(Z),sellAsset:F().describe("Asset to sell"),slipPercentage:D().describe("Slippage as a percentage"),sourceAddress:F().describe("Source address")}),EF=NP.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),AP=Y({asset:F().describe("Asset name"),image:F().describe("Asset image"),price:D().describe("Price in USD")}),TP=ZH,hA=Y({assets:G(W(AP)),maxStreamingQuantity:D().optional(),referrer:F().optional(),streamingInterval:D().optional(),tags:W(L.enum(VA))}),dA=hA.extend({affiliate:G(F()),affiliateFee:G(F()),approvalAddress:G(F().describe("Approval address for swap")),chainflip:TP.optional(),garden:JA.optional(),near:JA.optional(),priceImpact:G(D().describe("Price impact")),referrer:G(F()),txType:G(L.enum(wN))}),cA=W(Y({code:L.enum(JN),display:F(),tooltip:F().optional()})),HP=Y({buyAmount:F().describe("Buy amount"),buyAmountMaxSlippage:F().describe("Buy amount max slippage"),buyAsset:F().describe("Asset to buy"),fees:G(fN),provider:L.enum(Z),sellAmount:F().describe("Sell amount"),sellAsset:F().describe("Asset to sell")}),PP=Y({buyAsset:F().describe("Asset to buy"),destinationAddress:G(F().describe("Destination address")),estimatedTime:G(pN),expectedBuyAmount:F().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:F().describe("Expected Buy amount max slippage"),expiration:G(F().describe("Expiration")),fees:fN,inboundAddress:G(F().describe("Inbound address")),legs:W(HP),memo:G(F().describe("Memo")),meta:dA,providers:W(L.enum(Z)),routeId:F().describe("Route ID"),sellAmount:F().describe("Sell amount"),sellAsset:F().describe("Asset to sell"),sourceAddress:G(F().describe("Source address")),targetAddress:G(F().describe("Target address")),totalSlippageBps:D().describe("Total slippage in bps"),tx:G(aH),txType:G(L.enum(wN)),warnings:cA}),lA=Y({error:G(F().describe("Error message")),providerErrors:G(W(Y({errorCode:G(L.enum(PN)),message:G(F()),provider:L.enum(Z).optional()}))),quoteId:F().describe("Quote ID"),routes:W(PP)}),rA=L.object({chainId:L.enum(IN),createdAt:L.date(),id:L.number(),unit:L.string(),value:L.string()}),LP=L.array(rA),iA=L.union([rA,LP]),bF=W(Y({chain:L.enum(nN),decimal:D(),identifier:F(),symbol:F(),ticker:F(),value:F()})),nF=L.union([L.object({amount:L.string(),spender:L.string(),tokenIdentifier:L.string(),userWalletAddress:L.string()}),L.object({amount:L.string(),chainId:L.enum(IN),spender:L.string(),tokenContractAddress:L.string(),userWalletAddress:L.string()}),L.object({routeId:L.string()})]),wF=L.object({approvalTransaction:L.optional(L.object({data:L.string(),from:L.string(),gasLimit:L.optional(L.string()),gasPrice:L.optional(L.string()),to:L.string(),value:BN})),approvedAmount:L.string(),isApproved:L.boolean()}),FP=L.object({data:L.string().describe("Encoded approval call data"),from:L.string().describe("User wallet address"),gasLimit:L.string().optional().describe("Estimated gas limit"),gasPrice:L.string().optional().describe("Current gas price"),to:L.string().describe("Token contract address"),value:BN.describe("ETH value (always '0' for approvals)")}),OP=L.object({tx:L.string(),txType:L.literal("STELLAR")}),RP=L.union([FP,OP]),ZA=L.object({buyAmount:L.string().describe("Buy amount").optional(),buyAmountMaxSlippage:L.string().describe("Buy amount max slippage").optional(),buyAsset:L.string().describe("Asset to buy"),expectedBuyAmount:L.string().describe("Expected Buy amount").optional(),expectedBuyAmountMaxSlippage:L.string().describe("Expected Buy amount max slippage").optional(),fees:fN,provider:L.enum(Z),sellAmount:L.string().describe("Sell amount"),sellAsset:L.string().describe("Asset to sell")}),sA=ZA.extend({estimatedTime:L.optional(pN),expiration:L.optional(L.string().describe("Expiration")),legs:L.array(ZA),providers:L.array(L.enum(Z)),routeId:L.string().describe("Route ID"),totalSlippageBps:L.number().describe("Total slippage in bps"),warnings:cA}).omit({provider:!0}),eA=L.object({method:L.string(),payload:L.optional(L.unknown()),url:L.string()}),IP=sA.extend({meta:hA,nextActions:L.optional(L.array(eA))}),zF=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(L.object({errorCode:L.optional(L.enum(PN)),message:L.optional(L.string()),provider:L.enum(Z).optional()}))),quoteId:L.string().describe("Quote ID"),routes:L.array(IP)}),JF=L.object({providers:L.array(L.enum(Z)).optional().describe("Optional list of providers to query for trading pairs"),sellAsset:L.string().describe("Asset identifier to sell (e.g., 'BTC.BTC' or 'ETH.ETH')")}),BP=L.object({chain:L.enum(nN).describe("Chain the asset is on"),identifier:L.string().describe("Asset identifier (e.g., 'ETH.USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')"),providers:L.array(L.enum(Z)).describe("Providers that support this trading pair"),symbol:L.string().describe("Asset symbol"),ticker:L.string().describe("Asset ticker")}),QF=L.object({buyAssets:L.array(BP).describe("List of assets that can be swapped to"),sellAsset:L.string().describe("The input sell asset identifier")}),aA=sA.extend({destinationAddress:L.string().describe("Destination address"),inboundAddress:L.optional(L.string().describe("Inbound address")),memo:L.optional(L.string().describe("Memo to include in the transaction")),meta:dA,sourceAddress:L.string().describe("Source address"),targetAddress:L.optional(L.string().describe("Target address")),tx:G(CA),txType:L.optional(L.enum(wN))}),GP=L.object({data:L.optional(L.record(L.string(),L.string().optional())),errorCode:L.enum(PN),message:L.string().optional(),provider:L.enum(Z).optional()}),ZF=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(GP)),quoteId:L.string().describe("Quote ID"),routes:L.array(aA)}),NT=aA.extend({approvalTx:RP.optional().describe("Optional approval transaction required before swap execution"),nextActions:L.optional(L.array(eA)),swapId:L.string().describe("The unique swap ID for tracking")});var x=_.extend({dynamicHeader:async()=>{let N=g.get("widgetId"),A=g.get("widgetKey");if(N&&A&&typeof window<"u"){let H=Math.floor(Date.now()/1000),P=window.location.origin,O=await HA(A,N,P,H);return{Origin:P,"X-Signature":O,"X-Timestamp":H.toString(),"x-widget-id":N}}let{swapKit:T}=g.get("apiKeys");return T?{"x-api-key":T}:{}}});async function YP(N){let A=await x.post(V("/track"),{json:N});try{let T=yA.safeParse(A);if(!T.success)throw new u("api_v2_invalid_response",T.error);return T.data}catch(T){return A}}async function MP(N){let{getQuote:A}=g.get("endpoints");if(A)return A(N);let H=g.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",P=await x.post(V(H),{json:N});if(P.error)throw new u("api_v2_server_error",{message:P.error});try{let O=lA.safeParse(P);if(!O.success)throw new u("api_v2_invalid_response",O.error);return O.data}catch{return P}}async function _P(N){let{getRouteWithTx:A}=g.get("endpoints");if(A)return A(N);let H=g.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",P=await x.post(V(H),{json:N});try{let O=NT.safeParse(P);if(!O.success)throw new u("api_v2_invalid_response",O.error);return O.data}catch(O){return console.error(new u("api_v2_invalid_response",O)),P}}async function DP({chain:N,address:A,scamFilter:T=!0}){let{getBalance:H}=g.get("endpoints");if(H)return H({address:A,chain:N});let P=V(`/balance?chain=${N}&address=${A}`),O=await x.get(P),I=Array.isArray(O)?O:[];return T?JP(I):I}function SP(N){let A=$P(N).with({routeId:GN.string,spender:GN.string},({routeId:T,spender:H})=>V(`/approve?routeId=${T}&sourceAddress=${H}`)).with({assetValue:GN.instanceOf(q),spender:GN.string,userWallet:GN.string},({spender:T,userWallet:H,assetValue:P})=>V(`/approve?tokenIdentifier=${P.toString()}&userWalletAddress=${H}&spender=${T}&amount=${P.getValue("string")}`)).exhaustive();return x.get(A)}function uP(){let N=V("/providers");return x.get(N)}function UP(N){let A=V(`/tokens?provider=${N}`);return x.get(A)}function XP({query:N,chain:A,page:T,limit:H}){let P=new URLSearchParams({query:N});if(A!==void 0)P.set("chain",A);if(T!==void 0)P.set("page",T.toString());if(H!==void 0)P.set("limit",H.toString());let O=V(`/tokens/search?${P.toString()}`);return x.get(O)}async function gP(N){let A=V("/price"),T=await x.post(A,{json:N});try{let H=kA.safeParse(T);if(!H.success)throw new u("api_v2_invalid_response",H.error);return H.data}catch(H){throw new u("api_v2_invalid_response",H)}}async function WP(){let N=V("/gas"),A=await x.get(N);try{let T=iA.safeParse(A);if(!T.success)throw new u("api_v2_invalid_response",T.error);return Array.isArray(T)?T:[T]}catch(T){throw new u("api_v2_invalid_response",T)}}async function EP(N){let{destinationAddress:A}=N;if(!A)throw new u("chainflip_broker_invalid_params");let T=g.get("integrations").chainflip?.brokerUrl||V("/chainflip/broker/channel"),H=await x.post(T,{json:N});try{let P=fA.safeParse(H);if(!P.success)throw new u("api_v2_invalid_response",P.error);return P.data}catch(P){throw new u("api_v2_invalid_response",P)}}async function bP(N){let{destinationAddress:A}=N;if(!A)throw new u("chainflip_broker_invalid_params");let T=V("/near/channel"),H=await x.post(T,{json:N});try{let P=pA.safeParse(H);if(!P.success)throw new u("api_v2_invalid_response",P.error);return P.data}catch(P){throw new u("api_v2_invalid_response",P)}}function V(N){let{isDev:A,apiUrl:T,devApiUrl:H}=g.get("envs"),{enabled:P,quoteUrl:O,swapUrl:I}=g.get("localMode");if(P&&N){let[M]=N.split("?");if(M==="/quote"||M==="/v3/quote")return`${O}${N}`;if(M==="/swap"||M==="/v3/swap")return`${I}${N}`}return`${A?H:T}${N}`}function nP(N){try{return q.from({asset:N.identifier})}catch{return}}var wP=new Set(["OP.OP"]),zP=/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/im;function JP(N){return N.filter((A)=>{let T=nP(A);if(!T)return!1;if(wP.has(T.toString().toUpperCase()))return!0;return(!yN.includes(T.chain)||T.isGasAsset||!!T.address)&&!zP.test(T.ticker)})}async function QP(N){let{getSwapTo:A}=g.get("endpoints");if(A)return A(N);let T=new URLSearchParams({sellAsset:N.sellAsset});if(N.providers?.length)for(let I of N.providers)T.append("providers",I);let H=V(`/swapTo?${T.toString()}`),P=await x.get(H);if(!Array.isArray(P))return{buyAssets:[],sellAsset:N.sellAsset};let O=[];for(let I of P)try{let $=q.from({asset:I});O.push({chain:$.chain,identifier:$.toString(),providers:[],symbol:$.symbol,ticker:$.ticker})}catch{}return{buyAssets:O,sellAsset:N.sellAsset}}var CN={};lN(CN,{getThorchainQueue:()=>xP,getTcyStakers:()=>pP,getTcyStaker:()=>fP,getTcyClaimers:()=>oP,getTcyClaimer:()=>yP,getTNSPreferredAsset:()=>KP,getTHORNodeTNSDetails:()=>AT,getRunePoolProviderInfo:()=>mP,getRunePoolInfo:()=>kP,getNodes:()=>qP,getMimirInfo:()=>vP,getLastBlock:()=>VP,getInboundAddresses:()=>tP});import{match as ZP}from"ts-pattern";function v(N){let{isStagenet:A}=g.get("envs"),T=g.get("thornodeUrls");return`${ZP({isStagenet:A,type:N}).with({type:"mayachain"},({isStagenet:P})=>P?T.MAYA_STAGENET:T.MAYA).otherwise(({isStagenet:P})=>P?T.THOR_STAGENET:T.THOR)}/${N??"thorchain"}`}function jP(N){let A=N==="mayachain"?"mayaname":"thorname";return`${v(N)}/${A}`}function VP(N="thorchain"){return _.get(`${v(N)}/lastblock`)}function xP(N){return _.get(`${v(N)}/queue`)}function qP(N){return _.get(`${v(N)}/nodes`)}function vP(N){return _.get(`${v(N)}/mimir`)}function tP(N){return _.get(`${v(N)}/inbound_addresses`)}async function AT({type:N,name:A}){try{return await _.get(`${jP(N)}/${A}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:A,owner:"",preferred_asset:""}}}async function KP({type:N,tns:A}){let T=await AT({name:A,type:N});if(!T.preferred_asset||T.preferred_asset===".")return;return q.from({asset:T.preferred_asset,asyncTokenLookup:!0})}function kP(N){return _.get(`${v(N)}/runepool`)}function mP({type:N,thorAddress:A}){return _.get(`${v(N)}/rune_provider/${A}`)}function fP({type:N,address:A}){return _.get(`${v(N)}/tcy_staker/${A}`)}function pP(N){return _.get(`${v(N)}/tcy_stakers`)}function yP({type:N,address:A}){return _.get(`${v(N)}/tcy_claimer/${A}`)}function oP(N){return _.get(`${v(N)}/tcy_claimers`)}var CF={...oN,mayachainMidgard:zA,thorchainMidgard:wA,thornode:CN};
|
|
5
|
-
export{dP as a,PN as b,JN as c,Z as d,QN as e,RT as f,IT as g,BT as h,u as i,iP as j,MN as k,sN as l,aP as m,GT as n,j as o,g as p,_ as q,HA as r,_L as s,c as t,VN as u,JT as v,l as w,WL as x,EL as y,bL as z,nL as A,tL as B,vT as C,SA as D,uA as E,UA as F,UN as G,xN as H,y as I,FN as J,KL as K,kL as L,C as M,m as N,hT as O,q as P,iL as Q,EN as R,VA as S,wN as T,xA as U,qA as V,vA as W,tA as X,RF as Y,IF as Z,BF as _,GF as $,NN as aa,KA as ba,$F as ca,kA as da,YF as ea,MF as fa,mA as ga,ZH as ha,fA as ia,JA as ja,_F as ka,pA as la,yA as ma,DF as na,SF as oa,fN as pa,pN as qa,mH as ra,uF as sa,UF as ta,fH as ua,pH as va,yH as wa,XF as xa,cH as ya,lH as za,rH as Aa,iH as Ba,gF as Ca,sH as Da,eH as Ea,oA as Fa,WF as Ga,NP as Ha,EF as Ia,AP as Ja,TP as Ka,hA as La,dA as Ma,cA as Na,PP as Oa,lA as Pa,rA as Qa,iA as Ra,nF as Sa,wF as Ta,FP as Ua,OP as Va,RP as Wa,zF as Xa,JF as Ya,BP as Za,QF as _a,aA as $a,GP as ab,ZF as bb,NT as cb,CF as db};
|