@swapkit/helpers 5.0.2 → 5.2.0
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 +14 -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/swapKitConfig.d.ts +1 -2
- package/dist/types/modules/swapKitError.d.ts +10 -1
- package/dist/types/types/derivationPath.d.ts +11 -1
- package/dist/types/types/wallet.d.ts +50 -36
- package/dist/types/utils/derivationPath.d.ts +98 -11
- package/dist/types/utils/wallets.d.ts +2 -2
- package/package.json +4 -4
- package/dist/chunk-g60m4sgr.js +0 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @swapkit/helpers
|
|
2
2
|
|
|
3
|
+
## 5.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [`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.
|
|
8
|
+
- Update generated token lists. (via @swapkit/tokens@5.0.4)
|
|
9
|
+
|
|
10
|
+
## 5.1.0
|
|
11
|
+
|
|
12
|
+
### Minor Changes
|
|
13
|
+
|
|
14
|
+
- [#346](https://github.com/swapkit/sdk/pull/346) [`8cca094`](https://github.com/swapkit/sdk/commit/8cca094c278b7d89dff8625b4ced3664f8a51209) Thanks [@towanTG](https://github.com/towanTG)! - Make wallet options and SwapKit error keys extensible through module augmentation plus runtime registration. Extension error codes should use the reserved 80000-89999 range, and wallet registrations are automatically added to the default `SKConfig` wallet list.
|
|
15
|
+
- Update generated token lists. (via @swapkit/tokens@5.0.3)
|
|
16
|
+
|
|
3
17
|
## 5.0.2
|
|
4
18
|
|
|
5
19
|
### Patch Changes
|
package/dist/api/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as
|
|
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 L,Oa as lJ,P as pG,Pa as pJ,Q as oG,Qa as oJ,R as rG,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 Y,aa as ZJ,ab as ZQ,b as LG,ba as $J,c as RG,ca as XJ,d as YG,da as HJ,e as FG,ea as VJ,f as v,fa as jJ,g as xG,ga as _J,h as d,ha as BJ,i as o,ia as LJ,j as WG,ja as RJ,k as qG,ka as YJ,l as E,la as FJ,m as B,ma as xJ,n as IG,na as WJ,o as KG,oa as qJ,p as MG,pa as IJ,q as S,qa as KJ,r as EG,ra as MJ,s as NG,sa as EJ,t as PG,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-g60m4sgr.js";export*from"@swapkit/tokens";export*from"@swapkit/types";var A={average:1,fast:1.5,fastest:2};function N(z="average"){let G=E.get("feeMultipliers");if(G&&G[z]!==void 0)return G[z];return A[z]}function f(z="average"){let G=N(z),Q=10n,J=BigInt(Math.round(G*10));return{denominator:Q,numerator:J}}function zz(z,G="average"){let{numerator:Q,denominator:J}=f(G);return z*Q/J}function Gz(z,G="average",Q=!1){let J=N(G),Z=z*J;return Q?Math.floor(Z):Z}import{Chain as P,EVMChains as y}from"@swapkit/types";function I(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 w([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(y.includes(z)){if(J&&["legacy","account"].includes(J))return[44,60,0,G];if(J==="ledgerLive")return[44,60,G,0,Q];return I(Y[z],{index:G})}if(z===P.Solana){if(J==="account")return[44,501,0,G];return I(Y[z],{index:G})}let Z=z===P.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 I(Y[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(Y).reduce((z,G)=>{return z[G]=w(Y[G]),z},{});import{Chain as b,getChainConfig as c}from"@swapkit/types";function h({liquidityUnits:z,poolUnits:G,runeDepth:Q}){let J=j(z),Z=j(G),$=j(Q),H=J.mul($),V=Z.mul(Z).mul(2),X=Z.mul(J).mul(2),_=J.mul(J),R=Z.mul(Z).mul(Z);return H.mul(V.sub(X).add(_)).div(R)}function m({liquidityUnits:z,poolUnits:G,assetDepth:Q}){let J=j(z),Z=j(G),$=j(Q),H=J.mul($),V=Z.mul(Z).mul(2),X=Z.mul(J).mul(2),_=J.mul(J),R=H.mul(V.sub(X).add(_)),F=Z.mul(Z).mul(Z);return R.div(F)}function Bz({percent:z,runeDepth:G,liquidityUnits:Q,poolUnits:J}){return h({liquidityUnits:Q,poolUnits:J,runeDepth:G}).mul(z)}function Lz({percent:z,assetDepth:G,liquidityUnits:Q,poolUnits:J}){return m({assetDepth:G,liquidityUnits:Q,poolUnits:J}).mul(z)}function j(z){return L.fromBigInt(BigInt(z),c(b.THORChain).baseDecimal)}function u({liquidityUnits:z,poolUnits:G,runeDepth:Q,assetDepth:J}){return{assetAmount:j(J).mul(z).div(G),runeAmount:j(Q).mul(z).div(G)}}function Rz({liquidityUnits:z,poolUnits:G,runeDepth:Q,assetDepth:J,percent:Z}){return Object.fromEntries(Object.entries(u({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 L({decimal:8,value:z}),V=new L({decimal:8,value:Q}),X=new L({decimal:8,value:G}),_=new L({decimal:8,value:Z}),R=new L({decimal:8,value:$}),F=_.mul(V),K=R.mul(H),g=_.mul(R),U=H.mul(V),k=X.mul(F.add(K.add(g.mul(2)))),T=F.add(K.add(U.mul(2))),M=k.div(T),q=j(J).add(M);if(M.getBaseValue("number")===0)return q.div(X).getBaseValue("number");let O=X.add(q);return q.div(O).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=j(Q),$=j(J),H=j(G),V=j(z),X=H.mul(Z).sub($.mul(V)),_=$.mul(V).add(Z.mul($));return Math.abs(X.div(_).getBaseValue("number"))}import{Chain as x}from"@swapkit/types";import{match as l}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 W("POOL+",z)}function Pz({chain:z,symbol:G,address:Q,...J}){let Z=p({chain:z,symbol:G}),$=Q?`:${Q}:`:":";return W(`${"+"}:${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 W(`${"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 W(`${Z}`,Q)}function W(z,{affiliateAddress:G,affiliateBasisPoints:Q}={}){let J=`${z}${G?`:${G}:${Q||0}`:""}`;return J.endsWith(":")?J.slice(0,-1):J}function p({chain:z,symbol:G}){return l(z).with(x.Bitcoin,x.Dogecoin,x.Litecoin,()=>z.slice(0,1).toLowerCase()).with(x.BitcoinCash,()=>"c").otherwise(()=>`${z}.${G}`)}function Tz(z){if(z<0)throw new B({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:z}});return 10+z}function Oz(z){if(z<0)throw new B({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 C}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("METAMASK");if(G)X.push("CTRL");if(Q)X.push("VULTISIG");if(J)X.push("BRAVE");if(Z)X.push("TRUSTWALLET_WEB");if($)X.push("COINBASE_WEB");if(a())X.push("OKX_MOBILE");if(H)X.push("BITGET");if(V)X.push("ONEKEY");return X}async function s(z,G,Q){let J=C(G);try{await D({method:"wallet_switchEthereumChain",params:[{chainId:J.chainIdHex}],provider:z})}catch(Z){if(!Q)throw new B("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 B("wallet_chain_not_supported",{chain:z.join(", "),wallet:Q});let Z=z.filter(($)=>!G.includes($));return S({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}=C(Q);if((await G.getNetwork()).chainId.toString()===Z)return z(...J);try{await s(G,Q)}catch($){throw new B({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 _=n(X,Q,G);return{...H,[V]:_}},{});return{...z,...$}}function i(z,G){return D({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"TRUSTWALLET_WEB";if(G)return"BRAVE";if(J&&Z?.isCoinbaseWallet)return"COINBASE_WEB";if(Q)return"CTRL";if(window?.$onekey?.ethereum)return"ONEKEY";return"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 D({provider:z,params:G,method:Q}){if(!z?.send)throw new B("helpers_not_found_provider");let J=G?Array.isArray(G)?G:[G]:[];return z.send(Q,J)}export{MG as wrapWithThrow,n as wrapMethodWithNetworkSwitch,S as warnOnce,vz as validateTNS,uG as validateIdentifier,I as updateDerivationPath,KJ as toHexTransactionValue,s as switchEVMWalletNetwork,qG as swapKitConfigStore,KG as signWidgetRequest,D as providerRequest,uz as prepareNetworkSwitch,IJ as parseTransactionValue,wG as parseSymbolForAddress,a as okxMobileEnabled,r as listWeb3EVMWallets,cz as isWeb3Detected,qJ as isTransactionValue,vG as isGasAsset,hz as isDetected,SG as initializeRPCUrlsWithFallback,Xz as getWalletFormatFor,bG as getTokenLogoURI,Tz as getTHORNameCost,Rz as getSymmetricWithdraw,u as getSymmetricPoolShare,NG as getRPCUrlSync,PG as getRPCUrl,lG 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,f as getFeeMultiplierAsBigInt,N as getFeeMultiplier,CG as getExplorerTxUrl,DG as getExplorerAddressUrl,Yz as getEstimatedPoolShare,lz as getETHDefaultWallet,pz as getEIP6963Wallets,$z as getDerivationPathFor,AG as getCommonAssetInfo,gG as getChainIdentifier,Bz as getAsymmetricRuneWithdrawAmount,h as getAsymmetricRuneShare,Lz as getAsymmetricAssetWithdrawAmount,m as getAsymmetricAssetShare,fG as getAssetType,hG as formatBigIntToSafeValue,cG as findAssetBy,mz as filterSupportedChains,OG as fetchTokenInfo,w as derivationPathToString,kG as decodeABIString,TG as decodeABIDynamicString,yG as assetFromString,zz as applyFeeMultiplierToBigInt,Gz as applyFeeMultiplier,i as addEVMWalletNetwork,dz as addAccountsChangedCallback,EG as _rpcCache,RG as WarningCodeEnum,o as WalletOption,rG as TxnType,nG as TxnStatus,EJ as TronTransactionSchema,YJ as TransactionSchema,FJ as TransactionDTOSchema,iG as TrackingStatus,tG as TrackingRequestSchema,eG as TrackingRequestQuerySchema,RJ as TrackerResponseSchema,aG as TokenSchema,QJ as TokenDetailsMetadataSchema,gJ as TONTransactionSchema,DJ as TONTransactionMessageSchema,eJ as SwapToResponseSchema,aJ as SwapToRequestSchema,tJ as SwapToAssetSchema,QQ as SwapRouteV2ResponseSchema,L as SwapKitNumber,B as SwapKitError,ZQ as SwapKitApi,nJ as SwapApprovalTransactionSchema,sJ as StellarApprovalTransactionSchema,CJ as StarknetTransactionSchema,E as SKConfig,hJ as RouteQuoteWarningSchema,oG as RouteQuoteTxType,GQ as RouteQuoteProviderErrorSchema,cJ as RouteQuoteMetadataV2Schema,bJ as RouteQuoteMetadataSchema,yJ as RouteQuoteMetadataAssetSchema,fJ as RouteLegWithoutAddressesSchema,AJ as RouteLegSchema,IG as RequestClient,iJ as QuoteV3ResponseSchema,JQ as QuoteV2ResponseSchema,zQ as QuoteRouteV2Response,uJ as QuoteResponseSchema,mJ as QuoteResponseRouteItem,$J as QuoteRequestSchema,YG as ProviderName,sG as ProviderAction,pG as PriorityLabel,ZJ as PriceResponseSchema,XJ as PriceRequestSchema,Y as NetworkDerivationPath,LJ as NearSwapResponseSchema,BJ as NearDepositChannelResultSchema,_J as NearDepositChannelParamsSchema,d as MemoType,WG as LedgerErrorCode,OJ as HyperCoreTypedDataTransactionSchema,vJ as HyperCoreSendAssetTransactionSchema,TJ as HyperCoreSendAssetActionSchema,kJ as HyperCoreEip712TypedDataSchema,UJ as HYPERCORE_USDC_TOKEN_ID,dJ as GasSchema,lJ as GasResponseSchema,xJ as FeesSchema,FG as FeeTypeEnum,v as FeeOption,WJ as EstimatedTimeSchema,LG as ErrorCode,MJ as EVMTransactionSchema,PJ as EVMTransactionDetailsSchema,NJ as EVMTransactionDetailsParamsSchema,Hz as DerivationPath,jJ as DepositChannelResponseSchema,HJ as DepositChannelParamsSchema,A as DEFAULT_FEE_MULTIPLIERS,SJ as CosmosTransactionSchema,UG as CommonAssetStrings,JJ as CoinGeckoMetadataSchema,wJ as ChainflipMetadataSchema,VJ as BrokerDepositChannelParamsSchema,mG as BigIntArithmetics,GJ as AssetValueSchema,dG as AssetValue,oJ as ApproveResponseSchema,pJ as ApproveRequestParams,xG as ApproveMode,rJ as ApprovalTransactionSchema,zJ 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};
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Chain } from "@swapkit/types";
|
|
2
2
|
import type { BalanceResponse, QuoteRequest, QuoteResponse, SwapRouteV2Response, SwapToRequest, SwapToResponse } from "../api";
|
|
3
|
-
import { WalletOption } from "../types";
|
|
4
3
|
import type { FeeMultiplierConfig } from "./feeMultiplier";
|
|
5
4
|
export type V3SwapFlowConfig = {
|
|
6
5
|
/**
|
|
@@ -178,7 +177,7 @@ declare const initialState: {
|
|
|
178
177
|
MAYA_STAGENET: "https://stagenet.mayanode.mayachain.info";
|
|
179
178
|
};
|
|
180
179
|
v3SwapFlow: V3SwapFlowConfig;
|
|
181
|
-
wallets:
|
|
180
|
+
wallets: any[];
|
|
182
181
|
widgetId: string;
|
|
183
182
|
widgetKey: string;
|
|
184
183
|
};
|
|
@@ -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
|
*/
|
|
@@ -536,7 +537,13 @@ declare const errorCodes: {
|
|
|
536
537
|
*/
|
|
537
538
|
readonly not_implemented: 99999;
|
|
538
539
|
};
|
|
539
|
-
|
|
540
|
+
/**
|
|
541
|
+
* Registry for downstream error keys. Augment this interface with number-literal entries; codes 80000-89999 are reserved
|
|
542
|
+
* for extensions, while first-party SwapKit error codes remain outside that range.
|
|
543
|
+
*/
|
|
544
|
+
export interface SwapKitErrorRegistry {
|
|
545
|
+
}
|
|
546
|
+
export type ErrorKeys = keyof typeof errorCodes | (keyof SwapKitErrorRegistry & string);
|
|
540
547
|
export declare class SwapKitError extends Error {
|
|
541
548
|
static ErrorCode: {
|
|
542
549
|
/**
|
|
@@ -1025,6 +1032,7 @@ export declare class SwapKitError extends Error {
|
|
|
1025
1032
|
readonly toolbox_not_supported: 59901;
|
|
1026
1033
|
readonly toolbox_fee_estimation_failed: 59902;
|
|
1027
1034
|
readonly toolbox_sweep_amount_too_low: 59903;
|
|
1035
|
+
readonly toolbox_derivation_slot_unsupported: 59904;
|
|
1028
1036
|
/**
|
|
1029
1037
|
* NEAR Plugin
|
|
1030
1038
|
*/
|
|
@@ -1082,4 +1090,5 @@ export declare class SwapKitError extends Error {
|
|
|
1082
1090
|
info?: Record<string, any>;
|
|
1083
1091
|
}, sourceErrorOrInfo?: any);
|
|
1084
1092
|
}
|
|
1093
|
+
export declare function registerErrorCodes(codes: Record<string, number>): void;
|
|
1085
1094
|
export {};
|
|
@@ -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]>>;
|
|
@@ -42,43 +42,57 @@ export type NetworkParams = {
|
|
|
42
42
|
rpcUrls: string[];
|
|
43
43
|
blockExplorerUrls: string[];
|
|
44
44
|
};
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
45
|
+
/**
|
|
46
|
+
* Registry of supported wallet identifiers. Downstream packages can add identifiers with module augmentation:
|
|
47
|
+
*
|
|
48
|
+
* ```ts
|
|
49
|
+
* declare module "@swapkit/helpers" {
|
|
50
|
+
* interface WalletOptionRegistry {
|
|
51
|
+
* NOIR_WALLET: "NOIR_WALLET";
|
|
52
|
+
* }
|
|
53
|
+
* }
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
export interface WalletOptionRegistry {
|
|
57
|
+
BITGET: "BITGET";
|
|
58
|
+
BRAVE: "BRAVE";
|
|
59
|
+
COINBASE_MOBILE: "COINBASE_MOBILE";
|
|
60
|
+
COINBASE_WEB: "COINBASE_WEB";
|
|
61
|
+
COSMOSTATION: "COSMOSTATION";
|
|
62
|
+
CTRL: "CTRL";
|
|
63
|
+
EIP6963: "EIP6963";
|
|
64
|
+
/** @deprecated Use PASSKEYS instead */
|
|
65
|
+
EXODUS: "EXODUS";
|
|
66
|
+
KEEPKEY: "KEEPKEY";
|
|
67
|
+
KEEPKEY_BEX: "KEEPKEY_BEX";
|
|
68
|
+
KEPLR: "KEPLR";
|
|
69
|
+
KEYSTORE: "KEYSTORE";
|
|
70
|
+
LEAP: "LEAP";
|
|
71
|
+
LEDGER: "LEDGER";
|
|
72
|
+
METAMASK: "METAMASK";
|
|
73
|
+
OKX: "OKX";
|
|
74
|
+
OKX_MOBILE: "OKX_MOBILE";
|
|
75
|
+
ONEKEY: "ONEKEY";
|
|
76
|
+
PASSKEYS: "PASSKEYS";
|
|
77
|
+
PASSKEY_WALLET: "PASSKEY_WALLET";
|
|
78
|
+
PETRA: "PETRA";
|
|
79
|
+
PHANTOM: "PHANTOM";
|
|
80
|
+
POLKADOT_JS: "POLKADOT_JS";
|
|
81
|
+
RADIX_WALLET: "RADIX_WALLET";
|
|
82
|
+
TALISMAN: "TALISMAN";
|
|
83
|
+
TREZOR: "TREZOR";
|
|
84
|
+
TRONLINK: "TRONLINK";
|
|
85
|
+
TRUSTWALLET_WEB: "TRUSTWALLET_WEB";
|
|
86
|
+
VULTISIG: "VULTISIG";
|
|
87
|
+
WALLETCONNECT: "WALLETCONNECT";
|
|
88
|
+
WALLET_SELECTOR: "WALLET_SELECTOR";
|
|
89
|
+
XAMAN: "XAMAN";
|
|
81
90
|
}
|
|
91
|
+
export type WalletOption = WalletOptionRegistry[keyof WalletOptionRegistry];
|
|
92
|
+
export declare const WalletOption: WalletOptionRegistry;
|
|
93
|
+
/** @internal */
|
|
94
|
+
export declare function subscribeWalletOptionRegistration(listener: (walletOption: WalletOption) => void): () => boolean;
|
|
95
|
+
export declare function registerWalletOption<K extends keyof WalletOptionRegistry & string>(key: K, value: WalletOptionRegistry[K]): void;
|
|
82
96
|
export declare enum LedgerErrorCode {
|
|
83
97
|
NoError = 36864,
|
|
84
98
|
LockedDevice = 21781,
|
|
@@ -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 {};
|
|
@@ -2,7 +2,7 @@ import { type Chain } from "@swapkit/types";
|
|
|
2
2
|
import { type EIP6963Provider, type EvmRpcProvider, type NetworkParams, WalletOption } from "../types";
|
|
3
3
|
export declare function isWeb3Detected(): boolean;
|
|
4
4
|
export declare function isDetected(walletOption: WalletOption): boolean;
|
|
5
|
-
export declare function listWeb3EVMWallets():
|
|
5
|
+
export declare function listWeb3EVMWallets(): string[];
|
|
6
6
|
export declare function switchEVMWalletNetwork(provider: EvmRpcProvider, chain: Chain, networkParams?: NetworkParams): Promise<void>;
|
|
7
7
|
export declare function filterSupportedChains<T extends string[]>({ chains, supportedChains, walletType, }: {
|
|
8
8
|
chains: Chain[];
|
|
@@ -18,7 +18,7 @@ export declare function prepareNetworkSwitch<T extends Record<string, unknown>,
|
|
|
18
18
|
}): T & {};
|
|
19
19
|
export declare function addEVMWalletNetwork(provider: EvmRpcProvider, networkParams: NetworkParams): Promise<unknown>;
|
|
20
20
|
export declare function addAccountsChangedCallback(callback: () => void): void;
|
|
21
|
-
export declare function getETHDefaultWallet():
|
|
21
|
+
export declare function getETHDefaultWallet(): "BRAVE" | "COINBASE_WEB" | "CTRL" | "METAMASK" | "ONEKEY" | "TRUSTWALLET_WEB";
|
|
22
22
|
export declare function getEIP6963Wallets(): {
|
|
23
23
|
providers: EIP6963Provider[];
|
|
24
24
|
removeEIP6963EventListener: () => void;
|
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.4",
|
|
7
|
+
"@swapkit/types": "1.1.0"
|
|
8
8
|
},
|
|
9
9
|
"description": "SwapKit - Helpers",
|
|
10
|
-
"devDependencies": { "@swapkit/toolboxes": "5.
|
|
10
|
+
"devDependencies": { "@swapkit/toolboxes": "5.2.0" },
|
|
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.0
|
|
33
|
+
"version": "5.2.0"
|
|
34
34
|
}
|
package/dist/chunk-g60m4sgr.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
var AT=Object.defineProperty;var TT=(N)=>N;function HT(N,A){this[N]=TT.bind(null,A)}var lN=(N,A)=>{for(var T in A)AT(N,T,{get:A[T],enumerable:!0,configurable:!0,set:HT.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 wN,getChainConfig as NH}from"@swapkit/types";import{AllChains as pT,Chain as z,EVMChains as oT,getChainConfig as ON}from"@swapkit/types";import{match as kN}from"ts-pattern";import{Chain as B,EVMChains as jT,getChainConfig as p,UTXOChains as VT}from"@swapkit/types";import{match as FN}from"ts-pattern";import{AllChains as sN,Chain as iN,getChainConfig as BT,MAYAConfig as $T,StagenetChain as _N,StagenetMAYAConfig as eN,StagenetTHORConfig as aN,THORConfig as GT}from"@swapkit/types";import{createStore as YT}from"zustand/vanilla";import{AllChains as LT,getChainConfig as PT}from"@swapkit/types";var dL=LT.reduce((N,A)=>{return N[A]=PT(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 ZN;((H)=>{H.highSlippage="highSlippage";H.highPriceImpact="highPriceImpact";H.insufficientBalance="insufficientBalance"})(ZN||={});var V;((J)=>{J.CHAINFLIP="CHAINFLIP";J.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";J.JUPITER="JUPITER";J.MAYACHAIN="MAYACHAIN";J.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";J.ONEINCH="ONEINCH";J.PANCAKESWAP="PANCAKESWAP";J.SUSHISWAP_V2="SUSHISWAP_V2";J.THORCHAIN="THORCHAIN";J.THORCHAIN_STREAMING="THORCHAIN_STREAMING";J.TRADERJOE_V2="TRADERJOE_V2";J.UNISWAP_V2="UNISWAP_V2";J.UNISWAP_V3="UNISWAP_V3";J.NEAR="NEAR";J.GARDEN="GARDEN";J.OKX="OKX";J.HARBOR="HARBOR";J.FLASHNET="FLASHNET";J.MAYAN="MAYAN"})(V||={});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 FT;((H)=>{H.Average="average";H.Fast="fast";H.Fastest="fastest"})(FT||={});var IT;((T)=>{T.Approve="approve";T.CheckOnly="checkOnly"})(IT||={});var RT;((S)=>{S.NAME_REGISTER="~";S.BOND="BOND";S.DEPOSIT="+";S.LEAVE="LEAVE";S.UNBOND="UNBOND";S.WITHDRAW="-";S.RUNEPOOL_DEPOSIT="POOL+";S.RUNEPOOL_WITHDRAW="POOL-";S.CLAIM_TCY="tcy";S.STAKE_TCY="tcy+";S.UNSTAKE_TCY="tcy-"})(RT||={});var jN;((E)=>{E.BITGET="BITGET";E.BRAVE="BRAVE";E.COINBASE_MOBILE="COINBASE_MOBILE";E.COINBASE_WEB="COINBASE_WEB";E.COSMOSTATION="COSMOSTATION";E.CTRL="CTRL";E.EIP6963="EIP6963";E.EXODUS="EXODUS";E.KEEPKEY="KEEPKEY";E.KEEPKEY_BEX="KEEPKEY_BEX";E.KEPLR="KEPLR";E.KEYSTORE="KEYSTORE";E.LEAP="LEAP";E.LEDGER="LEDGER";E.METAMASK="METAMASK";E.OKX="OKX";E.OKX_MOBILE="OKX_MOBILE";E.ONEKEY="ONEKEY";E.PASSKEYS="PASSKEYS";E.PASSKEY_WALLET="PASSKEY_WALLET";E.PETRA="PETRA";E.PHANTOM="PHANTOM";E.POLKADOT_JS="POLKADOT_JS";E.RADIX_WALLET="RADIX_WALLET";E.TALISMAN="TALISMAN";E.TREZOR="TREZOR";E.TRONLINK="TRONLINK";E.TRUSTWALLET_WEB="TRUSTWALLET_WEB";E.VULTISIG="VULTISIG";E.WALLETCONNECT="WALLETCONNECT";E.WALLET_SELECTOR="WALLET_SELECTOR";E.XAMAN="XAMAN"})(jN||={});var OT;((H)=>{H[H.NoError=36864]="NoError";H[H.LockedDevice=21781]="LockedDevice";H[H.TC_NotFound=65535]="TC_NotFound"})(OT||={});var MT=sN.reduce((N,A)=>{if(!N.THOR_STAGENET)N[_N.Maya]=eN.rpcUrls,N[_N.THORChain]=aN.rpcUrls;return N[A]=BT(A).rpcUrls,N},{}),_T={[iN.THORChain]:GT.nodeUrl,[iN.Maya]:$T.nodeUrl,[_N.THORChain]:aN.nodeUrl,[_N.Maya]:eN.nodeUrl},NA={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:sN,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:MT,thornodeUrls:_T,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(jN),widgetId:"",widgetKey:""},x=YT((N)=>({...NA,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})})),b={get:(N)=>x.getState()[N],getState:x.getState,reinitialize:()=>x.setState(NA),set:(N)=>x.getState().setConfig(N),setApiKey:(N,A)=>x.getState().setApiKey(N,A),setEndpoint:(N,A)=>x.getState().setEndpoint(N,A),setEnv:(N,A)=>x.getState().setEnv(N,A),setFeeMultipliers:(N)=>x.getState().setFeeMultipliers(N),setIntegrationConfig:(N,A)=>x.getState().setIntegrationConfig(N,A),setRequestOptions:(N)=>x.getState().setRequestOptions(N),setRpcUrl:(N,A)=>x.getState().setRpcUrl(N,A),setThornodeUrl:(N,A)=>x.getState().setThornodeUrl(N,A),setWidgetId:(N)=>x.getState().setWidgetId(N),setWidgetKey:(N)=>x.getState().setWidgetKey(N)};var DT={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 VN(N){return JSON.stringify(N,(A,T)=>typeof T==="bigint"?T.toString():T)}class U extends Error{static ErrorCode=DT;errorKey;info;constructor(N,A){let T=typeof N==="string",H=T?N:N.errorKey,L=T?void 0:N.info,I=`${H}${L?`: ${VN(L)}`:""}`;super(I);if(Object.setPrototypeOf(this,U.prototype),this.name="SwapKitError",this.errorKey=H,this.info=L,this.cause=A,A){let O=A instanceof Error?`${A.message}${A.cause?` (${A.cause})`:""}`:VN(A);console.error(`SwapKitError [${H}]: ${O}`)}else if(L)console.error(`SwapKitError [${H}]: ${VN(L)}`)}}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 ET=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 I={data:H?.data,error:H?.error,message:H?.message,status:T.status};throw new U({errorKey:H?.error||"helpers_invalid_response",info:I},I)}let L=H?.routes?.length||H?.result||H?.data&&!H?.error;if(H?.error&&!L){let I={data:H.data,error:H.error,message:H.message,status:T.status};throw new U({errorKey:H.error,info:I},I)}if(H?.providerErrors?.length||H?.error&&L)console.warn("[SwapKit] Partial errors in response:",H.providerErrors||H.error);return H};function DN(N,A={}){return async function(H,L={}){let{searchParams:I,json:O,body:G,headers:M,dynamicHeader:Q,retry:X,timeoutMs:S,abortController:j,onError:w,onSuccess:K,responseHandler:Z,...W}={...A,...L},HN=b.get("requestOptions"),h={...HN.retry,...X},J=!!O||H.endsWith(".json"),YN=bT(H,I),dN=Q?await Q():{},LN=ST(J,{...M,...dN}),c=J?JSON.stringify(O):G,QN;for(let MN=0;MN<=h.maxRetries;MN++){let hN=j||new AbortController,cN=setTimeout(()=>hN.abort(),S||HN.timeoutMs);try{let y=await ET(YN,{...W,body:c,headers:LN,method:N,signal:hN.signal});return clearTimeout(cN),K?.(y)||Z?.(y)||y}catch(y){clearTimeout(cN),QN=y;let NT=y?.cause?.status;if(MN>=h.maxRetries||!UT(y,NT))return w?w(y):Promise.reject(y);await uT(XT(MN,h))}}return w?w(QN):Promise.reject(QN)}}function ST(N,A){return{...A,...N&&{"Content-Type":"application/json"}}}function bT(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 AA(N,A,T,H){let L=`${A}:${T}:${H}`,I=new TextEncoder,O=await crypto.subtle.importKey("raw",I.encode(N),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),G=await crypto.subtle.sign("HMAC",O,I.encode(L));return Array.from(new Uint8Array(G)).map((M)=>M.toString(16).padStart(2,"0")).join("")}import{Chain as u,CosmosChains as PA,EVMChains as FA,getChainConfig as IA,StagenetChains as gT,SubstrateChains as wT,UTXOChains as RA}from"@swapkit/types";import{match as uN}from"ts-pattern";function $P(N,A){try{return N()}catch(T){if(A)throw new U(A,T);return}}var TA=new Set;function l({condition:N,id:A,warning:T}){if(N){if(TA.has(A))return;console.warn(T),TA.add(A)}}function zT(N){return uN(N).with(...FA,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...RA,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...PA,...gT,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(u.Polkadot,u.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(u.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(u.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(u.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(u.Aleo,u.Aptos,u.Tron,u.Radix,u.Stellar,()=>"").with(u.Hype,()=>({type:"meta"})).with(u.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(u.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(u.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new U("helpers_chain_not_supported",{chain:N})})}function HA(N){return uN(N).with(u.Aptos,()=>"/-/healthy").with(u.Aleo,()=>"/mainnet/block/height/latest").with(u.Hype,()=>"/info").with(u.Radix,()=>"/status/network-configuration").with(u.Stellar,()=>"").with(u.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function LA(N,A){try{let T=A.startsWith("wss")?A.replace("wss","https"):A;if(N===u.Aleo||N===u.Stellar)return(await fetch(`${T}${HA(N)}`,{cache:"no-store",method:"GET",signal:AbortSignal.timeout(3000)})).ok;return(await fetch(`${T}${HA(N)}`,{body:JSON.stringify(zT(N)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var xN=new Map,JT=120000;function QT(N){let[A=""]=b.get("rpcUrls")[N];if(!A)throw l({condition:!0,id:"helpers_chain_no_public_or_set_rpc_url",warning:`No public or set RPC URL found for chain. Please ensure you configured rpcUrls for ${N}.`}),new U("helpers_chain_no_public_or_set_rpc_url",{chain:N});let T=xN.get(N);if(T&&Date.now()-T.timestamp<JT)return T.url;return xN.set(N,{timestamp:Date.now(),url:A}),A}async function r(N){let A=QT(N),[,...T]=b.get("rpcUrls")[N];if(await LA(N,A))return A;for(let L of T)if(await LA(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 XP(N){l({condition:!0,id:"initializeRPCUrlsWithFallback",warning:"initializeRPCUrlsWithFallback is deprecated. Use static { rpcUrls, fallbackRpcUrls } SwapKit init config or dynamic SKConfig.setRpcUrl/setFallbackRpcUrl to configure RPC endpoints."})}function UP({chain:N,txHash:A}){let{explorerUrl:T}=IA(N);return uN(N).with(...PA,u.Solana,()=>`${T}/tx/${A.startsWith("0x")?A.slice(2):A}`).with(...FA,...wT,()=>`${T}/tx/${A.startsWith("0x")?A:`0x${A}`}`).with(...RA,u.Radix,u.Tron,()=>`${T}/transaction/${A.toLowerCase()}`).with(u.Near,()=>`${T}/txns/${A}`).with(u.Ripple,()=>`${T}/transactions/${A}`).with(u.Stellar,()=>`${T}/explorer/public/tx/${A}`).with(u.Sui,()=>`${T}/txblock/${A}`).with(u.Cardano,u.Hype,u.Spark,u.Ton,()=>`${T}/tx/${A}`).otherwise(()=>"")}function EP({chain:N,address:A}){let{explorerUrl:T}=IA(N);return uN(N).with(u.Solana,u.Sui,u.Radix,()=>`${T}/account/${A}`).with(u.Stellar,()=>`${T}/explorer/public/account/${A}`).otherwise(()=>`${T}/address/${A}`)}function SP(N){switch(N){case u.THORChain:return`${N}.RUNE`;case u.Cosmos:return`${N}.ATOM`;case u.BinanceSmartChain:return`${N}`;default:return`${N}.${N}`}}import{keccak_256 as ZT}from"@noble/hashes/sha3.js";import{bytesToHex as WT}from"@noble/hashes/utils.js";var OA=/^(0x)?[0-9a-fA-F]{40}$/;function XN(N){if(typeof N!=="string"||!OA.test(N))throw Error(`invalid address: ${N}`);let A=N.toLowerCase().replace(/^0x/,""),T=WT(ZT(new TextEncoder().encode(A))),H=[...A].map((I,O)=>Number.parseInt(T[O]??"0",16)>=8?I.toUpperCase():I).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 BA(N){if(typeof N!=="string"||!OA.test(N))return!1;try{return XN(N),!0}catch{return!1}}var xP=[`${B.Maya}.MAYA`,`${B.Maya}.CACAO`,`${B.Ethereum}.THOR`,`${B.Ethereum}.vTHOR`,`${B.Kujira}.USK`,`${B.Ethereum}.FLIP`,`${B.Radix}.XRD`],YA=[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 r(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 r(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 MA({chain:N,address:A,methodHex:T,id:H}){let L=await r(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 _A(N.replace(/^0x/,""))?.trim()||"UNKNOWN"}catch(A){return console.warn(`Failed to decode ABI string from ${N}: ${A}`),"UNKNOWN"}}function nT(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 MA({address:A,chain:N,id:2,methodHex:"0x313ce567"}).catch((O)=>{return console.warn(`Could not fetch decimals for ${A} on ${N}: ${O.message}`),{result:""}});return nT(L.result,T)}async function KT({chain:N,address:A}){let T=A.toLowerCase();if(T===""||!T.startsWith("0x"))return;let H=await MA({address:A,chain:N,id:1,methodHex:"0x95d89b41"}).catch((I)=>{return console.warn(`Could not fetch symbol for ${A} on ${N}: ${I.message}`),{result:""}});return vT(H.result)}async function $A({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 GA(N){let A=N.match(/.{2}/g)?.map((T)=>Number.parseInt(T,16))??[];return new TextDecoder().decode(new Uint8Array(A))}function _A(N){return FN(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?GA(H):void 0}).when((A)=>A.length===64,(A)=>{let T=A.replace(/(00)+$/,"");if(T.length>0&&T.length%2===0)return GA(T);return}).otherwise(()=>{return})}function DA({chain:N,address:A}){let{baseDecimal:T}=p(N),H={decimals:T,ticker:void 0};return FN(N).with(...jT,async()=>{try{if(!BA(A.replace(/^0X/,"0x")))return H;let[L,I]=await Promise.all([KT({address:A,chain:N}),kT({address:A,chain:N})]);return{decimals:I,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 I=await L.json(),O=Array.isArray(I)?I[0]:I;if(O)return{decimals:O.decimals??T,ticker:O.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 r(B.Tron),[I,O]=await Promise.all([$A({contractAddress:A,functionSelector:"symbol()",rpcUrl:L}),$A({contractAddress:A,functionSelector:"decimals()",rpcUrl:L})]),G=_A(I);return{decimals:I!==void 0&&O?Number(BigInt(`0x${O}`)):T,ticker:G}}catch(L){let I=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Tron token info for ${A}: ${I}`),H}}).with(B.Near,async()=>{if(!A)return H;try{let L=await r(B.Near),I=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(!I.result?.result)throw Error("NEAR ft_metadata returned no result");let O=JSON.parse(new TextDecoder().decode(new Uint8Array(I.result.result)));return{decimals:O?.decimals||T,ticker:O?.symbol}}catch(L){let I=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Near token info for ${A}: ${I}`),H}}).with(B.Radix,async()=>{if(!A)return H;try{let[L,I]=await Promise.all([qT(A),xT(A)]);return{decimals:I,ticker:L}}catch(L){let I=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Radix token info for ${A}: ${I}`),H}}).otherwise(async()=>H)}function uA({chain:N,symbol:A}){return FN(N).with(...YA,()=>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 FN(N.toUpperCase()).with(...YA,(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 qN({chain:N,symbol:A}){if(A.includes("/"))return"Synth";if(A.includes("~"))return"Trade";return FN(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 o=(N)=>{let[A,...T]=N.split("."),H=N.includes("/"),L=T.join("."),I=L?.split("-"),O=I?.length?I.length===1?I[0]:I.slice(0,-1).join("-"):void 0;return{chain:A,symbol:L,synth:H,ticker:O}};function IN(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 qP(N){return`https://storage.googleapis.com/token-list-swapkit-dev/images/${N.toLowerCase()}.png`}async function vP(N){let{loadTokenLists:A}=await import("./tokens.js"),T=await A(void 0,{source:b.get("envs").isDev?"dev":"prod"}),H=Object.values(T).flatMap((I)=>I.tokens);if("identifier"in N)return H.find((I)=>I.identifier===N.identifier)?.identifier;let L=N.contract.toLowerCase();for(let I of H){let{chain:O,symbol:G}=o(I.identifier);if(O!==N.chain)continue;let{address:M}=IN(G,O);if(M?.toLowerCase()===L)return I.identifier}return}import{match as EN}from"ts-pattern";var i=8,mT=10,yT=64;function d({value:N,bigIntDecimal:A=i,decimal:T=i}){if(T===0)return N.toString();let H=N<0n,L=N.toString().substring(H?1:0),I=T-(L.length-1);if(I>0)L="0".repeat(I)+L;let O=L.length-T,G=L.slice(-T);if(Number.parseInt(G[A]||"0",10)>=5){let Q=Number.parseInt(G[A-1]||"0",10);G=`${G.substring(0,A-1)}${Q+1}`}else G=G.substring(0,A);return`${H?"-":""}${L.slice(0,O)}.${G}`.replace(/\.?0*$/,"")}class t{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(N,A){return new t({decimal:A,value:d({bigIntDecimal:A,decimal:A,value:N})})}static shiftDecimals({value:N,from:A,to:T}){return t.fromBigInt(N.getBaseValue("bigint")*C(T)/C(A),T)}constructor(N){let A=vN(N),T=typeof N==="object";this.decimal=T?N.decimal:void 0,this.decimalMultiplier=T&&"decimalMultiplier"in N?N.decimalMultiplier:C(Math.max(XA(SN(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=RN(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 I=this.formatBigIntToSafeValue(this.bigIntValue,L);return EN(N).with("number",()=>Number(I)).with("string",()=>I).with("bigint",()=>{return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}).otherwise(()=>I)}getBaseValue(N,A){let T=this.decimalMultiplier/C(A||this.decimal||i),H=fT(this.bigIntValue,T);return EN(N).with("number",()=>Number(H)).with("string",()=>H.toString()).otherwise(()=>H)}getBigIntValue(N,A){if(!A&&typeof N==="object")return N.bigIntValue;let T=vN(N),H=SN(T);if(H==="0"||H==="undefined")return 0n;return this.#H(H,A)}toSignificant(N=6){let A=this.getValue("string"),[T="",H=""]=A.split("."),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 O=H.replace(/^0+/,"")||"0",G=O.slice(0,N),M=H.length-O.length;return`0.${G.padStart(M+G.length,"0")}`}toFixed(N=6){let A=this.getValue("string"),T=A.startsWith("-"),[H="0",L=""]=(T?A.slice(1):A).split("."),I=H==="0"&&Number.parseInt(L.slice(0,N),10)===0,O=T&&!I?"-":"";if(N===0){if(H==="0"&&!L)return"0";return L&&Number.parseInt(L[0]||"0",10)>=5?`${O}${BigInt(H)+1n}.0`:`${O}${H}.0`}if(!L)return`${O}${H}.${"0".repeat(N)}`;let G=L[N];if(!(G&&Number.parseInt(G,10)>=5))return`${O}${H}.${L.slice(0,N).padEnd(N,"0")}`;let Q=BigInt(L.slice(0,N).padEnd(N,"0"))+1n,X=10n**BigInt(N);if(Q>=X)return`${O}${BigInt(H)+1n}.${"0".repeat(N)}`;return`${O}${H}.${Q.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:I=!0}={}){let O=this.toFixed(T),G=A==="end",[M="0",Q=""]=O.split("."),X=M.replace(/\B(?=(\d{3})+(?!\d))/g,L),S=Q&&Number.parseInt(Q,10)>0,j=S?`${X}${H}${Q}`:X,K=j.length<100&&I&&S?j.replace(/\.?0*$/,""):j;return G?`${K}${N}`:`${N}${K}`}formatBigIntToSafeValue(N,A){let T=A||this.decimal||i,H=Math.max(T,RN(this.decimalMultiplier));return d({bigIntDecimal:T,decimal:H,value:N})}#A(N,...A){let T=this.#T(this,...A),H=RN(this.decimalMultiplier),L=Math.max(T,H),I=Math.min(L+mT,yT),O=C(I),G=A.reduce((X,S)=>{let j=this.getBigIntValue(S,I);return EN(N).with("add",()=>X+j).with("sub",()=>X-j).with("mul",()=>X*j/O).with("div",()=>{if(j===0n)throw RangeError("Division by zero");return X*O/j}).otherwise(()=>X)},this.bigIntValue*O/this.decimalMultiplier),M=d({bigIntDecimal:I,decimal:I,value:G}),Q=this.decimal===void 0?void 0:Math.min(this.decimal,I);return new this.constructor({decimal:Q,decimalMultiplier:C(I),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 EN(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=SN(N)||"0";this.bigIntValue=this.#H(A)}#T(...N){let A=N.map((T)=>{return typeof T==="object"?T.decimal||RN(T.decimalMultiplier):XA(SN(T))}).filter(Boolean);return Math.max(...A,i)}#H(N,A){let T=A?C(A):this.decimalMultiplier,H=RN(T),[L="",I=""]=N.split(".");return BigInt(`${L}${I.padEnd(H,"0")}`)}}var tT=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function SN(N){let T=`${typeof N==="number"?tT.format(N):vN(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,i)}function vN(N){return typeof N==="object"?"getValue"in N?N.getValue("string"):N.value:N}function fT(N,A){if(A===0n)throw Error("Cannot divide by zero");let T=A/2n;return N>=0n&&A>=0n||N<0n&&A<0n?(N+T)/A:(N-T)/A}function C(N){return 10n**BigInt(N)}function RN(N){return N.toString().length-1}function CT(N=""){let A=N.toUpperCase(),T=b.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=[z.Hype,z.Near,z.Ripple,z.Solana,z.Stellar,z.Sui,z.Ton,z.Tron],KN=[z.THORChain,z.Maya],s=new Map,bN=new Map,e=new Map,dT=3600000;function hT(N){let A=e.get(N);if(A?.timestamp&&Date.now()-A.timestamp>dT){e.delete(N);return}return A}function cT(N,A){if(e.size>1000){let T=e.keys().next().value;if(T)e.delete(T)}e.set(N,{...A,timestamp:Date.now()})}class 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:I}){super(typeof N==="object"?N:{decimal:A,value:N});let O=UA(I||`${H}.${L}`);this.type=qN(O),this.tax=T,this.chain=O.chain,this.ticker=O.ticker,this.symbol=O.symbol,this.address=O.address,this.isSynthetic=O.isSynthetic,this.isTradeAsset=O.isTradeAsset,this.isGasAsset=O.isGasAsset,this.chainId=ON(O.chain).chainId}toString({includeSynthProtocol:N}={}){return(this.isSynthetic||this.isTradeAsset)&&!N?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){if(this.isSynthetic)return`${this.chain}.${this.symbol.replace(/\//g,".")}`;if(this.isTradeAsset)return`${this.chain}.${this.symbol.replace(/~/g,"..")}`;let N=this.symbol.replace(/\./g,"__");return`${this.chain}.${N}`}getIconUrl(){return s.get(this.toString())?.logoURI}eqAsset({chain:N,symbol:A}){return this.chain===N&&this.symbol===A}eq(N){return this.eqAsset(N)&&this.eqValue(N)}static fromUrl(N,A=0){let T=N.indexOf(".");if(T===-1)throw new U({errorKey:"helpers_invalid_asset_url",info:{urlAsset:N}});let H=N.slice(0,T),L=N.slice(T+1),I=kN({chain:H,rest:L}).when(({rest:O})=>O.includes(".."),({chain:O,rest:G})=>`${O}.${G.replace(/\.\./g,"~")}`).when(({chain:O,rest:G})=>KN.includes(O)&&G.includes("."),({chain:O,rest:G})=>`${O}.${G.replace(/\./g,"/")}`).otherwise(({chain:O,rest:G})=>`${O}.${G.replace(/__/g,".")}`);return n.from({asset:I,value:A})}static from({value:N=0,fromBaseDecimal:A,asyncTokenLookup:T,...H}){let L=N instanceof t?N.getValue("string"):N,I="address"in H&&"chain"in H,O=sT(H);if(O===null&&T&&I){let{chain:LN,address:c}=H;return rT({address:c,chain:LN,fromBaseDecimal:A,parsedValue:L})}let G=I&&!O?`${H.chain}.UNKNOWN-${H.address}`:O,{identifier:M,decimal:Q}=UN(G),{chain:X,isSynthetic:S,isTradeAsset:j,address:w}=UA(M),{baseDecimal:K}=ON(X),Z=s.get(f.includes(X)?M:M.toUpperCase());if(!Z&&T&&!S&&!j)return(async()=>{let{ticker:LN}=o(M),c=await EA({address:w,chain:X,ticker:LN});return nN({decimal:c.decimals,identifier:c.identifier,value:A?a(BigInt(L),A):L})})();let W=Z?.decimal||Q;l({condition:!W&&!T,id:`assetValue_static_decimal_not_found_${X}`,warning:`Couldn't find static decimal for one or more tokens on ${X} (Using default ${K} decimal as fallback).
|
|
2
|
-
This can result in incorrect calculations and mess with amount sent on transactions.
|
|
3
|
-
You can load static assets by installing @swapkit/tokens package and calling AssetValue.loadStaticAssets()
|
|
4
|
-
or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`});let{decimal:HN,identifier:h,tax:J}=Z||{decimal:W||K,identifier:M},YN=A?a(BigInt(L),A):a(L,HN);return S||j?lT(h,YN):nN({decimal:HN,identifier:h,tax:J,value:YN})}static async loadStaticAssets(N){let{loadTokenLists:A}=await import("@swapkit/tokens"),T=await A(N,{source:b.get("envs").isDev?"dev":"prod"});for(let{tokens:H}of Object.values(T))for(let L of H){let{identifier:I}=L,{chain:O,symbol:G}=o(I),{address:M}=IN(G,O),{baseDecimal:Q}=ON(O),X=f.includes(O)?I:I.toUpperCase(),S="decimals"in L&&L.decimals!==void 0?L.decimals:Q,j="logoURI"in L&&L.logoURI?L.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${I.toLowerCase()}.png`,w={decimal:S,identifier:I,logoURI:j,tax:"tax"in L?L.tax:void 0};if(s.set(X,w),M){let K=f.includes(O)?`${O}:${M}`:`${O}:${M.toUpperCase()}`;bN.set(K,I)}}return!0}static setStaticAssets(N){s.clear(),bN.clear();for(let[A,T]of N.entries()){let{identifier:H}=T,{chain:L,symbol:I}=o(H),{address:O}=IN(I,L),{baseDecimal:G}=ON(L),M=T.chain??L,Q=T.address??O,X=f.includes(M)?H:H.toUpperCase(),S=T.decimals??T.decimal??G,j=T.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${H.toLowerCase()}.png`,w={decimal:S,identifier:X,logoURI:j,tax:T.tax};if(s.set(X,w),Q){let K=f.includes(M)?`${M}:${Q}`:`${M}:${Q.toUpperCase()}`;bN.set(K,H)}}return!0}static get staticAssets(){return s}}function hP(N){let A=n.from({chain:N});return kN(N).with(z.Bitcoin,z.Litecoin,z.BitcoinCash,z.Dash,()=>A.set(0.00010001)).with(z.Dogecoin,()=>A.set(1.00000001)).with(z.Avalanche,z.Ethereum,z.Arbitrum,z.BinanceSmartChain,()=>A.set(0.00000001)).with(z.THORChain,z.Maya,()=>A.set(0)).with(z.Cosmos,z.Kujira,()=>A.set(0.000001)).otherwise(()=>A.set(0.00000001))}async function EA({chain:N,address:A,ticker:T}){let L=f.includes(N)?`${N}:${A||T}`:`${N}:${A||T}`.toUpperCase(),I=hT(L);if(I)return I;if(!A){let{baseDecimal:M}=ON(N);return{decimals:M,identifier:`${N}.${T||"UNKNOWN"}`}}let O=await DA({address:A,chain:N}),G=`${N}.${O.ticker||T||"UNKNOWN"}-${A}`;return l({condition:!!(!O.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 (${O.decimals}).`}),O.ticker&&cT(L,{decimals:O.decimals,identifier:G}),{decimals:O.decimals,identifier:G}}function nN({identifier:N,decimal:A,value:T,tax:H}){return CT(N),new n({decimal:A,identifier:N,tax:H,value:a(T,A)})}function lT(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("~")?"~":"/",[I,O]=H?N.split(".").slice(1).join().split(L):N.split(L);if(!(I&&O))throw new U({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});return new n({decimal:8,identifier:`${T||z.THORChain}.${I}${L}${O}`,value:a(A,8)})}async function rT({address:N,chain:A,fromBaseDecimal:T,parsedValue:H}){let{decimals:L,identifier:I}=await EA({address:N,chain:A}),O=T?a(BigInt(H),T):H;return nN({decimal:L,identifier:I,value:O})}function a(N,A){return typeof N==="bigint"?d({bigIntDecimal:A,decimal:A,value:N}):N}function iT(N){let A=kN(N).when((T)=>("chain"in T)&&T.chain!==void 0,({chain:T})=>T).otherwise((T)=>{let H=o(T.asset);return H.synth?z.THORChain:H.chain});if(!pT.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 sT(N){if(iT(N),"chain"in N){let{chain:L,address:I}=N;if(I){let O=f.includes(L)?`${L}:${I}`:`${L}:${I.toUpperCase()}`,G=bN.get(O);if(G)return G;return null}return L}let{chain:A,symbol:T}=o(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(),I=KN.includes(L),O=T?"~":"/",[G,M=""]=I?H.slice(1).join(".").split(O):N.split(O);if(!(G&&M))throw new U({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});let{ticker:Q,address:X}=SA({chain:G,symbol:M}),S=`${G}${O}${M}`;return{address:X,chain:L,isGasAsset:!1,isSynthetic:A,isTradeAsset:T,symbol:S,ticker:Q}}function aT(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:I}=SA({chain:T,symbol:H}),O;try{O=L&&oT.includes(T)&&XN(L)?XN(L):L}catch{O=L}let G=O?`${I}-${O}`:H;return{address:O,chain:T,isGasAsset:uA({chain:T,symbol:H}),isSynthetic:!1,isTradeAsset:!1,symbol:G,ticker:I}}function UA(N){let A=N.slice(0,14),T=A.includes("/"),H=A.includes("~");if(T||H)return eT(N,T,H);return aT(N)}function SA({symbol:N,chain:A}){let{ticker:T,address:H}=IN(N,A);return{address:H&&!f.includes(A)?H.toLowerCase():H,ticker:T}}class gN extends t{eq(N){return this.eqValue(N)}static fromBigInt(N,A){return new gN({decimal:A,value:d({bigIntDecimal:A,decimal:A,value:N})})}}function bA(N=!0){return N?"https://gateway.liquify.com/chain/thorchain_midgard":"https://midgard.mayachain.info"}function AH(N=!0){let A=bA(N);return N?`${A}/v2/thorname`:`${A}/v2/mayaname`}function TH(N){return function(T){let H=T?`?status=${T}`:"";return _.get(`${N}/v2/pools${H}`)}}function HH(N){return function(T){return _.get(`${N}/v2/pool/${T}`)}}function LH(N){return function(T,H){let L=H?`?period=${H}`:"";return _.get(`${N}/v2/pool/${T}/stats${L}`)}}function PH(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 I=L.toString()?`?${L.toString()}`:"";return _.get(`${N}/v2/history/depths/${T}${I}`)}}function FH(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 OH(N){return function(T){return _.get(`${N}/v2/node/${T}`)}}function BH(N){return function(){return _.get(`${N}/v2/mimir/votes`)}}function $H(N){return function(){return _.get(`${N}/v2/mimir`)}}function GH(N){return function(){return _.get(`${N}/v2/constants`)}}function YH(N){return function(){return _.get(`${N}/v2/stats`)}}function MH(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 _H(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 I=L.toString()?`?${L.toString()}`:"",O=T?`/swaps/${T}`:"/swaps";return _.get(`${N}/v2/history${O}${I}`)}}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 EH(N){return function(T){let H=T?`/${T}`:"";return _.get(`${N}/v2/members${H}`)}}function SH(N){return function(T,H){let L=H?`&asset=${H}`:"";return _.get(`${N}/v2/saver/${T}${L?`?${L.substring(1)}`:""}`)}}function bH(N){return function(T){return _.get(`${N}/v2/savers/${T}`)}}function gH(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 I=L.toString()?`?${L.toString()}`:"",O=T?`/savers/${T}`:"/savers";return _.get(`${N}/v2/history${O}${I}`)}}function wH(N){return function(T){return _.get(`${N}/v2/balance/${T}`)}}function zH(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 JH(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 QH(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 NN({asset:N,value:A}){return n.from({asset:N,fromBaseDecimal:NH(wN.THORChain).baseDecimal,value:A})}function ZH({liquidityPositionGetter:N,isThorchain:A}){return async function(H){let L=await N(H),I=A?"rune":"cacao";return L.pools.map((O)=>({[`${I}Pending`]:NN({asset:"THOR.RUNE",value:O.runePending}),[`${I}RegisteredAddress`]:O.runeAddress,[`${I}Withdrawn`]:NN({asset:"THOR.RUNE",value:O.runeWithdrawn}),[I]:NN({asset:"THOR.RUNE",value:O.runeAdded}),asset:NN({asset:O.pool,value:O.assetAdded}),assetPending:NN({asset:O.pool,value:O.assetPending}),assetRegisteredAddress:O.assetAddress,assetWithdrawn:NN({asset:O.pool,value:O.assetWithdrawn}),dateFirstAdded:O.dateFirstAdded,dateLastAdded:O.dateLastAdded,poolShare:new gN(O.liquidityUnits).div(O.pool)}))}}function gA(N){let A=N===wN.THORChain,T=bA(A),H=AH(A),L=UH(T);return{getActions:XH(T),getBalance:wH(T),getConstants:GH(T),getEarningsHistory:MH(T),getHealth:IH(T),getLiquidityPosition:ZH({isThorchain:A,liquidityPositionGetter:L}),getLiquidityPositionRaw:L,getMembers:EH(T),getMimir:$H(T),getMimirVotes:BH(T),getNameDetails:zH(H),getNamesByAddress:JH(H),getNamesByOwner:QH(H),getNetworkInfo:FH(T),getNode:OH(T),getNodes:RH(T),getPool:HH(T),getPoolDepthHistory:PH(T),getPoolStats:LH(T),getPools:TH(T),getSaverDetails:SH(T),getSavers:bH(T),getSaversHistory:gH(T),getStats:YH(T),getSwapHistory:_H(T),getTVLHistory:DH(T)}}var wA=gA(wN.THORChain),zA=gA(wN.Maya);var oN={};lN(oN,{searchTokens:()=>UL,getTrackerDetails:()=>GL,getTokenListProviders:()=>uL,getTokenList:()=>XL,getTokenApproval:()=>DL,getSwapTo:()=>ZL,getSwapQuote:()=>YL,getRouteWithTx:()=>ML,getPrice:()=>EL,getNearDepositChannel:()=>gL,getGasRate:()=>SL,getChainflipDepositChannel:()=>bL,getChainBalance:()=>_L,SKRequestClient:()=>v});import{EVMChains as pN}from"@swapkit/types";import{match as $L,P as GN}from"ts-pattern";import{Chain as zN,ChainId as BN}from"@swapkit/types";import{array as g,boolean as m,coerce as WA,number as D,object as Y,optional as $,string as F,union as mN,unknown as yN,z as P}from"zod";var jA;((H)=>{H.CHEAPEST="CHEAPEST";H.FASTEST="FASTEST";H.RECOMMENDED="RECOMMENDED"})(jA||={});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 VA;((W)=>{W.approve="approve";W.claim="claim";W.deposit="deposit";W.donate="donate";W.lending="lending";W.lp_action="lp_action";W.native_contract_call="native_contract_call";W.native_send="native_send";W.stake="stake";W.streaming_swap="streaming_swap";W.swap="swap";W.thorname_action="thorname_action";W.token_contract_call="token_contract_call";W.token_transfer="token_transfer";W.unknown="unknown";W.unstake="unstake"})(VA||={});var xA;((w)=>{w.swap="swap";w.aggregation="aggregation";w.addLiquidity="addLiquidity";w.withdrawLiquidity="withdrawLiquidity";w.addSavers="addSavers";w.withdrawSavers="withdrawSavers";w.borrow="borrow";w.repay="repay";w.name="name";w.donate="donate";w.claim="claim";w.stake="stake";w.unstake="unstake"})(xA||={});var qA;((G)=>{G.unknown="unknown";G.not_started="not_started";G.pending="pending";G.swapping="swapping";G.completed="completed";G.refunded="refunded";G.failed="failed"})(qA||={});var vA;((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"})(vA||={});var LF=Y({address:$(F()),chain:P.enum(zN).optional(),chainId:P.enum(BN),coingeckoId:$(F()),decimals:WA.number(),extensions:$(P.looseObject({})),identifier:F(),logoURI:$(F()),name:$(F()),shortCode:$(F()),symbol:$(F()),ticker:F()}),PF=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"}),FF=P.object({forceUpdate:P.string().toLowerCase().transform((N)=>N==="true").pipe(P.boolean()).optional()}),IF=Y({error:F(),message:F()}),AN=Y({address:$(F()),chain:P.enum(zN),decimal:$(D()),isGasAsset:m(),isSynthetic:m(),symbol:F(),tax:$(Y({buy:D(),sell:D()})),ticker:F()}),nA=Y({id:F(),market_cap:D(),name:F(),price_change_24h_usd:D(),price_change_percentage_24h_usd:D(),sparkline_in_7d:g(D()),timestamp:F(),total_volume:D()}).partial(),RF=Y({cg:$(nA),identifier:F(),price_usd:D(),provider:F(),timestamp:D()}),kA=g(Y({cg:$(nA),identifier:F(),price_usd:D(),provider:F(),timestamp:D()}).partial()),OF=Y({affiliate:$(F().describe("Affiliate thorname")),affiliateFee:$(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:$(m().describe("Allow smart contract as recipient")),allowSmartContractSender:$(m().describe("Allow smart contract as sender")),buyAsset:F().describe("Asset to buy"),cfBoost:$(m().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:$(F().describe("Address to send asset to")),disableSecurityChecks:$(m().describe("Disable security checks")),includeTx:$(m().describe("Set to true to include an transaction object (EVM only)")),providers:$(g(F().describe("List of providers to use").refine((N)=>V[N]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:$(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:$(D().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:$(F().describe("Address to send asset from"))}).refine((N)=>N.sellAsset!==N.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),BF=Y({metadata:m(),tokens:g(Y({identifier:F()}))}),KA=Y({destinationAddress:F()}),WH=KA.extend({affiliateFees:g(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()})}),mA=Y({channelId:F(),depositAddress:F()}),JA=KA.extend({affiliateFees:Y({feeBps:D(),nearId:F()}).optional(),buyAsset:F(),sellAmount:F(),sellAsset:F(),slippage:WA.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:yN()}),yA=Y({buyAsset:F(),buyAssetAmount:F(),buyAssetAmountMaxSlippage:F(),deadline:F().optional(),depositAddress:F(),depositAmount:F(),depositAsset:F(),tx:yN()}),jH=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())}),VH=Y({currentStage:F(),inboundConfirmation:D(),inboundObservation:D(),outboundDelay:D(),outboundObservation:D(),streamingSwap:D()}),xH=Y({count:$(D()),interval:$(D()),quantity:$(D()),subSwapsMap:$(g(D()))}),qH=P.object({currentLegIndex:P.optional(P.number()),estimatedTimeToComplete:P.number(),estimates:P.optional(VH),providerDetails:P.optional(P.object({streamingDetails:P.optional(xH)}))}),vH=Y({affiliate:$(AN),liquidity:$(AN),network:$(AN),protocol:$(AN),tax:$(AN)}),nH=Y({affiliate:F(),bps:F(),isReferrer:m()}),kH=Y({affiliate:$(F()),affiliateFees:$(g(nH)),broadcastedAt:$(D()),explorerUrl:$(F()),fees:$(vH),images:$(Y({chain:$(F()),from:$(F()),provider:$(F()),to:$(F())})),provider:$(P.enum(V)),providerAction:P.optional(P.enum(xA)),quoteId:$(F()),wallet:$(F())}),TN=P.object({block:P.number(),chainId:P.enum(BN),finalAddress:P.optional(P.string()),finalAsset:P.optional(AN),finalisedAt:P.number(),fromAddress:P.string(),fromAmount:P.string(),fromAsset:P.string(),hash:P.string(),meta:P.optional(kH),payload:P.optional(jH),status:P.enum(qA),toAddress:P.string(),toAmount:P.string(),toAsset:P.string(),trackingStatus:P.optional(P.enum(vA)),transient:P.optional(qH),type:P.enum(VA)}),tA=TN.extend({legs:P.array(TN)}),GF=TN.extend({legs:g(TN)}),YF=TN.extend({legs:g(TN)}),tN=g(Y({amount:F(),asset:F(),chain:F(),protocol:P.enum(V),type:P.enum(WN)})),fN=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")}),KH=/^(?:0x[0-9a-fA-F]+|[0-9]+)$/;function mH(N){return N===""||KH.test(N)}function MF(N){return N?BigInt(N):0n}function _F(N){let A=typeof N==="bigint"?N:BigInt(N);return A>0n?`0x${A.toString(16)}`:"0x0"}var $N=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"),yH=Y({data:F().describe("Data to send"),from:F().describe("Address of the sender"),to:F().describe("Address of the recipient"),value:$N}),tH=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:$N.optional(),visible:P.boolean()}),fH=g(mN([F(),D(),g(F()),Y({from:F(),value:$N}).describe("Parameters to pass to the contract method")])),DF=Y({approvalSpender:$(F().describe("Address of the spender to approve")),approvalToken:$(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:g(F().describe("Names of the parameters to pass to the contract method")),contractParams:fH}),pH=Y({typeUrl:F("/types.MsgDeposit"),value:Y({coins:g(Y({amount:F(),asset:Y({chain:F(),symbol:F(),synth:m(),ticker:F()})})),memo:F(),signer:F()})}),oH=Y({typeUrl:F("/types.MsgSend"),value:Y({amount:g(Y({amount:F(),denom:F()})),fromAddress:F(),toAddress:F()})}),CH=Y({typeUrl:F(),value:oH.shape.value.or(pH.shape.value)}),dH=Y({amount:g(Y({amount:F(),denom:F()})),gas:F()}),hH=Y({accountNumber:D(),chainId:P.enum(BN),fee:dH,memo:F(),msgs:g(CH),sequence:D()}),cH=P.array(P.object({calldata:P.array(P.string()),contractAddress:P.string(),entrypoint:P.string()})),lH=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")}),rH=P.object({messages:P.array(lH),sendMode:P.number().describe("TON wallet send mode for the whole transfer")}),uF="USDC:0x6d1e7cde53ba9467b783cb7c530ce054",iH=P.looseObject({domain:P.looseObject({chainId:$(mN([D(),F()])),name:$(F()),verifyingContract:$(F()),version:$(F())}),message:P.record(F(),yN()),primaryType:F(),types:P.record(F(),g(P.looseObject({name:F(),type:F()})))}),sH=P.looseObject({amount:F(),destination:F(),destinationDex:F(),fromSubAccount:F(),hyperliquidChain:F(),nonce:D().int(),signatureChainId:F(),sourceDex:F(),token:F(),type:P.literal("sendAsset")}),fA=P.looseObject({action:P.looseObject({type:F()}),submitTo:F(),typedData:iH}),XF=fA.extend({action:sH}),pA=mN([yH,hH,tH,rH,fA,F()]),eH=pA.or(cH),aH=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:fN.optional(),provider:P.enum(V),sellAsset:F().describe("Asset to sell"),slipPercentage:D().describe("Slippage as a percentage"),sourceAddress:F().describe("Source address")}),UF=aH.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),NL=Y({asset:F().describe("Asset name"),image:F().describe("Asset image"),price:D().describe("Price in USD")}),AL=WH,oA=Y({assets:$(g(NL)),maxStreamingQuantity:D().optional(),referrer:F().optional(),streamingInterval:D().optional(),tags:g(P.enum(jA))}),CA=oA.extend({affiliate:$(F()),affiliateFee:$(F()),approvalAddress:$(F().describe("Approval address for swap")),chainflip:AL.optional(),garden:JA.optional(),near:JA.optional(),priceImpact:$(D().describe("Price impact")),referrer:$(F()),txType:$(P.enum(JN))}),dA=g(Y({code:P.enum(ZN),display:F(),tooltip:F().optional()})),TL=Y({buyAmount:F().describe("Buy amount"),buyAmountMaxSlippage:F().describe("Buy amount max slippage"),buyAsset:F().describe("Asset to buy"),fees:$(tN),provider:P.enum(V),sellAmount:F().describe("Sell amount"),sellAsset:F().describe("Asset to sell")}),HL=Y({buyAsset:F().describe("Asset to buy"),destinationAddress:$(F().describe("Destination address")),estimatedTime:$(fN),expectedBuyAmount:F().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:F().describe("Expected Buy amount max slippage"),expiration:$(F().describe("Expiration")),fees:tN,inboundAddress:$(F().describe("Inbound address")),legs:g(TL),memo:$(F().describe("Memo")),meta:CA,providers:g(P.enum(V)),routeId:F().describe("Route ID"),sellAmount:F().describe("Sell amount"),sellAsset:F().describe("Asset to sell"),sourceAddress:$(F().describe("Source address")),targetAddress:$(F().describe("Target address")),totalSlippageBps:D().describe("Total slippage in bps"),tx:$(eH),txType:$(P.enum(JN)),warnings:dA}),hA=Y({error:$(F().describe("Error message")),providerErrors:$(g(Y({errorCode:$(P.enum(PN)),message:$(F()),provider:P.enum(V).optional()}))),quoteId:F().describe("Quote ID"),routes:g(HL)}),cA=P.object({chainId:P.enum(BN),createdAt:P.date(),id:P.number(),unit:P.string(),value:P.string()}),LL=P.array(cA),lA=P.union([cA,LL]),EF=g(Y({chain:P.enum(zN),decimal:D(),identifier:F(),symbol:F(),ticker:F(),value:F()})),SF=P.union([P.object({amount:P.string(),spender:P.string(),tokenIdentifier:P.string(),userWalletAddress:P.string()}),P.object({amount:P.string(),chainId:P.enum(BN),spender:P.string(),tokenContractAddress:P.string(),userWalletAddress:P.string()}),P.object({routeId:P.string()})]),bF=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:$N})),approvedAmount:P.string(),isApproved:P.boolean()}),PL=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:$N.describe("ETH value (always '0' for approvals)")}),FL=P.object({tx:P.string(),txType:P.literal("STELLAR")}),IL=P.union([PL,FL]),ZA=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:tN,provider:P.enum(V),sellAmount:P.string().describe("Sell amount"),sellAsset:P.string().describe("Asset to sell")}),rA=ZA.extend({estimatedTime:P.optional(fN),expiration:P.optional(P.string().describe("Expiration")),legs:P.array(ZA),providers:P.array(P.enum(V)),routeId:P.string().describe("Route ID"),totalSlippageBps:P.number().describe("Total slippage in bps"),warnings:dA}).omit({provider:!0}),iA=P.object({method:P.string(),payload:P.optional(P.unknown()),url:P.string()}),RL=rA.extend({meta:oA,nextActions:P.optional(P.array(iA))}),gF=P.object({error:P.optional(P.string().describe("Error message")),providerErrors:P.optional(P.array(P.object({errorCode:P.optional(P.enum(PN)),message:P.optional(P.string()),provider:P.enum(V).optional()}))),quoteId:P.string().describe("Quote ID"),routes:P.array(RL)}),wF=P.object({providers:P.array(P.enum(V)).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')")}),OL=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(V)).describe("Providers that support this trading pair"),symbol:P.string().describe("Asset symbol"),ticker:P.string().describe("Asset ticker")}),zF=P.object({buyAssets:P.array(OL).describe("List of assets that can be swapped to"),sellAsset:P.string().describe("The input sell asset identifier")}),sA=rA.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:CA,sourceAddress:P.string().describe("Source address"),targetAddress:P.optional(P.string().describe("Target address")),tx:$(pA),txType:P.optional(P.enum(JN))}),BL=P.object({data:P.optional(P.record(P.string(),P.string().optional())),errorCode:P.enum(PN),message:P.string().optional(),provider:P.enum(V).optional()}),JF=P.object({error:P.optional(P.string().describe("Error message")),providerErrors:P.optional(P.array(BL)),quoteId:P.string().describe("Quote ID"),routes:P.array(sA)}),eA=sA.extend({approvalTx:IL.optional().describe("Optional approval transaction required before swap execution"),nextActions:P.optional(P.array(iA)),swapId:P.string().describe("The unique swap ID for tracking")});var v=_.extend({dynamicHeader:async()=>{let N=b.get("widgetId"),A=b.get("widgetKey");if(N&&A&&typeof window<"u"){let H=Math.floor(Date.now()/1000),L=window.location.origin,I=await AA(A,N,L,H);return{Origin:L,"X-Signature":I,"X-Timestamp":H.toString(),"x-widget-id":N}}let{swapKit:T}=b.get("apiKeys");return T?{"x-api-key":T}:{}}});async function GL(N){let A=await v.post(q("/track"),{json:N});try{let T=tA.safeParse(A);if(!T.success)throw new U("api_v2_invalid_response",T.error);return T.data}catch(T){return A}}async function YL(N){let{getQuote:A}=b.get("endpoints");if(A)return A(N);let H=b.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",L=await v.post(q(H),{json:N});if(L.error)throw new U("api_v2_server_error",{message:L.error});try{let I=hA.safeParse(L);if(!I.success)throw new U("api_v2_invalid_response",I.error);return I.data}catch{return L}}async function ML(N){let{getRouteWithTx:A}=b.get("endpoints");if(A)return A(N);let H=b.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",L=await v.post(q(H),{json:N});try{let I=eA.safeParse(L);if(!I.success)throw new U("api_v2_invalid_response",I.error);return I.data}catch(I){return console.error(new U("api_v2_invalid_response",I)),L}}async function _L({chain:N,address:A,scamFilter:T=!0}){let{getBalance:H}=b.get("endpoints");if(H)return H({address:A,chain:N});let L=q(`/balance?chain=${N}&address=${A}`),I=await v.get(L),O=Array.isArray(I)?I:[];return T?QL(O):O}function DL(N){let A=$L(N).with({routeId:GN.string,spender:GN.string},({routeId:T,spender:H})=>q(`/approve?routeId=${T}&sourceAddress=${H}`)).with({assetValue:GN.instanceOf(n),spender:GN.string,userWallet:GN.string},({spender:T,userWallet:H,assetValue:L})=>q(`/approve?tokenIdentifier=${L.toString()}&userWalletAddress=${H}&spender=${T}&amount=${L.getValue("string")}`)).exhaustive();return v.get(A)}function uL(){let N=q("/providers");return v.get(N)}function XL(N){let A=q(`/tokens?provider=${N}`);return v.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 I=q(`/tokens/search?${L.toString()}`);return v.get(I)}async function EL(N){let A=q("/price"),T=await v.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 SL(){let N=q("/gas"),A=await v.get(N);try{let T=lA.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 bL(N){let{destinationAddress:A}=N;if(!A)throw new U("chainflip_broker_invalid_params");let T=b.get("integrations").chainflip?.brokerUrl||q("/chainflip/broker/channel"),H=await v.post(T,{json:N});try{let L=mA.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 gL(N){let{destinationAddress:A}=N;if(!A)throw new U("chainflip_broker_invalid_params");let T=q("/near/channel"),H=await v.post(T,{json:N});try{let L=yA.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 q(N){let{isDev:A,apiUrl:T,devApiUrl:H}=b.get("envs"),{enabled:L,quoteUrl:I,swapUrl:O}=b.get("localMode");if(L&&N){let[M]=N.split("?");if(M==="/quote"||M==="/v3/quote")return`${I}${N}`;if(M==="/swap"||M==="/v3/swap")return`${O}${N}`}return`${A?H:T}${N}`}function wL(N){try{return n.from({asset:N.identifier})}catch{return}}var zL=new Set(["OP.OP"]),JL=/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/im;function QL(N){return N.filter((A)=>{let T=wL(A);if(!T)return!1;if(zL.has(T.toString().toUpperCase()))return!0;return(!pN.includes(T.chain)||T.isGasAsset||!!T.address)&&!JL.test(T.ticker)})}async function ZL(N){let{getSwapTo:A}=b.get("endpoints");if(A)return A(N);let T=new URLSearchParams({sellAsset:N.sellAsset});if(N.providers?.length)for(let O of N.providers)T.append("providers",O);let H=q(`/swapTo?${T.toString()}`),L=await v.get(H);if(!Array.isArray(L))return{buyAssets:[],sellAsset:N.sellAsset};let I=[];for(let O of L)try{let G=n.from({asset:O});I.push({chain:G.chain,identifier:G.toString(),providers:[],symbol:G.symbol,ticker:G.ticker})}catch{}return{buyAssets:I,sellAsset:N.sellAsset}}var CN={};lN(CN,{getThorchainQueue:()=>xL,getTcyStakers:()=>tL,getTcyStaker:()=>yL,getTcyClaimers:()=>pL,getTcyClaimer:()=>fL,getTNSPreferredAsset:()=>kL,getTHORNodeTNSDetails:()=>aA,getRunePoolProviderInfo:()=>mL,getRunePoolInfo:()=>KL,getNodes:()=>qL,getMimirInfo:()=>vL,getLastBlock:()=>VL,getInboundAddresses:()=>nL});import{match as WL}from"ts-pattern";function k(N){let{isStagenet:A}=b.get("envs"),T=b.get("thornodeUrls");return`${WL({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 jL(N){let A=N==="mayachain"?"mayaname":"thorname";return`${k(N)}/${A}`}function VL(N="thorchain"){return _.get(`${k(N)}/lastblock`)}function xL(N){return _.get(`${k(N)}/queue`)}function qL(N){return _.get(`${k(N)}/nodes`)}function vL(N){return _.get(`${k(N)}/mimir`)}function nL(N){return _.get(`${k(N)}/inbound_addresses`)}async function aA({type:N,name:A}){try{return await _.get(`${jL(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 aA({name:A,type:N});if(!T.preferred_asset||T.preferred_asset===".")return;return n.from({asset:T.preferred_asset,asyncTokenLookup:!0})}function KL(N){return _.get(`${k(N)}/runepool`)}function mL({type:N,thorAddress:A}){return _.get(`${k(N)}/rune_provider/${A}`)}function yL({type:N,address:A}){return _.get(`${k(N)}/tcy_staker/${A}`)}function tL(N){return _.get(`${k(N)}/tcy_stakers`)}function fL({type:N,address:A}){return _.get(`${k(N)}/tcy_claimer/${A}`)}function pL(N){return _.get(`${k(N)}/tcy_claimers`)}var tF={...oN,mayachainMidgard:zA,thorchainMidgard:wA,thornode:CN};
|
|
5
|
-
export{dL as a,PN as b,ZN as c,V as d,WN as e,FT as f,IT as g,RT as h,jN as i,OT as j,x as k,b as l,U as m,_ as n,AA as o,$P as p,l as q,xN as r,QT as s,r as t,XP as u,UP as v,EP as w,SP as x,xP as y,vT as z,_A as A,DA as B,uA as C,UN as D,qN as E,o as F,IN as G,qP as H,vP as I,d as J,t as K,CT as L,n as M,hP as N,gN as O,jA as P,JN as Q,VA as R,xA as S,qA as T,vA as U,LF as V,PF as W,FF as X,IF as Y,AN as Z,nA as _,RF as $,kA as aa,OF as ba,BF as ca,KA as da,WH as ea,mA as fa,JA as ga,$F as ha,yA as ia,tA as ja,GF as ka,YF as la,tN as ma,fN as na,mH as oa,MF as pa,_F as qa,yH as ra,tH as sa,fH as ta,DF as ua,hH as va,cH as wa,lH as xa,rH as ya,uF as za,iH as Aa,sH as Ba,fA as Ca,XF as Da,aH as Ea,UF as Fa,NL as Ga,AL as Ha,oA as Ia,CA as Ja,dA as Ka,HL as La,hA as Ma,cA as Na,lA as Oa,SF as Pa,bF as Qa,PL as Ra,FL as Sa,IL as Ta,gF as Ua,wF as Va,OL as Wa,zF as Xa,sA as Ya,BL as Za,JF as _a,eA as $a,tF as ab};
|