@swapkit/helpers 6.2.0 → 6.4.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 CHANGED
@@ -1,5 +1,23 @@
1
1
  # @swapkit/helpers
2
2
 
3
+ ## 6.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#460](https://github.com/swapkit/sdk/pull/460) [`9190931`](https://github.com/swapkit/sdk/commit/9190931bb2c1f911543a22cb8ccc91e3913cfe6c) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - `SwapKitApi` now covers the full limit-order API: `getLimitOrderTokens`, `getLimitOrderQuote`, `buildLimitOrder`, `submitLimitOrder`, `getLimitOrders`, `getLimitOrder`, `buildLimitOrderCancel` and `submitLimitOrderCancel`, with typed responses and `LimitOrderStatus` and `LimitOrderTxType` constants. `getLimitOrderQuote` accepts an optional `providers` list to restrict the quote to those providers. Each call can be overridden through `SKConfig.endpoints`.
8
+ - [#467](https://github.com/swapkit/sdk/pull/467) [`6ddbd12`](https://github.com/swapkit/sdk/commit/6ddbd12b87af88d304aa575518970214ca4516e9) Thanks [@ice-chillios](https://github.com/ice-chillios)! - `getTokenAddress` and `getChecksumAddressFromAsset` now use `isGasAsset`, so `MONAD.MON`, `XLAYER.OKB` and `GNO.xDAI` resolve to the native asset address instead of returning `null` or throwing. Identifiers that repeat the chain name on a chain whose gas asset has another ticker, such as `ARB.ARB` or `BSC.BSC`, no longer resolve to the native asset address. `ContractAddress[Chain.Optimism]` is now the zero address, like every EVM chain except Polygon, so `OP.ETH` resolves to the zero address instead of the OP token contract (`0x4200000000000000000000000000000000000042`). `OP.OP` without an address still resolves to the OP token contract. The Botanix toolbox now targets the Botanix network instead of Sonic.
9
+ - [#474](https://github.com/swapkit/sdk/pull/474) [`f107064`](https://github.com/swapkit/sdk/commit/f10706478e42440912a009b011b92b4e345104f8) Thanks [@ice-chillios](https://github.com/ice-chillios)! - The TON toolbox spaces out and retries its requests to the public Toncenter endpoint, which allows about one request per second without an API key, so TON jetton sales such as TON.USDT are much less likely to fail there. Requests to the chain's default endpoints start at least 1.1 seconds apart, through a queue shared by every toolbox in the process. Waits therefore grow with concurrent TON activity; for servers and other high-volume use, configure a custom TON RPC or a Toncenter API key, which is not spaced out. The endpoint health check is not queued. A request rejected with 429 or a gateway error (502 and above) is sent again after 1, 2 and 4 seconds. A node's 500 answer, such as a rejected message, a timeout and a network failure fail at once. A jetton lookup that the RPC does not answer is reported as `helpers_chain_rpc_connection_failed` instead of `core_swap_contract_not_found`. A toolbox looks up each jetton wallet address only once per jetton and owner.
10
+ - [#464](https://github.com/swapkit/sdk/pull/464) [`c20cc10`](https://github.com/swapkit/sdk/commit/c20cc10b4534c7948dfe4b57f29e07f1b183f1ca) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/tokens@5.0.17)
11
+
12
+ ## 6.3.0
13
+
14
+ ### Minor Changes
15
+
16
+ - [#459](https://github.com/swapkit/sdk/pull/459) [`29bda2c`](https://github.com/swapkit/sdk/commit/29bda2c7a7f69112fc9403c042cb4aee7c2010a5) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Wallets now declare all their signing capabilities per chain in one `signingSupport` map on `createWallet`: `direct` (signs the transaction the API builds for a route), `typedData` (EIP-712) and `btcMessage` (BIP-137), with the names exported as `SigningCapability`. Undeclared capabilities count as unsupported, and each connected chain wallet carries its capabilities as `signing`. Use `walletSupportsDirectSigning(wallet)` to check for direct signing; it understands wallets from both old and new connectors.
17
+ - [#462](https://github.com/swapkit/sdk/pull/462) [`adf132c`](https://github.com/swapkit/sdk/commit/adf132ce1b856153be10f132372cb4fd6cabe7d6) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - EVM wallets wrapped by `prepareNetworkSwitch` now switch to the chain's network before `signTypedData`, as they already do before sending a transaction. A refused or impossible switch fails with `helpers_failed_to_switch_network` before anything is signed. Message signing (`signMessage`) is unchanged.
18
+ - [#457](https://github.com/swapkit/sdk/pull/457) [`59568bc`](https://github.com/swapkit/sdk/commit/59568bcafbe907e7efa3a6ee0eb55a8c2500bac4) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - EVM `signTypedData` now accepts standard EIP-712 payloads that include `EIP712Domain` in `types`, as wallets and backends produce them for `eth_signTypedData_v4`. Such payloads previously threw; callers no longer need to strip `EIP712Domain` before signing. If the declared `EIP712Domain` does not exactly match the fields of `domain` (names, types and canonical order), signing rejects with `toolbox_evm_typed_data_domain_mismatch` instead of signing a different domain. Payloads without it sign exactly as before.
19
+ - [#453](https://github.com/swapkit/sdk/pull/453) [`e8988db`](https://github.com/swapkit/sdk/commit/e8988dbd06040f6b134163e7d9cba1910b9ee711) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/tokens@5.0.16)
20
+
3
21
  ## 6.2.0
4
22
 
5
23
  ### Minor Changes
package/dist/api/index.js CHANGED
@@ -1 +1 @@
1
- import{$ as k,$a as la,Aa as L,Ba as M,Ca as N,Da as O,Ea as P,Fa as Q,Ga as R,Ha as S,Ia as T,Ja as U,Ka as V,La as W,Ma as X,Na as Y,Oa as Z,Pa as _,Qa as aa,R as a,Ra as ba,S as b,Sa as ca,T as c,Ta as da,U as d,Ua as ea,V as e,Va as fa,W as f,Wa as ga,X as g,Xa as ha,Y as h,Ya as ia,Z as i,Za as ja,_ as j,_a as ka,aa as l,ab as ma,ba as m,bb as na,ca as n,cb as oa,da as o,ea as p,fa as q,ga as r,ha as s,ia as t,ja as u,ka as v,la as w,ma as x,na as y,oa as z,pa as A,qa as B,ra as C,sa as D,ta as E,ua as F,va as G,wa as H,xa as I,ya as J,za as K}from"../chunk-d8rmhscp.js";export{j as ApiV2ErrorSchema,da as ApprovalTransactionSchema,ba as ApproveRequestParams,ca as ApproveResponseSchema,k as AssetValueSchema,r as BrokerDepositChannelParamsSchema,U as ChainflipMetadataSchema,l as CoinGeckoMetadataSchema,I as CosmosTransactionSchema,q as DepositChannelParamsSchema,s as DepositChannelResponseSchema,G as EVMTransactionDetailsParamsSchema,H as EVMTransactionDetailsSchema,E as EVMTransactionSchema,A as EstimatedTimeSchema,z as FeesSchema,aa as GasResponseSchema,_ as GasSchema,M as HYPERCORE_USDC_TOKEN_ID,N as HyperCoreEip712TypedDataSchema,O as HyperCoreSendAssetActionSchema,Q as HyperCoreSendAssetTransactionSchema,P as HyperCoreTypedDataTransactionSchema,t as NearDepositChannelParamsSchema,u as NearDepositChannelResultSchema,v as NearSwapResponseSchema,p as PriceRequestSchema,n as PriceResponseSchema,a as PriorityLabel,d as ProviderAction,o as QuoteRequestSchema,Y as QuoteResponseRouteItem,Z as QuoteResponseSchema,ka as QuoteRouteV2Response,ma as QuoteV2ResponseSchema,ga as QuoteV3ResponseSchema,R as RouteLegSchema,S as RouteLegWithoutAddressesSchema,T as RouteQuoteMetadataAssetSchema,V as RouteQuoteMetadataSchema,W as RouteQuoteMetadataV2Schema,la as RouteQuoteProviderErrorSchema,b as RouteQuoteTxType,X as RouteQuoteWarningSchema,J as StarknetTransactionSchema,ea as StellarApprovalTransactionSchema,fa as SwapApprovalTransactionSchema,oa as SwapKitApi,na as SwapRouteV2ResponseSchema,ia as SwapToAssetSchema,ha as SwapToRequestSchema,ja as SwapToResponseSchema,K as TONTransactionMessageSchema,L as TONTransactionSchema,m as TokenDetailsMetadataSchema,g as TokenSchema,w as TrackerResponseSchema,i as TrackingRequestQuerySchema,h as TrackingRequestSchema,f as TrackingStatus,y as TransactionDTOSchema,x as TransactionSchema,F as TronTransactionSchema,e as TxnStatus,c as TxnType,B as isTransactionValue,C as parseTransactionValue,D as toHexTransactionValue};
1
+ import{$ as j,$a as ka,Aa as K,Ba as L,Ca as M,Da as N,Ea as O,Fa as P,Ga as Q,Ha as R,Ia as S,Ja as T,Ka as U,La as V,Ma as W,Na as X,Oa as Y,Pa as Z,Qa as _,Ra as aa,S as a,Sa as ba,T as b,Ta as ca,U as c,Ua as da,V as d,Va as ea,W as e,Wa as fa,X as f,Xa as ga,Y as g,Ya as ha,Z as h,Za as ia,_ as i,_a as ja,aa as k,ab as la,ba as l,bb as ma,ca as m,cb as na,da as n,db as oa,ea as o,eb as pa,fa as p,fb as qa,ga as q,gb as ra,ha as r,hb as sa,ia as s,ib as ta,ja as t,jb as ua,ka as u,kb as va,la as v,lb as wa,ma as w,mb as xa,na as x,nb as ya,oa as y,ob as za,pa as z,pb as Aa,qa as A,qb as Ba,ra as B,rb as Ca,sa as C,sb as Da,ta as D,tb as Ea,ua as E,ub as Fa,va as F,vb as Ga,wa as G,wb as Ha,xa as H,xb as Ia,ya as I,za as J}from"../chunk-8wabqp6d.js";export{j as ApiV2ErrorSchema,da as ApprovalTransactionSchema,ba as ApproveRequestParams,ca as ApproveResponseSchema,k as AssetValueSchema,r as BrokerDepositChannelParamsSchema,U as ChainflipMetadataSchema,l as CoinGeckoMetadataSchema,I as CosmosTransactionSchema,q as DepositChannelParamsSchema,s as DepositChannelResponseSchema,G as EVMTransactionDetailsParamsSchema,H as EVMTransactionDetailsSchema,E as EVMTransactionSchema,A as EstimatedTimeSchema,z as FeesSchema,aa as GasResponseSchema,_ as GasSchema,M as HYPERCORE_USDC_TOKEN_ID,N as HyperCoreEip712TypedDataSchema,O as HyperCoreSendAssetActionSchema,Q as HyperCoreSendAssetTransactionSchema,P as HyperCoreTypedDataTransactionSchema,ya as LimitOrderApprovalTxSchema,ua as LimitOrderBuildRequestSchema,za as LimitOrderBuildResponseSchema,Ga as LimitOrderCancelBuildResponseSchema,Ha as LimitOrderCancelSubmitResponseSchema,Fa as LimitOrderCancelTxSchema,Ea as LimitOrderCancelTypedDataSchema,wa as LimitOrderEVMTransactionSchema,Da as LimitOrderListResponseSchema,ra as LimitOrderQuoteRequestSchema,ta as LimitOrderQuoteResponseSchema,sa as LimitOrderQuoteRouteSchema,Ca as LimitOrderSchema,oa as LimitOrderStatus,Aa as LimitOrderSubmitResponseSchema,qa as LimitOrderTokensResponseSchema,Ba as LimitOrderTxHashSchema,xa as LimitOrderTxMetaSchema,pa as LimitOrderTxType,va as LimitOrderTypedDataSchema,t as NearDepositChannelParamsSchema,u as NearDepositChannelResultSchema,v as NearSwapResponseSchema,p as PriceRequestSchema,n as PriceResponseSchema,a as PriorityLabel,d as ProviderAction,o as QuoteRequestSchema,Y as QuoteResponseRouteItem,Z as QuoteResponseSchema,ka as QuoteRouteV2Response,ma as QuoteV2ResponseSchema,ga as QuoteV3ResponseSchema,R as RouteLegSchema,S as RouteLegWithoutAddressesSchema,T as RouteQuoteMetadataAssetSchema,V as RouteQuoteMetadataSchema,W as RouteQuoteMetadataV2Schema,la as RouteQuoteProviderErrorSchema,b as RouteQuoteTxType,X as RouteQuoteWarningSchema,J as StarknetTransactionSchema,ea as StellarApprovalTransactionSchema,fa as SwapApprovalTransactionSchema,Ia as SwapKitApi,na as SwapRouteV2ResponseSchema,ia as SwapToAssetSchema,ha as SwapToRequestSchema,ja as SwapToResponseSchema,K as TONTransactionMessageSchema,L as TONTransactionSchema,m as TokenDetailsMetadataSchema,g as TokenSchema,w as TrackerResponseSchema,i as TrackingRequestQuerySchema,h as TrackingRequestSchema,f as TrackingStatus,y as TransactionDTOSchema,x as TransactionSchema,F as TronTransactionSchema,e as TxnStatus,c as TxnType,B as isTransactionValue,C as parseTransactionValue,D as toHexTransactionValue};
@@ -0,0 +1,5 @@
1
+ var yn=Object.defineProperty;var bn=(e)=>e;function Sn(e,t){this[e]=bn.bind(null,t)}var nt=(e,t)=>{for(var r in t)yn(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Sn.bind(t,r)})};var rt=((e)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{Chain as Ce,getChainConfig as fr}from"@swapkit/types";import{AllChains as sr,Chain as R,EVMChains as or,getChainConfig as ce}from"@swapkit/types";import{match as Be}from"ts-pattern";import{Chain as u,EVMChains as Wn,getChainConfig as j,UTXOChains as Gn}from"@swapkit/types";import{match as le}from"ts-pattern";import{AllChains as at,Chain as ot,getChainConfig as In,MAYAConfig as Cn,THORConfig as On}from"@swapkit/types";import{createStore as Pn}from"zustand/vanilla";import{AllChains as An,getChainConfig as Tn}from"@swapkit/types";var Rs=Object.freeze(Object.fromEntries(An.map((e)=>[e,Object.freeze(Tn(e).networkDerivationPath)])));var oe;((d)=>{d.unknownError="unknownError";d.test_error="test_error";d.providerDetailsError="providerDetailsError";d.blockHeaderNotFound="blockHeaderNotFound";d.blockHashNotFoundAtHeight="blockHashNotFoundAtHeight";d.blockHashNotFoundAtHash="blockHashNotFoundAtHash";d.txHashMissing="txHashMissing";d.assetValueMissingInfo="assetValueMissingInfo";d.invalidAsset="invalidAsset";d.blockIsRequired="blockIsRequired";d.currentBlockHeaderNotFound="currentBlockHeaderNotFound";d.failedToRetrieveBalance="failedToRetrieveBalance";d.failedToRetrieveBlock="failedToRetrieveBlock";d.failedToRetrieveFees="failedToRetrieveFees";d.notImplementedBCH="notImplementedBCH";d.notImplementedDoge="notImplementedDoge";d.noPoolsFound="noPoolsFound";d.noVaultsFound="noVaultsFound";d.noTxFound="noTxFound";d.noInputCoinFound="noInputCoinFound";d.noBlockDataFound="noBlockDataFound";d.multipleCosmosMessages="multipleCosmosMessages";d.heightOrHashNotProvided="heightOrHashNotProvided";d.unknownDenom="unknownDenom";d.invalidBlockHeight="invalidBlockHeight";d.timestampExtrinsicNoArgumentsForBlock="timestampExtrinsicNoArgumentsForBlock";d.timestampExtrinsicNoTimestampForBlock="timestampExtrinsicNoTimestampForBlock";d.noTimestampExtrinsicForHash="noTimestampExtrinsicForHash";d.timestampExtrinsicNoArgumentsForHash="timestampExtrinsicNoArgumentsForHash";d.txMemoUndefined="txMemoUndefined";d.txMemoIncorrect="txMemoIncorrect";d.txTypeNotFound="txTypeNotFound";d.txNoMessage="txNoMessage";d.txNotFound="txNotFound";d.txReceiptNotFound="txReceiptNotFound";d.txParsingError="txParsingError";d.txLogsParsingError="txLogsParsingError";d.blockNotFound="blockNotFound";d.balanceNotFound="balanceNotFound";d.configError="configError";d.synthSwapDisallowed="synthSwapDisallowed";d.providerQuoteTimeout="providerQuoteTimeout";d.noQuoteResponse="noQuoteResponse";d.noPoolAssetsFound="noPoolAssetsFound";d.noThorchainPools="noThorchainPools";d.noMayachainPools="noMayachainPools";d.noThorchainNetworkInfo="noThorchainNetworkInfo";d.invalidAffiliateFee="invalidAffiliateFee";d.invalidBuyAssetAddress="invalidBuyAssetAddress";d.invalidSellAssetAddress="invalidSellAssetAddress";d.invalidSourceAddress="invalidSourceAddress";d.invalidDestinationAddress="invalidDestinationAddress";d.sourceAddressIsSmartContract="sourceAddressIsSmartContract";d.destinationAddressIsSmartContract="destinationAddressIsSmartContract";d.invalidChainId="invalidChainId";d.unsupportedChainId="unsupportedChainId";d.unsupportedEVMChainId="unsupportedEVMChainId";d.unsupportedMethod="unsupportedMethod";d.unsupportedProvider="unsupportedProvider";d.invalidParamsForMethod="invalidParamsForMethod";d.unsupportedAdapter="unsupportedAdapter";d.noWhitelistTokens="noWhitelistTokens";d.failedFetchGasPrice="failedFetchGasPrice";d.failedToCreateDepositChannel="failedToCreateDepositChannel";d.noProviderDetailsFound="noProviderDetailsFound";d.noTokenListsFound="noTokenListsFound";d.tokenNotFound="tokenNotFound";d.tokenPriceNotFound="tokenPriceNotFound";d.tokenPriceFailedToUpdate="tokenPriceFailedToUpdate";d.swapAmountTooSmall="swapAmountTooSmall";d.legsArrayIsEmpty="legsArrayIsEmpty";d.failedToFetchQuoteForLeg="failedToFetchQuoteForLeg";d.noBlockHeaderFound="noBlockHeaderFound";d.failedToSimulateSwap="failedToSimulateSwap";d.addressScreeningFailed="addressScreeningFailed";d.noLiquidtyProvidersFound="noLiquidtyProvidersFound";d.insufficientLiquidity="insufficientLiquidity";d.noInboundDataFound="noInbounDataFound";d.noInboundAddressesFound="noInboundAddressesFound";d.noInboundAddressFoundForChain="noInboundAddressFoundForChain";d.noLastBlocksFound="noLastBlocksFound";d.noVersionFound="noVersionFound";d.noConstantsFound="noConstantsFound";d.noMimirsFound="noMimirsFound";d.noRoutesFound="noRoutesFound";d.quoteNotFound="quoteNotFound";d.ledgerSignFailed="ledgerSignFailed";d.ledgerWrongPayload="ledgerWrongPayload";d.ledgerFetchSwapFailed="ledgerFetchSwapFailed";d.failedToFetchTx="failedToFetchTx";d.failedBuildTransactionDetails="failedBuildTransactionDetails";d.noLegsForRoute="noLegsForRoute";d.noRouterAddressFound="noRouterAddressFound";d.noAggregatorAddressFound="noAggregatorAddressFound";d.noContractInstanceFound="noContractInstanceFound";d.noContractAddressFound="noContractAddressFound";d.invalidAffiliate="invalidAffiliate";d.thornameAffiliate="thornameAffiliate";d.providerNotfound="No provider found";d.noRecordFound="No Record found";d.slippageTooLow="Slippage too low";d.tradingHalted="tradingHalted";d.noWrappedGasAsset="noWrappedGasAsset";d.aggregatorAddressNotFound="aggregatorAddressNotFound";d.routerAddressNotFound="routerAddressNotFound";d.dummyAddressNotFound="dummyAddressNotFound";d.trackerError="trackerError";d.thorchainPoolUnavailable="thorchainPoolUnavailable";d.noOhlcvDataFound="noOhlcvDataFound";d.noTradingPairs="noTradingPairs";d.noLendingAvailability="noLendingAvailability";d.lendingRepayTooSmall="lendingRepayTooSmall";d.missingState="missingState";d.ledgerSwapNotFound="ledgerSwapNotFound";d.ledgerSwapNotReadyForTracking="ledgerSwapNotReadyForTracking";d.errorEstimatingGas="errorEstimatingGas";d.apiKeyInvalid="apiKeyInvalid";d.apiKeyFailedToUpdate="apiKeyFailedToUpdate";d.apiKeyExpired="apiKeyExpired";d.unauthorized="unauthorized";d.failedToCreateMemo="failedToCreateMemo";d.radixIncorrectInstructions="radixIncorrectInstructions";d.radixTxMissedParam="radixTxMissedParam";d.radixTxMissedAccount="radixTxMissedAccount";d.radixManifestParseError="radixManifestParseError";d.radixManifestBuildError="radixManifestBuildError";d.invalidAddressForChain="invalidAddressForChain";d.riskyAddress="riskyAddress";d.noRoutesToProcess="noRoutesToProcess";d.sellAssetAmountTooSmall="sellAssetAmountTooSmall";d.missingPrivateKey="missingPrivateKey";d.noMemoPriceProtection="noMemoPriceProtection"})(oe||={});var Le;((i)=>{i.highSlippage="highSlippage";i.highPriceImpact="highPriceImpact";i.insufficientBalance="insufficientBalance"})(Le||={});var C;((x)=>{x.CHAINFLIP="CHAINFLIP";x.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";x.JUPITER="JUPITER";x.MAYACHAIN="MAYACHAIN";x.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";x.ONEINCH="ONEINCH";x.PANCAKESWAP="PANCAKESWAP";x.SUSHISWAP_V2="SUSHISWAP_V2";x.THORCHAIN="THORCHAIN";x.THORCHAIN_STREAMING="THORCHAIN_STREAMING";x.TRADERJOE_V2="TRADERJOE_V2";x.UNISWAP_V2="UNISWAP_V2";x.UNISWAP_V3="UNISWAP_V3";x.NEAR="NEAR";x.GARDEN="GARDEN";x.OKX="OKX";x.HARBOR="HARBOR";x.FLASHNET="FLASHNET";x.MAYAN="MAYAN";x.PACTSWAP="PACTSWAP";x.RELAY="RELAY"})(C||={});var _e;((g)=>{g.LIQUIDITY="liquidity";g.NETWORK="network";g.INBOUND="inbound";g.OUTBOUND="outbound";g.AFFILIATE="affiliate";g.TAX="tax";g.PRIORITY="priority";g.SERVICE="service"})(_e||={});var wn;((i)=>{i.Average="average";i.Fast="fast";i.Fastest="fastest"})(wn||={});var xn;((r)=>{r.Approve="approve";r.CheckOnly="checkOnly"})(xn||={});var Rn;((w)=>{w.NAME_REGISTER="~";w.BOND="BOND";w.DEPOSIT="+";w.LEAVE="LEAVE";w.UNBOND="UNBOND";w.WITHDRAW="-";w.RUNEPOOL_DEPOSIT="POOL+";w.RUNEPOOL_WITHDRAW="POOL-";w.CLAIM_TCY="tcy";w.STAKE_TCY="tcy+";w.UNSTAKE_TCY="tcy-"})(Rn||={});var it={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_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_walletconnect_project_id_not_specified:20401,wallet_walletconnect_connection_not_established:20402,wallet_walletconnect_namespace_not_supported:20403,wallet_walletconnect_chain_not_supported:20404,wallet_walletconnect_invalid_method:20405,wallet_walletconnect_method_not_supported:20406,wallet_trezor_failed_to_sign_transaction:20501,wallet_trezor_derivation_path_not_supported:20502,wallet_trezor_failed_to_get_address:20503,wallet_trezor_transport_error:20504,wallet_trezor_method_not_supported:20505,wallet_trezor_failed_to_get_public_key:20506,wallet_talisman_not_enabled:20601,wallet_talisman_not_found:20602,wallet_polkadot_not_found:20701,wallet_radix_not_found:20801,wallet_radix_transaction_failed:20802,wallet_radix_invalid_manifest:20803,wallet_radix_method_not_supported:20804,wallet_radix_no_account:20805,wallet_keepkey_not_found:20901,wallet_keepkey_asset_not_defined:20902,wallet_keepkey_contract_address_not_provided:20903,wallet_keepkey_send_transaction_no_address:20904,wallet_keepkey_derivation_path_error:20905,wallet_keepkey_signing_error:20906,wallet_keepkey_transport_error:20907,wallet_keepkey_unsupported_chain:20908,wallet_keepkey_invalid_response:20909,wallet_keepkey_chain_not_supported:20910,wallet_keepkey_signer_not_found:20911,wallet_keepkey_no_accounts:20912,wallet_keepkey_method_not_supported:20913,wallet_keepkey_invalid_params:20914,wallet_keepkey_config_not_found:20915,wallet_keepkey_no_provider:20916,wallet_keepkey_account_not_found:20917,wallet_keepkey_failed_to_get_public_key:20918,wallet_bitkeep_not_found:21001,wallet_bitkeep_failed_to_switch_network:21002,wallet_bitkeep_no_accounts:21003,wallet_passkeys_sign_transaction_error:21101,wallet_passkeys_not_found:21102,wallet_passkeys_no_address:21103,wallet_passkeys_request_canceled:21104,wallet_passkeys_signature_canceled:21105,wallet_passkeys_failed_to_switch_network:21106,wallet_passkeys_chain_not_supported:21107,wallet_passkeys_instance_missing:21108,wallet_onekey_not_found:21201,wallet_onekey_sign_transaction_error:21202,wallet_okx_not_found:21301,wallet_okx_chain_not_supported:21302,wallet_okx_failed_to_switch_network:21303,wallet_okx_no_accounts:21304,wallet_keplr_not_found:21401,wallet_keplr_chain_not_supported:21402,wallet_keplr_signer_not_found:21403,wallet_keplr_no_accounts:21404,wallet_cosmostation_not_found:21501,wallet_cosmostation_chain_not_supported:21502,wallet_cosmostation_evm_provider_not_found:21503,wallet_cosmostation_keplr_provider_not_found:21504,wallet_cosmostation_no_accounts:21505,wallet_cosmostation_no_evm_accounts:21506,wallet_cosmostation_no_evm_address:21507,wallet_cosmostation_signer_not_found:21508,wallet_passkey_not_supported:21601,wallet_passkey_connection_failed:21602,wallet_coinbase_not_found:21701,wallet_coinbase_chain_not_supported:21702,wallet_coinbase_method_not_supported:21703,wallet_coinbase_no_accounts:21704,wallet_evm_extensions_failed_to_switch_network:21801,wallet_evm_extensions_no_provider:21802,wallet_evm_extensions_not_found:21803,wallet_keystore_invalid_password:21901,wallet_keystore_unsupported_version:21902,wallet_keystore_invalid_word_count:21903,wallet_near_extensions_failed_to_switch_network:22001,wallet_near_extensions_no_provider:22002,wallet_near_extensions_not_found:22003,wallet_near_method_not_supported:22004,wallet_petra_not_found:22201,wallet_vultisig_not_found:22101,wallet_vultisig_contract_address_not_provided:22102,wallet_vultisig_asset_not_defined:22103,wallet_vultisig_send_transaction_no_address:22104,wallet_xaman_not_configured:23001,wallet_xaman_not_connected:23002,wallet_xaman_auth_failed:23003,wallet_xaman_connection_failed:23004,wallet_xaman_transaction_failed:23005,wallet_xaman_monitoring_failed:23006,wallet_tronlink_request_accounts_failed:24001,wallet_tronlink_locked:24002,chainflip_channel_error:30001,chainflip_unknown_asset:30002,chainflip_broker_invalid_params:30101,chainflip_broker_recipient_error:30102,chainflip_broker_register:30103,chainflip_broker_tx_error:30104,chainflip_broker_withdraw:30105,chainflip_broker_fund_only_flip_supported:30106,chainflip_broker_fund_invalid_address:30107,thorchain_chain_halted:40001,thorchain_trading_halted:40002,thorchain_asset_is_not_tcy:40003,thorchain_swapin_router_required:40101,thorchain_swapin_vault_required:40102,thorchain_swapin_memo_required:40103,thorchain_swapin_token_required:40104,thorchain_preferred_asset_payout_required:40105,toolbox_cosmos_account_not_found:50101,toolbox_cosmos_invalid_fee:50102,toolbox_cosmos_invalid_params:50103,toolbox_cosmos_no_signer:50104,toolbox_cosmos_not_supported:50105,toolbox_cosmos_signer_not_defined:50106,toolbox_cosmos_validate_address_prefix_not_found:50107,toolbox_cosmos_verify_signature_no_pubkey:50108,toolbox_evm_error_estimating_gas_limit:50201,toolbox_evm_error_sending_transaction:50202,toolbox_evm_gas_estimation_error:50203,toolbox_evm_invalid_gas_asset_address:50204,toolbox_evm_invalid_params:50205,toolbox_evm_invalid_transaction:50206,toolbox_evm_no_abi_fragment:50207,toolbox_evm_no_contract_address:50208,toolbox_evm_no_fee_data:50209,toolbox_evm_no_from_address:50210,toolbox_evm_no_gas_price:50211,toolbox_evm_no_signer_address:50212,toolbox_evm_no_signer:50213,toolbox_evm_no_to_address:50214,toolbox_evm_not_supported:50215,toolbox_evm_provider_not_eip1193_compatible:50216,toolbox_evm_invalid_eip7702_authorization:50217,toolbox_evm_nonce_conflict:50218,toolbox_evm_tx_already_known:50219,toolbox_evm_typed_data_domain_mismatch:50220,toolbox_utxo_api_error:50301,toolbox_utxo_broadcast_failed:50302,toolbox_utxo_insufficient_balance:50303,toolbox_utxo_invalid_address:50304,toolbox_utxo_invalid_params:50305,toolbox_utxo_invalid_transaction:50306,toolbox_utxo_no_signer:50307,toolbox_utxo_not_supported:50308,toolbox_utxo_tx_not_found:50309,toolbox_utxo_rbf_not_supported:50310,toolbox_utxo_tx_not_replaceable:50311,toolbox_utxo_tx_already_confirmed:50312,toolbox_utxo_rbf_fee_too_low:50313,toolbox_utxo_rbf_insufficient_change:50314,toolbox_utxo_unsupported_script_type:50315,toolbox_solana_no_signer:50401,toolbox_solana_insufficient_balance:50402,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_lightspark_missing_credentials:91301,toolbox_lightspark_invalid_invoice:91302,toolbox_lightspark_invoice_amount_mismatch:91303,toolbox_lightspark_invoice_destination_mismatch:91304,toolbox_lightspark_invoice_expired:91305,toolbox_lightspark_invoice_already_settled:91306,toolbox_lightspark_fee_limit_exceeded:91307,toolbox_lightspark_invalid_params:91308,toolbox_lightspark_api_error:91309,toolbox_lightspark_invalid_amount:91310,toolbox_lightspark_invalid_destination:91311,toolbox_lightspark_network_mismatch:91312,toolbox_lightspark_signing_key_unavailable:91313,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,plugin_swapkit_limit_order_invalid_build:43005,plugin_swapkit_limit_order_unsupported_sign_shape:43006,plugin_swapkit_limit_order_unsupported_cancel_shape:43007,plugin_swapkit_limit_order_wallet_cannot_sign:43008,plugin_swapkit_limit_order_no_signable_provider:43009,plugin_swapkit_limit_order_submit_failed:43010,plugin_swapkit_limit_order_cancel_submit_failed:43011,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 Ee(e){return JSON.stringify(e,(t,r)=>typeof r==="bigint"?r.toString():r)}class b extends Error{static ErrorCode=it;errorKey;info;constructor(e,t){let r=typeof e==="string",i=r?e:e.errorKey,s=r?void 0:e.info,a=`${i}${s?`: ${Ee(s)}`:""}`;super(a);if(Object.setPrototypeOf(this,b.prototype),this.name="SwapKitError",this.errorKey=i,this.info=s,this.cause=t,t){let l=t instanceof Error?`${t.message}${t.cause?` (${t.cause})`:""}`:Ee(t);console.error(`SwapKitError [${i}]: ${l}`)}else if(s)console.error(`SwapKitError [${i}]: ${Ee(s)}`)}}function Os(e){let t=it;for(let[r,i]of Object.entries(e)){if(Object.hasOwn(t,r)){if(t[r]===i)continue;throw new b({errorKey:"helpers_invalid_params",info:{code:i,existingCode:t[r],key:r}})}let s=Object.keys(t).find((a)=>t[a]===i);if(s)throw new b({errorKey:"helpers_invalid_params",info:{code:i,existingKey:s,key:r}});t[r]=i}}var he={BITGET:"BITGET",BRAVE:"BRAVE",COINBASE_MOBILE:"COINBASE_MOBILE",COINBASE_WEB:"COINBASE_WEB",COSMOSTATION:"COSMOSTATION",EIP6963:"EIP6963",EXODUS:"EXODUS",KEEPKEY:"KEEPKEY",KEEPKEY_BEX:"KEEPKEY_BEX",KEPLR:"KEPLR",KEYSTORE:"KEYSTORE",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"},Ne=new Set;function st(e){return Ne.add(e),()=>Ne.delete(e)}function Ls(e,t){let r=he;if(Object.hasOwn(r,e)){if(r[e]===t)return;throw new b({errorKey:"helpers_invalid_params",info:{existingValue:r[e],key:e,value:t}})}r[e]=t;for(let i of Ne)i(t)}var vn;((i)=>{i[i.NoError=36864]="NoError";i[i.LockedDevice=21781]="LockedDevice";i[i.TC_NotFound=65535]="TC_NotFound"})(vn||={});var Es={BtcMessage:"btcMessage",Direct:"direct",TypedData:"typedData"};var kn=at.reduce((e,t)=>(e[t]=In(t).rpcUrls,e),{}),Ln={[ot.THORChain]:On.nodeUrl,[ot.Maya]:Cn.nodeUrl},lt={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:at,endpoints:{},envs:{apiUrl:"https://api.swapkit.dev",devApiUrl:"https://dev-api.swapkit.dev",isDev:!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:kn,thornodeUrls:Ln,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(he),widgetId:"",widgetKey:""},L=Pn((e)=>({...lt,setApiKey:(t,r)=>e((i)=>({apiKeys:{...i.apiKeys,[t]:r}})),setConfig:(t)=>e((r)=>({apiKeys:{...r.apiKeys,...t?.apiKeys},chains:r.chains.concat(t?.chains||[]),endpoints:{...r.endpoints,...t?.endpoints},envs:{...r.envs,...t?.envs},feeMultipliers:t?.feeMultipliers||r.feeMultipliers,integrations:{...r.integrations,...t?.integrations},localMode:{...r.localMode,...t?.localMode},rpcUrls:{...r.rpcUrls,...t?.rpcUrls},thornodeUrls:{...r.thornodeUrls,...t?.thornodeUrls},v3SwapFlow:{...r.v3SwapFlow,...t?.v3SwapFlow},wallets:r.wallets.concat(t?.wallets||[]),widgetId:t?.widgetId||r.widgetId,widgetKey:t?.widgetKey||r.widgetKey})),setEndpoint:(t,r)=>e((i)=>({endpoints:{...i.endpoints,[t]:r}})),setEnv:(t,r)=>e((i)=>({envs:{...i.envs,[t]:r}})),setFeeMultipliers:(t)=>e(()=>({feeMultipliers:t})),setIntegrationConfig:(t,r)=>e((i)=>({integrations:{...i.integrations,[t]:r}})),setRequestOptions:(t)=>e((r)=>({requestOptions:{retry:{...r.requestOptions.retry,...t.retry},timeoutMs:t.timeoutMs||r.requestOptions.timeoutMs}})),setRpcUrl:(t,r)=>e((i)=>({rpcUrls:{...i.rpcUrls,[t]:r}})),setThornodeUrl:(t,r)=>e((i)=>({thornodeUrls:{...i.thornodeUrls,[t]:r}})),setWidgetId:(t)=>e({widgetId:t}),setWidgetKey:(t)=>e({widgetKey:t})}));st((e)=>{L.setState((t)=>t.wallets.includes(e)?t:{wallets:[...t.wallets,e]})});var A={get:(e)=>L.getState()[e],getState:L.getState,reinitialize:()=>L.setState({...lt,wallets:Object.values(he)}),set:(e)=>L.getState().setConfig(e),setApiKey:(e,t)=>L.getState().setApiKey(e,t),setEndpoint:(e,t)=>L.getState().setEndpoint(e,t),setEnv:(e,t)=>L.getState().setEnv(e,t),setFeeMultipliers:(e)=>L.getState().setFeeMultipliers(e),setIntegrationConfig:(e,t)=>L.getState().setIntegrationConfig(e,t),setRequestOptions:(e)=>L.getState().setRequestOptions(e),setRpcUrl:(e,t)=>L.getState().setRpcUrl(e,t),setThornodeUrl:(e,t)=>L.getState().setThornodeUrl(e,t),setWidgetId:(e)=>L.getState().setWidgetId(e),setWidgetKey:(e)=>L.getState().setWidgetKey(e)};var En=(e)=>new Promise((t)=>setTimeout(t,e)),Nn=(e,{baseDelay:t,backoffMultiplier:r,maxDelay:i})=>Math.min(t*r**e,i);function Dn(e,t){if(e instanceof Error&&e.name==="AbortError")return!0;if(e instanceof TypeError)return!0;if(t===429)return!0;if(t&&t>=500&&t<600)return!0;return!1}var Mn=async(e,t)=>{let r=await fetch(e,t),i;try{i=await r.json()}catch{if(!r.ok)throw new b({errorKey:"helpers_invalid_response",info:{status:r.status,statusText:r.statusText}},{status:r.status,statusText:r.statusText});return{}}if(!r.ok){let a={data:i?.data,error:i?.error,message:i?.message,status:r.status};throw new b({errorKey:i?.error||"helpers_invalid_response",info:a},a)}let s=i?.routes?.length||i?.result||i?.data&&!i?.error;if(i?.error&&!s){let a={data:i.data,error:i.error,message:i.message,status:r.status};throw new b({errorKey:i.error,info:a},a)}if(i?.providerErrors?.length||i?.error&&s)console.warn("[SwapKit] Partial errors in response:",i.providerErrors||i.error);return i};function fe(e,t={}){return async function(i,s={}){let{searchParams:a,json:l,body:p,headers:g,dynamicHeader:S,retry:y,timeoutMs:w,abortController:E,onError:T,onSuccess:M,...k}={...t,...s},I=A.get("requestOptions"),Q={...I.retry,...y},ue=!!l||i.endsWith(".json"),me=Hn(i,a),Ze=S?await S():{},x=Vn(ue,{...g,...Ze}),X=ue?JSON.stringify(l):p,ke;for(let ge=0;ge<=Q.maxRetries;ge++){let et=E||new AbortController,tt=setTimeout(()=>et.abort(),w||I.timeoutMs);try{let G=await Mn(me,{...k,body:X,headers:x,method:e,signal:et.signal});return clearTimeout(tt),M?.(G)||G}catch(G){clearTimeout(tt),ke=G;let fn=G?.cause?.status;if(ge>=Q.maxRetries||!Dn(G,fn))return T?T(G):Promise.reject(G);await En(Nn(ge,Q))}}return T?T(ke):Promise.reject(ke)}}function Vn(e,t){return{...t,...e&&{"Content-Type":"application/json"}}}function Hn(e,t){let r=new URL(e);if(t)r.search=new URLSearchParams(t).toString();return r.toString()}var _={extend:(e)=>({extend:(t)=>_.extend({...e,...t}),get:fe("GET",e),post:fe("POST",e)}),get:fe("GET"),post:fe("POST")};async function dt(e,t,r,i){let s=`${t}:${r}:${i}`,a=new TextEncoder,l=await crypto.subtle.importKey("raw",a.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),p=await crypto.subtle.sign("HMAC",l,a.encode(s));return Array.from(new Uint8Array(p)).map((g)=>g.toString(16).padStart(2,"0")).join("")}import{Chain as f,CosmosChains as gt,EVMChains as _t,getChainConfig as ht,SubstrateChains as Un,UTXOChains as ft}from"@swapkit/types";import{match as ye}from"ts-pattern";function zs(e,t){try{return e()}catch(r){if(t)throw new b(t,r);return}}var ct=new Set;function ae({condition:e,id:t,warning:r}){if(e){if(ct.has(t))return;console.warn(r),ct.add(t)}}function Bn(e){return ye(e).with(..._t,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...ft,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...gt,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(f.Polkadot,f.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(f.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(f.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(f.Ton,()=>({id:1,jsonrpc:"2.0",method:"getMasterchainInfo",params:{}})).with(f.Aleo,f.Aptos,f.Tron,f.Radix,f.Stellar,()=>"").with(f.Hype,()=>({type:"meta"})).with(f.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(f.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(f.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new b("helpers_chain_not_supported",{chain:e})})}function pt(e){return ye(e).with(f.Aptos,()=>"/-/healthy").with(f.Aleo,()=>"/mainnet/block/height/latest").with(f.Hype,()=>"/info").with(f.Radix,()=>"/status/network-configuration").with(f.Stellar,()=>"").with(f.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}function ut(e){if(e.ok)return"up";return e.status===429?"rateLimited":"down"}async function mt(e,t){try{let r=t.startsWith("wss")?t.replace("wss","https"):t;if(e===f.Aleo||e===f.Stellar){let s=await fetch(`${r}${pt(e)}`,{cache:"no-store",method:"GET",signal:AbortSignal.timeout(3000)});return ut(s)}let i=await fetch(`${r}${pt(e)}`,{body:JSON.stringify(Bn(e)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)});return ut(i)}catch{return"down"}}var De=new Map,$n=120000;function Fn(e){let[t=""]=A.get("rpcUrls")[e];if(!t)throw ae({condition:!0,id:"helpers_chain_no_public_or_set_rpc_url",warning:`No public or set RPC URL found for chain. Please ensure you configured rpcUrls for ${e}.`}),new b("helpers_chain_no_public_or_set_rpc_url",{chain:e});let r=De.get(e);if(r&&Date.now()-r.timestamp<$n)return r.url;return De.set(e,{timestamp:Date.now(),url:t}),t}async function J(e,{allowRateLimited:t=!1}={}){let r=Fn(e),[,...i]=A.get("rpcUrls")[e],s=await mt(e,r);if(s==="up")return r;let a=s==="rateLimited"?r:void 0;for(let l of i){let p=await mt(e,l);if(p==="up")return De.set(e,{timestamp:Date.now(),url:l}),l;a??=p==="rateLimited"?l:void 0}if(t&&a)return a;throw new b("helpers_chain_rpc_connection_failed",{chain:e,fallbackUrls:i,primaryRpcUrl:r})}function no({chain:e,txHash:t}){let{explorerUrl:r}=ht(e);return ye(e).with(...gt,f.Solana,()=>`${r}/tx/${t.startsWith("0x")?t.slice(2):t}`).with(..._t,...Un,()=>`${r}/tx/${t.startsWith("0x")?t:`0x${t}`}`).with(...ft,f.Radix,f.Tron,()=>`${r}/transaction/${t.toLowerCase()}`).with(f.Near,()=>`${r}/txns/${t}`).with(f.Ripple,()=>`${r}/transactions/${t}`).with(f.Stellar,()=>`${r}/explorer/public/tx/${t}`).with(f.Sui,()=>`${r}/txblock/${t}`).with(f.Cardano,f.Hype,f.Spark,f.Ton,()=>`${r}/tx/${t}`).otherwise(()=>"")}function ro({chain:e,address:t}){let{explorerUrl:r}=ht(e);return ye(e).with(f.Solana,f.Sui,f.Radix,()=>`${r}/account/${t}`).with(f.Stellar,()=>`${r}/explorer/public/account/${t}`).otherwise(()=>`${r}/address/${t}`)}function io(e){switch(e){case f.THORChain:return`${e}.RUNE`;case f.Cosmos:return`${e}.ATOM`;case f.BinanceSmartChain:return`${e}`;default:return`${e}.${e}`}}import{keccak_256 as Kn}from"@noble/hashes/sha3.js";import{bytesToHex as qn}from"@noble/hashes/utils.js";var yt=/^(0x)?[0-9a-fA-F]{40}$/;function be(e){if(typeof e!=="string"||!yt.test(e))throw Error(`invalid address: ${e}`);let t=e.toLowerCase().replace(/^0x/,""),r=qn(Kn(new TextEncoder().encode(t))),i=[...t].map((a,l)=>Number.parseInt(r[l]??"0",16)>=8?a.toUpperCase():a).join(""),s=e.replace(/^0x/,"");if(/[A-F]/.test(s)&&/[a-f]/.test(s)&&s!==i)throw Error(`bad address checksum: ${e}`);return`0x${i}`}function bt(e){if(typeof e!=="string"||!yt.test(e))return!1;try{return be(e),!0}catch{return!1}}var ho=[`${u.Maya}.MAYA`,`${u.Maya}.CACAO`,`${u.Ethereum}.THOR`,`${u.Ethereum}.vTHOR`,`${u.Kujira}.USK`,`${u.Ethereum}.FLIP`,`${u.Radix}.XRD`],jn=[u.Arbitrum,u.Aurora,u.Base,u.Ethereum,u.Optimism,u.Robinhood];async function Yn(e){let{baseDecimal:t}=j(u.Radix);try{let r=await J(u.Radix),{manager:i}=await _.post(`${r}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:e}),headers:{Accept:"*/*","Content-Type":"application/json"}});return i?.divisibility?.value?.divisibility}catch(r){let i=r instanceof Error?r.message:String(r);return console.warn(`Failed to fetch Radix asset decimals for ${e}: ${i}`),t}}async function zn(e){try{let t=await J(u.Radix);return(await _.post(`${t}/state/entity/details`,{body:JSON.stringify({addresses:[e],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((s)=>s.key==="symbol")?.value.typed.value||void 0}catch(t){let r=t instanceof Error?t.message:String(t);return console.warn(`Failed to fetch Radix asset symbol for ${e}: ${r}`),""}}async function Tt({chain:e,address:t,methodHex:r,id:i}){let s=await J(e);return _.post(s,{body:JSON.stringify({id:i,jsonrpc:"2.0",method:"eth_call",params:[{data:r,to:t.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}function Qn(e){if(!e||e==="0x")return"UNKNOWN";try{return wt(e.replace(/^0x/,""))?.trim()||"UNKNOWN"}catch(t){return console.warn(`Failed to decode ABI string from ${e}: ${t}`),"UNKNOWN"}}function Xn(e,t){if(!e||e==="0x")return t;try{return Number(e)}catch(r){return console.warn(`Failed to decode ABI uint8 from ${e}: ${r}`),t}}async function Jn({chain:e,address:t}){let{baseDecimal:r}=j(e),i=t.toLowerCase();if(t===""||!i.startsWith("0x"))return r;let s=await Tt({address:t,chain:e,id:2,methodHex:"0x313ce567"}).catch((l)=>(console.warn(`Could not fetch decimals for ${t} on ${e}: ${l.message}`),{result:""}));return Xn(s.result,r)}async function Zn({chain:e,address:t}){let r=t.toLowerCase();if(r===""||!r.startsWith("0x"))return;let i=await Tt({address:t,chain:e,id:1,methodHex:"0x95d89b41"}).catch((a)=>(console.warn(`Could not fetch symbol for ${t} on ${e}: ${a.message}`),{result:""}));return Qn(i.result)}async function St({rpcUrl:e,contractAddress:t,functionSelector:r}){return(await _.post(`${e}/wallet/triggerconstantcontract`,{body:JSON.stringify({contract_address:t,function_selector:r,owner_address:t,parameter:"",visible:!0}),headers:{accept:"application/json","content-type":"application/json"}}).catch(()=>{return}))?.constant_result?.[0]}function At(e){let t=e.match(/.{2}/g)?.map((r)=>Number.parseInt(r,16))??[];return new TextDecoder().decode(new Uint8Array(t))}function wt(e){return le(e).with(void 0,()=>{return}).when((t)=>t.length>=128,(t)=>{let r=Number.parseInt(t.slice(64,128),16),i=t.slice(128,128+r*2).replace(/(00)+$/,"");return i?At(i):void 0}).when((t)=>t.length===64,(t)=>{let r=t.replace(/(00)+$/,"");if(r.length>0&&r.length%2===0)return At(r);return}).otherwise(()=>{return})}function xt({chain:e,address:t}){let{baseDecimal:r}=j(e),i={decimals:r,ticker:void 0};return le(e).with(...Wn,async()=>{try{if(!bt(t.replace(/^0X/,"0x")))return i;let[s,a]=await Promise.all([Zn({address:t,chain:e}),Jn({address:t,chain:e})]);return{decimals:a,ticker:s}}catch(s){return console.warn(`Failed to fetch token info for ${t} on ${e}: ${s?.code} ${s?.message}`),i}}).with(u.Solana,async()=>{if(!t)return i;try{let s=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${t}`);if(s.ok){let a=await s.json(),l=Array.isArray(a)?a[0]:a;if(l)return{decimals:l.decimals??r,ticker:l.symbol||void 0}}}catch(s){console.warn(`Failed to fetch Solana token info for ${t}: ${s?.code} ${s?.message}`)}return i}).with(u.Tron,async()=>{if(!t)return i;try{let s=await J(u.Tron),[a,l]=await Promise.all([St({contractAddress:t,functionSelector:"symbol()",rpcUrl:s}),St({contractAddress:t,functionSelector:"decimals()",rpcUrl:s})]),p=wt(a);return{decimals:a!==void 0&&l?Number(BigInt(`0x${l}`)):r,ticker:p}}catch(s){let a=s instanceof Error?s.message:String(s);return console.warn(`Failed to fetch Tron token info for ${t}: ${a}`),i}}).with(u.Near,async()=>{if(!t)return i;try{let s=await J(u.Near),a=await _.post(s,{body:JSON.stringify({id:"dontcare",jsonrpc:"2.0",method:"query",params:{account_id:t,args_base64:"e30=",finality:"final",method_name:"ft_metadata",request_type:"call_function"}}),headers:{accept:"application/json","content-type":"application/json"}});if(!a.result?.result)throw Error("NEAR ft_metadata returned no result");let l=JSON.parse(new TextDecoder().decode(new Uint8Array(a.result.result)));return{decimals:l?.decimals||r,ticker:l?.symbol}}catch(s){let a=s instanceof Error?s.message:String(s);return console.warn(`Failed to fetch Near token info for ${t}: ${a}`),i}}).with(u.Radix,async()=>{if(!t)return i;try{let[s,a]=await Promise.all([zn(t),Yn(t)]);return{decimals:a,ticker:s}}catch(s){let a=s instanceof Error?s.message:String(s);return console.warn(`Failed to fetch Radix token info for ${t}: ${a}`),i}}).otherwise(async()=>i)}function Me(e){let t=j(e);return t.chain===e?t.nativeCurrency:void 0}function Rt({chain:e,symbol:t}){return le(e).with(u.Gnosis,()=>t==="xDAI"||t==="XDAI").with(u.Ton,()=>t==="GRAM"||t==="TON").with(u.Radix,()=>`${e}.${t}`===Se(e).identifier).otherwise(()=>t===(Me(e)??e))}var Se=(e)=>{let{baseDecimal:t}=j(e);return le(e.toUpperCase()).with(...jn,(i)=>({decimal:t,identifier:`${i}.ETH`})).with(u.Arc,(i)=>({decimal:t,identifier:`${i}.USDC`})).with(u.THORChain,(i)=>({decimal:t,identifier:`${i}.RUNE`})).with(u.Cosmos,(i)=>({decimal:t,identifier:`${i}.ATOM`})).with(u.Maya,(i)=>({decimal:10,identifier:`${i}.CACAO`})).with(u.BinanceSmartChain,(i)=>({decimal:t,identifier:`${i}.BNB`})).with(u.Monad,(i)=>({decimal:t,identifier:`${i}.MON`})).with(u.Avalanche,(i)=>({decimal:t,identifier:`${i}.AVAX`})).with(u.Gnosis,(i)=>({decimal:t,identifier:`${i}.xDAI`})).with(u.XLayer,(i)=>({decimal:t,identifier:`${i}.OKB`})).with(u.Berachain,(i)=>({decimal:t,identifier:`${i}.BERA`})).with(u.Hyperevm,(i)=>({decimal:t,identifier:`${i}.HYPE`})).with(u.Hype,(i)=>({decimal:t,identifier:`${i}.HYPE`})).with(u.Spark,(i)=>({decimal:t,identifier:`${i}.BTC`})).with(u.Tron,(i)=>({decimal:t,identifier:`${i}.TRX`})).with(u.Ton,(i)=>({decimal:t,identifier:`${i}.GRAM`})).with(u.Solana,u.Chainflip,u.Kujira,u.Ripple,u.Polkadot,u.Near,...Gn,(i)=>({decimal:t,identifier:`${i}.${i}`})).with(u.Radix,"XRD.XRD",()=>({decimal:t,identifier:"XRD.XRD"})).with(u.Polygon,"POL.POL",()=>({decimal:t,identifier:"POL.POL"})).with("KUJI.USK",(i)=>({decimal:6,identifier:i})).with("ETH.FLIP",()=>({decimal:j(u.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:j(u.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:j(u.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(i)=>({decimal:10,identifier:i})).with("MAYA.MAYA",(i)=>({decimal:4,identifier:i})).otherwise(()=>{let i=Me(e);return{decimal:t,identifier:i?`${e}.${i}`:e}})};function Ve({chain:e,symbol:t}){if(t.includes("/"))return"Synth";if(t.includes("~"))return"Trade";return le(e).with(u.Radix,()=>t===u.Radix||`${e}.${t}`===Se(e).identifier).with(u.Ton,()=>t==="GRAM"||t==="TON").with(u.Gnosis,()=>t===u.Gnosis).otherwise(()=>t===(Me(e)??e))?"Native":e}var Y=(e)=>{let[t,...r]=e.split("."),i=e.includes("/"),s=r.join("."),a=s?.split("-"),l=a?.length?a.length===1?a[0]:a.slice(0,-1).join("-"):void 0;return{chain:t,symbol:s,synth:i,ticker:l}};function de(e,t){let i=t===u.Near?e.indexOf("-"):e.lastIndexOf("-");if(i===-1)return{address:void 0,ticker:e};return{address:e.slice(i+1),ticker:e.slice(0,i)}}function fo(e){return`https://tokens.swapkit.dev/images/${e.toLowerCase()}.png`}async function yo(e){let{loadTokenLists:t}=await import("./tokens.js"),r=await t(void 0,{source:A.get("envs").isDev?"dev":"prod"}),i=Object.values(r).flatMap((a)=>a.tokens);if("identifier"in e)return i.find((a)=>a.identifier===e.identifier)?.identifier;let s=e.contract.toLowerCase();for(let a of i){let{chain:l,symbol:p}=Y(a.identifier);if(l!==e.chain)continue;let{address:g}=de(p,l);if(g?.toLowerCase()===s)return a.identifier}return}import{match as Ae}from"ts-pattern";var z=8,er=10,tr=64;function Z({value:e,bigIntDecimal:t=z,decimal:r=z}){if(r===0)return e.toString();let i=Math.min(t,r),s=i<r?vt(e,F(r-i)):e,a=s<0n,l=(a?-s:s).toString().padStart(i+1,"0"),p=l.length-i;return`${a?"-":""}${l.slice(0,p)}.${l.slice(p)}`.replace(/\.?0*$/,"")}class K{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(e,t){return new K({decimal:t,value:Z({bigIntDecimal:t,decimal:t,value:e})})}static shiftDecimals({value:e,from:t,to:r}){return K.fromBigInt(e.getBaseValue("bigint")*F(r)/F(t),r)}constructor(e){this.decimal=typeof e==="object"?e.decimal:void 0;let t=Te(typeof e==="object"&&"value"in e?e.value:e),r=typeof e==="object"&&"decimalMultiplier"in e?e.decimalMultiplier:F(this.decimal??0);this.decimalMultiplier=r!==void 0&&r>t.decimalMultiplier?r:t.decimalMultiplier,this.bigIntValue=t.bigIntValue*this.decimalMultiplier/t.decimalMultiplier}toString(e={}){return this.getValue("string")}set(e){return this.#n({decimal:this.decimal,value:new K(e)})}#n(e){return new this.constructor({...e,identifier:this.toString({includeSynthProtocol:!0})})}add(...e){return this.#t("add",...e)}sub(...e){return this.#t("sub",...e)}mul(...e){return this.#t("mul",...e)}div(...e){return this.#t("div",...e)}gt(e){return this.#e("gt",e)}gte(e){return this.#e("gte",e)}lt(e){return this.#e("lt",e)}lte(e){return this.#e("lte",e)}eqValue(e){return this.#e("eqValue",e)}getValue(e,t){let r=we(this.decimalMultiplier),i=t!==void 0?t:this.decimal,s=i!==void 0?i:r;if(i!==void 0&&i<r){if(this.formatBigIntToSafeValue(this.bigIntValue,i)==="0"&&this.bigIntValue!==0n)s=r}let a=this.formatBigIntToSafeValue(this.bigIntValue,s);return Ae(e).with("number",()=>Number(a)).with("string",()=>a).with("bigint",()=>this.bigIntValue*F(this.decimal??z)/this.decimalMultiplier).otherwise(()=>a)}getBaseValue(e,t){let r=F(t??this.decimal??z),i=vt(this.bigIntValue*r,this.decimalMultiplier);return Ae(e).with("number",()=>Number(i)).with("string",()=>i.toString()).otherwise(()=>i)}getBigIntValue(e,t){if(t===void 0&&typeof e==="object")return e.bigIntValue;let r=Te(e),i=t===void 0?this.decimalMultiplier:F(t);return r.bigIntValue*i/r.decimalMultiplier}toSignificant(e=6){let t=this.getValue("string"),r=t.startsWith("-"),i=r?t.slice(1):t,[s="",a=""]=i.split("."),l=Number.parseInt(s,10)>0;if((l?s.length+a.length:a.length)<=e)return B(r,i);if(s.length>=e)return B(r,s.slice(0,e).padEnd(s.length,"0"));if(l)return B(r,`${s}.${a.slice(0,e-s.length)}`);let g=a.replace(/^0+/,"")||"0",S=g.slice(0,e),y=a.length-g.length;return B(r,`0.${S.padStart(y+S.length,"0")}`)}toFixed(e=6){let t=this.getValue("string"),r=t.startsWith("-"),[i="0",s=""]=(r?t.slice(1):t).split(".");if(e===0){if(i==="0"&&!s)return"0";let y=s&&Number.parseInt(s[0]||"0",10)>=5?`${BigInt(i)+1n}.0`:`${i}.0`;return B(r,y)}if(!s)return B(r,`${i}.${"0".repeat(e)}`);let a=s[e];if(!(a&&Number.parseInt(a,10)>=5))return B(r,`${i}.${s.slice(0,e).padEnd(e,"0")}`);let p=BigInt(s.slice(0,e).padEnd(e,"0"))+1n,g=10n**BigInt(e);if(p>=g)return B(r,`${BigInt(i)+1n}.${"0".repeat(e)}`);return B(r,`${i}.${p.toString().padStart(e,"0")}`)}toAbbreviation(e=2){let t=this.getValue("string"),r=Number(t),i=["","K","M","B","T","Q","Qi","S"],s=Math.floor(Math.log10(Math.abs(r))/3);if(s===0||!i[s])return t;return`${(r/10**(s*3)).toFixed(e)}${i[s]}`}toCurrency(e="$",{currencyPosition:t="start",decimal:r=2,decimalSeparator:i=".",thousandSeparator:s=",",trimTrailingZeros:a=!0}={}){let l=this.toFixed(r),p=t==="end",[g="0",S=""]=l.split("."),y=g.replace(/\B(?=(\d{3})+(?!\d))/g,s),w=S&&Number.parseInt(S,10)>0,E=w?`${y}${i}${S}`:y,M=E.length<100&&a&&w?E.replace(/\.?0*$/,""):E;return p?`${M}${e}`:`${e}${M}`}formatBigIntToSafeValue(e,t){return Z({bigIntDecimal:t||this.decimal||z,decimal:we(this.decimalMultiplier),value:e})}#t(e,...t){let r=t.map(Te),i=Math.max(z,we(this.decimalMultiplier),...r.map(({decimalMultiplier:S})=>we(S))),s=Math.min(i+er,tr),a=F(s),l=r.reduce((S,y)=>{let w=S.decimalMultiplier*y.decimalMultiplier,E=Ae(e).with("add",()=>S.bigIntValue*y.decimalMultiplier+y.bigIntValue*S.decimalMultiplier).with("sub",()=>S.bigIntValue*y.decimalMultiplier-y.bigIntValue*S.decimalMultiplier).with("mul",()=>S.bigIntValue*y.bigIntValue).with("div",()=>{if(y.bigIntValue===0n)throw RangeError("Division by zero");return S.bigIntValue*y.decimalMultiplier}).exhaustive(),T=e==="div"?S.decimalMultiplier*y.bigIntValue:w;return{bigIntValue:E*a/T,decimalMultiplier:a}},this),p=this.decimal===void 0?void 0:Math.min(this.decimal,s),g=l.decimalMultiplier===a?l:{bigIntValue:l.bigIntValue*a/l.decimalMultiplier,decimalMultiplier:a};return this.#n({decimal:p,value:g})}#e(e,t){let r=Te(t),i=this.bigIntValue*r.decimalMultiplier,s=r.bigIntValue*this.decimalMultiplier;return Ae(e).with("gt",()=>i>s).with("gte",()=>i>=s).with("lt",()=>i<s).with("lte",()=>i<=s).with("eqValue",()=>i===s).exhaustive()}}var nr=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function rr(e){let r=`${typeof e==="number"?nr.format(e):e}`.replaceAll(",",".").split(".");return r.length>1?`${r.slice(0,-1).join("")}.${r.at(-1)}`:r[0]||"0"}function ir(e){let t=e.split(".")[1]?.length||0;return Math.max(t,z)}function Te(e){if(typeof e==="object")return e;let t=e==="undefined"?"0":rr(e),r=ir(t),[i="",s=""]=t.split(".");return{bigIntValue:BigInt(`${i}${s.padEnd(r,"0")}`),decimalMultiplier:F(r)}}function B(e,t){return e&&!/^0(?:\.0*)?$/.test(t)?`-${t}`:t}function vt(e,t){if(t===0n)throw Error("Cannot divide by zero");let r=t/2n;return e>=0n&&t>=0n||e<0n&&t<0n?(e+r)/t:(e-r)/t}function F(e){return 10n**BigInt(e)}function we(e){return e.toString().length-1}function ar(e=""){let t=e.toUpperCase(),r=A.get("chains"),[i]=t.split(".");if(r.includes(i))return!0;let[s]=t.split("/");if(r.includes(s))return!0;throw new b({errorKey:"helpers_invalid_identifier",info:{identifier:e,message:`Invalid identifier: ${e}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}var ne=[R.Hype,R.Near,R.Ripple,R.Solana,R.Stellar,R.Sui,R.Ton,R.Tron],$e=[R.THORChain,R.Maya];function xe(e,t){return ne.includes(e)?t:t.toUpperCase()}var ee=new Map,Re=new Map,te=new Map,lr=3600000;function dr(e){let t=te.get(e);if(t?.timestamp&&Date.now()-t.timestamp>lr){te.delete(e);return}return t}function cr(e,t){if(te.size>1000){let r=te.keys().next().value;if(r)te.delete(r)}te.set(e,{...t,timestamp:Date.now()})}class N extends K{address;chain;isGasAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:e,decimal:t,tax:r,chain:i,symbol:s,identifier:a}){super({decimal:t,value:e});let l=It(a||`${i}.${s}`);this.type=Ve(l),this.tax=r,this.chain=l.chain,this.ticker=l.ticker,this.symbol=l.symbol,this.address=l.address,this.isSynthetic=l.isSynthetic,this.isTradeAsset=l.isTradeAsset,this.isGasAsset=l.isGasAsset,this.chainId=ce(l.chain).chainId}toString({includeSynthProtocol:e}={}){return(this.isSynthetic||this.isTradeAsset)&&!e?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){if(this.isSynthetic)return`${this.chain}.${this.symbol.replace(/\//g,".")}`;if(this.isTradeAsset)return`${this.chain}.${this.symbol.replace(/~/g,"..")}`;let e=this.symbol.replace(/\./g,"__");return`${this.chain}.${e}`}getIconUrl(){return ee.get(xe(this.chain,this.toString()))?.logoURI}eqAsset({chain:e,symbol:t}){return this.chain===e&&this.symbol===t}eq(e){return this.eqAsset(e)&&this.eqValue(e)}static fromUrl(e,t=0){let r=e.indexOf(".");if(r===-1)throw new b({errorKey:"helpers_invalid_asset_url",info:{urlAsset:e}});let i=e.slice(0,r),s=e.slice(r+1),a=Be({chain:i,rest:s}).when(({rest:l})=>l.includes(".."),({chain:l,rest:p})=>`${l}.${p.replace(/\.\./g,"~")}`).when(({chain:l,rest:p})=>$e.includes(l)&&p.includes("."),({chain:l,rest:p})=>`${l}.${p.replace(/\./g,"/")}`).otherwise(({chain:l,rest:p})=>`${l}.${p.replace(/__/g,".")}`);return N.from({asset:a,value:t})}static from({value:e=0,fromBaseDecimal:t,asyncTokenLookup:r,...i}){let s="address"in i&&"chain"in i,a=gr(i);if(a===null&&r&&s){let{chain:x,address:X}=i;return ur({address:X,chain:x,fromBaseDecimal:t,parsedValue:e})}let l=s&&!a?`${i.chain}.UNKNOWN-${i.address}`:a,{identifier:p,decimal:g}=Se(l),{chain:S,isSynthetic:y,isTradeAsset:w,address:E}=It(p),{baseDecimal:T}=ce(S),M=ee.get(xe(S,p));if(!M&&r&&!y&&!w)return(async()=>{let{ticker:x}=Y(p),X=await Ct({address:E,chain:S,ticker:x});return He({decimal:X.decimals,identifier:X.identifier,value:t?Ue(e,t):e})})();let k=M?.decimal||g;ae({condition:!k&&!r,id:`assetValue_static_decimal_not_found_${S}`,warning:`Couldn't find static decimal for one or more tokens on ${S} (Using default ${T} decimal as fallback).
2
+ This can result in incorrect calculations and mess with amount sent on transactions.
3
+ You can load static assets by installing @swapkit/tokens package and calling AssetValue.loadStaticAssets()
4
+ or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`});let{decimal:I,identifier:Q,tax:ue}=M||{decimal:k||T,identifier:p},me=t?Ue(e,t):ve(e,I);return y||w?pr(Q,me):He({decimal:I,identifier:Q,tax:ue,value:me})}static async loadStaticAssets(e){let{loadTokenLists:t}=await import("@swapkit/tokens"),r=await t(e,{source:A.get("envs").isDev?"dev":"prod"});for(let{tokens:i}of Object.values(r))for(let s of i){let{identifier:a}=s,{chain:l,symbol:p}=Y(a),{address:g}=de(p,l),{baseDecimal:S}=ce(l),y=xe(l,a),w="decimals"in s&&s.decimals!==void 0?s.decimals:S,E="logoURI"in s&&s.logoURI?s.logoURI:`https://tokens.swapkit.dev/images/${a.toLowerCase()}.png`,T={decimal:w,identifier:a,logoURI:E,tax:"tax"in s?s.tax:void 0};if(ee.set(y,T),g){let M=ne.includes(l)?`${l}:${g}`:`${l}:${g.toUpperCase()}`;Re.set(M,a)}}return!0}static setStaticAssets(e){ee.clear(),Re.clear();for(let[t,r]of e.entries()){let{identifier:i}=r,{chain:s,symbol:a}=Y(i),{address:l}=de(a,s),{baseDecimal:p}=ce(s),g=r.chain??s,S=r.address??l,y=xe(g,i),w=r.decimals??r.decimal??p,E=r.logoURI??`https://tokens.swapkit.dev/images/${i.toLowerCase()}.png`,T={decimal:w,identifier:y,logoURI:E,tax:r.tax};if(ee.set(y,T),S){let M=ne.includes(g)?`${g}:${S}`:`${g}:${S.toUpperCase()}`;Re.set(M,i)}}return!0}static get staticAssets(){return ee}}function Po(e){let t=N.from({chain:e});return Be(e).with(R.Bitcoin,R.Litecoin,R.BitcoinCash,R.Dash,()=>t.set(0.00010001)).with(R.Zcash,()=>t.set(0.00015001)).with(R.Dogecoin,()=>t.set(1.00000001)).with(R.Avalanche,R.Ethereum,R.Arbitrum,R.BinanceSmartChain,()=>t.set(0.00000001)).with(R.THORChain,R.Maya,()=>t.set(0)).with(R.Cosmos,R.Kujira,()=>t.set(0.000001)).otherwise(()=>t.set(0.00000001))}async function Ct({chain:e,address:t,ticker:r}){let s=ne.includes(e)?`${e}:${t||r}`:`${e}:${t||r}`.toUpperCase(),a=dr(s);if(a)return a;if(!t){let{baseDecimal:g}=ce(e);return{decimals:g,identifier:`${e}.${r||"UNKNOWN"}`}}let l=await xt({address:t,chain:e}),p=`${e}.${l.ticker||r||"UNKNOWN"}-${t}`;return ae({condition:!!(!l.ticker&&r),id:`async_token_lookup_failed_${e}_${t}`,warning:`Could not fetch token metadata for ${e}:${t} from chain. Using user-provided ticker (${r}) with baseDecimal (${l.decimals}).`}),l.ticker&&cr(s,{decimals:l.decimals,identifier:p}),{decimals:l.decimals,identifier:p}}function He({identifier:e,decimal:t,value:r,tax:i}){return ar(e),new N({decimal:t,identifier:e,tax:i,value:ve(r,t)})}function pr(e,t=0){let r=e.includes(".")?e.split(".")?.[0]?.toUpperCase():void 0,i=r?$e.includes(r):!1,s=e.slice(0,14).includes("~")?"~":"/",[a,l]=i?e.split(".").slice(1).join().split(s):e.split(s);if(!(a&&l))throw new b({errorKey:"helpers_invalid_asset_identifier",info:{identifier:e}});return new N({decimal:8,identifier:`${r||R.THORChain}.${a}${s}${l}`,value:ve(t,8)})}async function ur({address:e,chain:t,fromBaseDecimal:r,parsedValue:i}){let{decimals:s,identifier:a}=await Ct({address:e,chain:t}),l=r?Ue(i,r):i;return He({decimal:s,identifier:a,value:l})}function Ue(e,t){let r=e instanceof K?e.getValue("string"):e;return ve(BigInt(r),t)}function ve(e,t){return typeof e==="bigint"?Z({bigIntDecimal:t,decimal:t,value:e}):e}function mr(e){let t=Be(e).when((r)=>("chain"in r)&&r.chain!==void 0,({chain:r})=>r).otherwise((r)=>{let i=Y(r.asset);return i.synth?R.THORChain:i.chain});if(!sr.includes(t.toUpperCase())){let r="asset"in e?e.asset:t;throw new b({errorKey:"helpers_invalid_asset_identifier",info:{identifier:r,message:`Unsupported chain "${t}" - use the AssetValue constructor directly`}})}}function gr(e){if(mr(e),"chain"in e){let{chain:s,address:a}=e;if(a){let l=ne.includes(s)?`${s}:${a}`:`${s}:${a.toUpperCase()}`,p=Re.get(l);if(p)return p;return null}return s}let{chain:t,symbol:r}=Y(e.asset);return Ve({chain:t,symbol:r})==="Native"?t:e.asset}function _r(e,t,r){let i=e.split("."),s=i[0]?.toUpperCase(),a=$e.includes(s),l=r?"~":"/",[p,g=""]=a?i.slice(1).join(".").split(l):e.split(l);if(!(p&&g))throw new b({errorKey:"helpers_invalid_asset_identifier",info:{identifier:e}});let{ticker:S,address:y}=Ot({chain:p,symbol:g}),w=`${p}${l}${g}`;return{address:y,chain:s,isGasAsset:!1,isSynthetic:t,isTradeAsset:r,symbol:w,ticker:S}}function hr(e){let t=e.indexOf("."),r=(t===-1?e:e.slice(0,t)).toUpperCase(),i=t===-1?e:e.slice(t+1),{address:s,ticker:a}=Ot({chain:r,symbol:i}),l;try{l=s&&or.includes(r)&&be(s)?be(s):s}catch{l=s}let p=l?`${a}-${l}`:i;return{address:l,chain:r,isGasAsset:Rt({chain:r,symbol:i}),isSynthetic:!1,isTradeAsset:!1,symbol:p,ticker:a}}function It(e){let t=e.slice(0,14),r=t.includes("/"),i=t.includes("~");if(r||i)return _r(e,r,i);return hr(e)}function Ot({symbol:e,chain:t}){let{ticker:r,address:i}=de(e,t);return{address:i&&!ne.includes(t)?i.toLowerCase():i,ticker:r}}class Ie extends K{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new Ie({decimal:t,value:Z({bigIntDecimal:t,decimal:t,value:e})})}}function Pt(e=!0){return e?"https://gateway.liquify.com/chain/thorchain_midgard":"https://midgard.mayachain.info"}function yr(e=!0){let t=Pt(e);return e?`${t}/v2/thorname`:`${t}/v2/mayaname`}function br(e){return function(r){let i=r?`?status=${r}`:"";return _.get(`${e}/v2/pools${i}`)}}function Sr(e){return function(r){return _.get(`${e}/v2/pool/${r}`)}}function Ar(e){return function(r,i){let s=i?`?period=${i}`:"";return _.get(`${e}/v2/pool/${r}/stats${s}`)}}function Tr(e){return function(r,i){let s=new URLSearchParams;if(i?.interval)s.append("interval",i.interval);if(i?.count)s.append("count",i.count.toString());if(i?.from)s.append("from",i.from.toString());if(i?.to)s.append("to",i.to.toString());let a=s.toString()?`?${s.toString()}`:"";return _.get(`${e}/v2/history/depths/${r}${a}`)}}function wr(e){return function(){return _.get(`${e}/v2/network`)}}function xr(e){return function(){return _.get(`${e}/v2/health`)}}function Rr(e){return function(){return _.get(`${e}/v2/nodes`)}}function vr(e){return function(r){return _.get(`${e}/v2/node/${r}`)}}function Ir(e){return function(){return _.get(`${e}/v2/mimir/votes`)}}function Cr(e){return function(){return _.get(`${e}/v2/mimir`)}}function Or(e){return function(){return _.get(`${e}/v2/constants`)}}function Pr(e){return function(){return _.get(`${e}/v2/stats`)}}function kr(e){return function(r){let i=new URLSearchParams;if(r?.interval)i.append("interval",r.interval);if(r?.count)i.append("count",r.count.toString());if(r?.from)i.append("from",r.from.toString());if(r?.to)i.append("to",r.to.toString());let s=i.toString()?`?${i.toString()}`:"";return _.get(`${e}/v2/history/earnings${s}`)}}function Lr(e){return function(r,i){let s=new URLSearchParams;if(i?.interval)s.append("interval",i.interval);if(i?.count)s.append("count",i.count.toString());if(i?.from)s.append("from",i.from.toString());if(i?.to)s.append("to",i.to.toString());let a=s.toString()?`?${s.toString()}`:"",l=r?`/swaps/${r}`:"/swaps";return _.get(`${e}/v2/history${l}${a}`)}}function Er(e){return function(r){let i=new URLSearchParams;if(r?.interval)i.append("interval",r.interval);if(r?.count)i.append("count",r.count.toString());if(r?.from)i.append("from",r.from.toString());if(r?.to)i.append("to",r.to.toString());let s=i.toString()?`?${i.toString()}`:"";return _.get(`${e}/v2/history/tvl${s}`)}}function Nr(e){if(!e)return"";let t=new URLSearchParams,r=(i,s)=>{if(s!==void 0)t.append(i,typeof s==="number"?s.toString():s)};return r("address",e.address),r("txid",e.txid),r("asset",e.asset),r("type",e.type),r("affiliate",e.affiliate),r("limit",e.limit),r("offset",e.offset),t.toString()?`?${t.toString()}`:""}function Dr(e){return function(r){let i=Nr(r);return _.get(`${e}/v2/actions${i}`)}}function Mr(e){return function(r){return _.get(`${e}/v2/member/${r}`)}}function Vr(e){return function(r){let i=r?`/${r}`:"";return _.get(`${e}/v2/members${i}`)}}function Hr(e){return function(r,i){let s=i?`&asset=${i}`:"";return _.get(`${e}/v2/saver/${r}${s?`?${s.substring(1)}`:""}`)}}function Ur(e){return function(r){return _.get(`${e}/v2/savers/${r}`)}}function Br(e){return function(r,i){let s=new URLSearchParams;if(i?.interval)s.append("interval",i.interval);if(i?.count)s.append("count",i.count.toString());if(i?.from)s.append("from",i.from.toString());if(i?.to)s.append("to",i.to.toString());let a=s.toString()?`?${s.toString()}`:"",l=r?`/savers/${r}`:"/savers";return _.get(`${e}/v2/history${l}${a}`)}}function $r(e){return function(r){return _.get(`${e}/v2/balance/${r}`)}}function Fr(e){return async function(r){let i=(s)=>{if(s?.cause?.status===404)return;throw s};return await _.get(`${e}/lookup/${r}`,{onError:i,retry:{maxRetries:1}})}}function Kr(e){return async function(r){let i=(s)=>{if(s?.cause?.status===404)return[];throw s};return await _.get(`${e}/rlookup/${r}`,{onError:i,retry:{maxRetries:1}})}}function qr(e){return async function(r){let i=(s)=>{if(s?.cause?.status===404)return[];throw s};return await _.get(`${e}/owner/${r}`,{onError:i,retry:{maxRetries:1}})}}function re({asset:e,value:t}){return N.from({asset:e,fromBaseDecimal:fr(Ce.THORChain).baseDecimal,value:t})}function Wr({liquidityPositionGetter:e,isThorchain:t}){return async function(i){let s=await e(i),a=t?"rune":"cacao";return s.pools.map((l)=>({[`${a}Pending`]:re({asset:"THOR.RUNE",value:l.runePending}),[`${a}RegisteredAddress`]:l.runeAddress,[`${a}Withdrawn`]:re({asset:"THOR.RUNE",value:l.runeWithdrawn}),[a]:re({asset:"THOR.RUNE",value:l.runeAdded}),asset:re({asset:l.pool,value:l.assetAdded}),assetPending:re({asset:l.pool,value:l.assetPending}),assetRegisteredAddress:l.assetAddress,assetWithdrawn:re({asset:l.pool,value:l.assetWithdrawn}),dateFirstAdded:l.dateFirstAdded,dateLastAdded:l.dateLastAdded,poolShare:new Ie(l.liquidityUnits).div(l.pool)}))}}function kt(e){let t=e===Ce.THORChain,r=Pt(t),i=yr(t),s=Mr(r);return{getActions:Dr(r),getBalance:$r(r),getConstants:Or(r),getEarningsHistory:kr(r),getHealth:xr(r),getLiquidityPosition:Wr({isThorchain:t,liquidityPositionGetter:s}),getLiquidityPositionRaw:s,getMembers:Vr(r),getMimir:Cr(r),getMimirVotes:Ir(r),getNameDetails:Fr(i),getNamesByAddress:Kr(i),getNamesByOwner:qr(i),getNetworkInfo:wr(r),getNode:vr(r),getNodes:Rr(r),getPool:Sr(r),getPoolDepthHistory:Tr(r),getPoolStats:Ar(r),getPools:br(r),getSaverDetails:Hr(r),getSavers:Ur(r),getSaversHistory:Br(r),getStats:Pr(r),getSwapHistory:Lr(r),getTVLHistory:Er(r)}}var Lt=kt(Ce.THORChain),Et=kt(Ce.Maya);var Xe={};nt(Xe,{SKRequestClient:()=>P,buildLimitOrder:()=>Zi,buildLimitOrderCancel:()=>rs,getChainBalance:()=>Fi,getChainflipDepositChannel:()=>zi,getGasRate:()=>Yi,getLimitOrder:()=>ns,getLimitOrderQuote:()=>Ji,getLimitOrderTokens:()=>Xi,getLimitOrders:()=>ts,getNearDepositChannel:()=>Qi,getPrice:()=>ji,getRouteWithTx:()=>$i,getSwapQuote:()=>Bi,getSwapTo:()=>ds,getTokenApproval:()=>Ki,getTokenList:()=>Wi,getTokenListProviders:()=>qi,getTrackerDetails:()=>Ui,searchTokens:()=>Gi,submitLimitOrder:()=>es,submitLimitOrderCancel:()=>is});import{EVMChains as Qe}from"@swapkit/types";import{match as Hi,P as pe}from"ts-pattern";import{Chain as Oe,ChainId as q}from"@swapkit/types";import{array as v,boolean as U,coerce as Vt,number as h,object as m,optional as c,string as o,union as Fe,unknown as Ke,z as n}from"zod";var Ht;((i)=>{i.CHEAPEST="CHEAPEST";i.FASTEST="FASTEST";i.RECOMMENDED="RECOMMENDED"})(Ht||={});var Pe;((y)=>{y.PSBT="PSBT";y.EVM="EVM";y.COSMOS="COSMOS";y.RADIX="RADIX";y.NEAR="NEAR";y.STELLAR="STELLAR";y.TON="TON";y.TRON="TRON";y.EIP_712_HYPE_SEND_ASSET="EIP_712_HYPE_SEND_ASSET";y.EIP_712_HYPE_WITHDRAW="EIP_712_HYPE_WITHDRAW"})(Pe||={});var Ut;((I)=>{I.approve="approve";I.claim="claim";I.deposit="deposit";I.donate="donate";I.lending="lending";I.lp_action="lp_action";I.native_contract_call="native_contract_call";I.native_send="native_send";I.stake="stake";I.streaming_swap="streaming_swap";I.swap="swap";I.thorname_action="thorname_action";I.token_contract_call="token_contract_call";I.token_transfer="token_transfer";I.unknown="unknown";I.unstake="unstake"})(Ut||={});var Bt;((T)=>{T.swap="swap";T.aggregation="aggregation";T.addLiquidity="addLiquidity";T.withdrawLiquidity="withdrawLiquidity";T.addSavers="addSavers";T.withdrawSavers="withdrawSavers";T.borrow="borrow";T.repay="repay";T.name="name";T.donate="donate";T.claim="claim";T.stake="stake";T.unstake="unstake"})(Bt||={});var $t;((p)=>{p.unknown="unknown";p.not_started="not_started";p.pending="pending";p.swapping="swapping";p.completed="completed";p.refunded="refunded";p.failed="failed"})($t||={});var Ft;((k)=>{k.not_started="not_started";k.starting="starting";k.broadcasted="broadcasted";k.mempool="mempool";k.inbound="inbound";k.outbound="outbound";k.swapping="swapping";k.completed="completed";k.refunded="refunded";k.partially_refunded="partially_refunded";k.dropped="dropped";k.reverted="reverted";k.replaced="replaced";k.retries_exceeded="retries_exceeded";k.parsing_error="parsing_error"})(Ft||={});var Fo=m({address:c(o()),chain:n.enum(Oe).optional(),chainId:n.enum(q),coingeckoId:c(o()),decimals:Vt.number(),extensions:c(n.looseObject({})),identifier:o(),logoURI:c(o()),name:c(o()),shortCode:c(o()),symbol:c(o()),ticker:o()}),Ko=n.object({block:n.optional(n.number().describe("Block number. Required for Polkadot chain. e.g. `123456`")),chainId:n.optional(n.string().describe("ChainId for the hash. e.g. `thorchain-1`")),depositChannelId:n.optional(n.string().describe("Deposit channel ID, required for Chainflip if tx was broadcasted without wallet connection")),hash:n.optional(n.string().describe("Hash for the first transaction broadcasted by the end user. e.g. `88D1819378ECD09E5284C54937CDC1E99B52F253C007617A02DD1200710CE677`"))}).refine((e)=>e.hash&&e.chainId||e.depositChannelId,{message:"Either `hash` and `chainId` or `depositChannelId` must be provided"}),qo=n.object({forceUpdate:n.string().toLowerCase().transform((e)=>e==="true").pipe(n.boolean()).optional()}),Wo=m({error:o(),message:o()}),ie=m({address:c(o()),chain:n.enum(Oe),decimal:c(h()),isGasAsset:U(),isSynthetic:U(),symbol:o(),tax:c(m({buy:h(),sell:h()})),ticker:o()}),Kt=m({id:o(),market_cap:h(),name:o(),price_change_24h_usd:h(),price_change_percentage_24h_usd:h(),sparkline_in_7d:v(h()),timestamp:o(),total_volume:h()}).partial(),Go=m({cg:c(Kt),identifier:o(),price_usd:h(),provider:o(),timestamp:h()}),qt=v(m({cg:c(Kt),identifier:o(),price_usd:h(),provider:o(),timestamp:h()}).partial()),jo=m({affiliate:c(o().describe("Affiliate thorname")),affiliateFee:c(h().describe("Affiliate fee in basis points").refine((e)=>e===Math.floor(e)&&e>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:c(U().describe("Allow smart contract as recipient")),allowSmartContractSender:c(U().describe("Allow smart contract as sender")),buyAsset:o().describe("Asset to buy"),cfBoost:c(U().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:c(o().describe("Address to send asset to")),disableSecurityChecks:c(U().describe("Disable security checks")),includeTx:c(U().describe("Set to true to include an transaction object (EVM only)")),providers:c(v(o().describe("List of providers to use").refine((e)=>C[e]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:c(o().describe("Referrer address (referral program)")),sellAmount:o().describe("Amount of asset to sell").refine((e)=>+e>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:o().describe("Asset to sell"),slippage:c(h().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:c(o().describe("Address to send asset from"))}).refine((e)=>e.sellAsset!==e.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),Yo=m({metadata:U(),tokens:v(m({identifier:o()}))}),Wt=m({destinationAddress:o()}),Gr=Wt.extend({affiliateFees:v(m({brokerAddress:o(),feeBps:h()})).optional(),brokerCommissionBps:h().optional(),buyAsset:m({asset:o(),chain:o()}),channelMetadata:m({cfParameters:o().optional(),gasBudget:o().optional(),message:o().optional()}).optional(),dcaParameters:m({chunkInterval:h().optional(),numberOfChunks:h().optional()}).optional(),maxBoostFeeBps:h().optional(),refundParameters:m({minPrice:o().optional(),refundAddress:o().optional(),retryDuration:h().optional()}).optional(),sellAsset:m({asset:o(),chain:o()})}),Gt=m({channelId:o(),depositAddress:o()}),Nt=Wt.extend({affiliateFees:m({feeBps:h(),nearId:o()}).optional(),buyAsset:o(),sellAmount:o(),sellAsset:o(),slippage:Vt.number(),sourceAddress:o()}),Dt=m({amountIn:o(),amountInFormatted:o(),amountInUsd:o(),amountOut:o(),amountOutFormatted:o(),amountOutUsd:o(),deadline:o().optional(),minAmountIn:o(),minAmountOut:o(),timeEstimate:h().optional(),timeWhenInactive:o().optional()}),zo=Dt.extend({depositAddress:o(),quote:Dt,signature:o(),timestamp:o(),tx:Ke()}),jt=m({buyAsset:o(),buyAssetAmount:o(),buyAssetAmountMaxSlippage:o(),deadline:o().optional(),depositAddress:o(),depositAmount:o(),depositAsset:o(),tx:Ke()}),jr=m({evmCalldata:n.optional(n.string()),intentHash:n.optional(n.string()),logs:n.optional(n.unknown()),manifest:n.optional(n.unknown()),memo:n.optional(n.string()),spender:n.optional(n.string()),thorname:n.optional(n.string())}),Yr=m({currentStage:o(),inboundConfirmation:h(),inboundObservation:h(),outboundDelay:h(),outboundObservation:h(),streamingSwap:h()}),zr=m({count:c(h()),interval:c(h()),quantity:c(h()),subSwapsMap:c(v(h()))}),Qr=n.object({currentLegIndex:n.optional(n.number()),estimatedTimeToComplete:n.number(),estimates:n.optional(Yr),providerDetails:n.optional(n.object({streamingDetails:n.optional(zr)}))}),Xr=m({affiliate:c(ie),liquidity:c(ie),network:c(ie),protocol:c(ie),tax:c(ie)}),Jr=m({affiliate:o(),bps:o(),isReferrer:U()}),Zr=m({affiliate:c(o()),affiliateFees:c(v(Jr)),broadcastedAt:c(h()),explorerUrl:c(o()),fees:c(Xr),images:c(m({chain:c(o()),from:c(o()),provider:c(o()),to:c(o())})),provider:c(n.enum(C)),providerAction:n.optional(n.enum(Bt)),quoteId:c(o()),wallet:c(o())}),se=n.object({block:n.number(),chainId:n.enum(q),finalAddress:n.optional(n.string()),finalAsset:n.optional(ie),finalisedAt:n.number(),fromAddress:n.string(),fromAmount:n.string(),fromAsset:n.string(),hash:n.string(),meta:n.optional(Zr),payload:n.optional(jr),status:n.enum($t),toAddress:n.string(),toAmount:n.string(),toAsset:n.string(),trackingStatus:n.optional(n.enum(Ft)),transient:n.optional(Qr),type:n.enum(Ut)}),Yt=se.extend({legs:n.array(se)}),Qo=se.extend({legs:v(se)}),Xo=se.extend({legs:v(se)}),qe=v(m({amount:o(),asset:o(),chain:o(),protocol:n.enum(C),type:n.enum(_e)})),We=n.object({inbound:n.optional(n.number().describe("Time to receive inbound asset in seconds")),outbound:n.optional(n.number().describe("Time to receive outbound asset in seconds")),swap:n.optional(n.number().describe("Time to swap assets in seconds")),total:n.number().describe("Total time in seconds")}),ei=/^(?:0x[0-9a-fA-F]+|[0-9]+)$/;function ti(e){return e===""||ei.test(e)}function Jo(e){return e?BigInt(e):0n}function Zo(e){let t=typeof e==="bigint"?e:BigInt(e);return t>0n?`0x${t.toString(16)}`:"0x0"}var H=o().refine(ti,{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"),ni=m({data:o().describe("Data to send"),from:o().describe("Address of the sender"),to:o().describe("Address of the recipient"),value:H}),ri=n.object({data:n.string().optional(),raw_data:n.object({contract:n.any(),data:n.string().optional(),expiration:n.number(),fee_limit:n.number().optional(),ref_block_bytes:n.string(),ref_block_hash:n.string(),timestamp:n.number()}).passthrough(),raw_data_hex:n.string(),txID:n.string(),value:H.optional(),visible:n.boolean()}),ii=v(Fe([o(),h(),v(o()),m({from:o(),value:H}).describe("Parameters to pass to the contract method")])),ea=m({approvalSpender:c(o().describe("Address of the spender to approve")),approvalToken:c(o().describe("Address of the token to approve spending of")),contractAddress:o().describe("Address of the contract to interact with"),contractMethod:o().describe("Name of the method to call"),contractParamNames:v(o().describe("Names of the parameters to pass to the contract method")),contractParams:ii}),si=m({typeUrl:o("/types.MsgDeposit"),value:m({coins:v(m({amount:o(),asset:m({chain:o(),symbol:o(),synth:U(),ticker:o()})})),memo:o(),signer:o()})}),oi=m({typeUrl:o("/types.MsgSend"),value:m({amount:v(m({amount:o(),denom:o()})),fromAddress:o(),toAddress:o()})}),ai=m({typeUrl:o(),value:oi.shape.value.or(si.shape.value)}),li=m({amount:v(m({amount:o(),denom:o()})),gas:o()}),di=m({accountNumber:h(),chainId:n.enum(q),fee:li,memo:o(),msgs:v(ai),sequence:h()}),ci=n.array(n.object({calldata:n.array(n.string()),contractAddress:n.string(),entrypoint:n.string()})),pi=n.object({address:n.string().describe("Destination address in friendly format"),amount:n.string().describe("Amount in nanotons"),payload:n.string().optional().describe("Base64 BOC of body cell"),stateInit:n.string().optional().describe("Base64 BOC of state init")}),ui=n.object({messages:n.array(pi),sendMode:n.number().describe("TON wallet send mode for the whole transfer")}),ta="USDC:0x6d1e7cde53ba9467b783cb7c530ce054",mi=n.looseObject({domain:n.looseObject({chainId:c(Fe([h(),o()])),name:c(o()),verifyingContract:c(o()),version:c(o())}),message:n.record(o(),Ke()),primaryType:o(),types:n.record(o(),v(n.looseObject({name:o(),type:o()})))}),gi=n.looseObject({amount:o(),destination:o(),destinationDex:o(),fromSubAccount:o(),hyperliquidChain:o(),nonce:h().int(),signatureChainId:o(),sourceDex:o(),token:o(),type:n.literal("sendAsset")}),zt=n.looseObject({action:n.looseObject({type:o()}),submitTo:o(),typedData:mi}),na=zt.extend({action:gi}),Qt=Fe([ni,di,ri,ui,zt,o()]),_i=Qt.or(ci),hi=m({affiliate:o().describe("Affiliate address").optional(),affiliateFee:h().describe("Affiliate fee").optional(),buyAsset:o().describe("Asset to buy"),destinationAddress:o().describe("Destination address"),estimatedTime:We.optional(),provider:n.enum(C),sellAsset:o().describe("Asset to sell"),slipPercentage:h().describe("Slippage as a percentage"),sourceAddress:o().describe("Source address")}),ra=hi.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),fi=m({asset:o().describe("Asset name"),image:o().describe("Asset image"),price:h().describe("Price in USD")}),yi=Gr,Xt=m({assets:c(v(fi)),maxStreamingQuantity:h().optional(),referrer:o().optional(),streamingInterval:h().optional(),tags:v(n.enum(Ht))}),Jt=Xt.extend({affiliate:c(o()),affiliateFee:c(o()),approvalAddress:c(o().describe("Approval address for swap")),chainflip:yi.optional(),garden:Nt.optional(),near:Nt.optional(),priceImpact:c(h().describe("Price impact")),referrer:c(o()),txType:c(n.enum(Pe))}),Zt=v(m({code:n.enum(Le),display:o(),tooltip:o().optional()})),bi=m({buyAmount:o().describe("Buy amount"),buyAmountMaxSlippage:o().describe("Buy amount max slippage"),buyAsset:o().describe("Asset to buy"),fees:c(qe),provider:n.enum(C),sellAmount:o().describe("Sell amount"),sellAsset:o().describe("Asset to sell")}),Si=m({buyAsset:o().describe("Asset to buy"),destinationAddress:c(o().describe("Destination address")),estimatedTime:c(We),expectedBuyAmount:o().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:o().describe("Expected Buy amount max slippage"),expiration:c(o().describe("Expiration")),fees:qe,inboundAddress:c(o().describe("Inbound address")),legs:v(bi),memo:c(o().describe("Memo")),meta:Jt,providers:v(n.enum(C)),routeId:o().describe("Route ID"),sellAmount:o().describe("Sell amount"),sellAsset:o().describe("Asset to sell"),sourceAddress:c(o().describe("Source address")),targetAddress:c(o().describe("Target address")),totalSlippageBps:h().describe("Total slippage in bps"),tx:c(_i),txType:c(n.enum(Pe)),warnings:Zt}),en=m({error:c(o().describe("Error message")),providerErrors:c(v(m({errorCode:c(n.enum(oe)),message:c(o()),provider:n.enum(C).optional()}))),quoteId:o().describe("Quote ID"),routes:v(Si)}),tn=n.object({chainId:n.enum(q),createdAt:n.date(),id:n.number(),unit:n.string(),value:n.string()}),Ai=n.array(tn),nn=n.union([tn,Ai]),ia=v(m({chain:n.enum(Oe),decimal:h(),identifier:o(),symbol:o(),ticker:o(),value:o()})),sa=n.union([n.object({amount:n.string(),spender:n.string(),tokenIdentifier:n.string(),userWalletAddress:n.string()}),n.object({amount:n.string(),chainId:n.enum(q),spender:n.string(),tokenContractAddress:n.string(),userWalletAddress:n.string()}),n.object({routeId:n.string()})]),oa=n.object({approvalTransaction:n.optional(n.object({data:n.string(),from:n.string(),gasLimit:n.optional(n.string()),gasPrice:n.optional(n.string()),to:n.string(),value:H})),approvedAmount:n.string(),isApproved:n.boolean()}),Ti=n.object({data:n.string().describe("Encoded approval call data"),from:n.string().describe("User wallet address"),gasLimit:n.string().optional().describe("Estimated gas limit"),gasPrice:n.string().optional().describe("Current gas price"),to:n.string().describe("Token contract address"),value:H.describe("ETH value (always '0' for approvals)")}),wi=n.object({tx:n.string(),txType:n.literal("STELLAR")}),xi=n.union([Ti,wi]),Mt=n.object({buyAmount:n.string().describe("Buy amount").optional(),buyAmountMaxSlippage:n.string().describe("Buy amount max slippage").optional(),buyAsset:n.string().describe("Asset to buy"),expectedBuyAmount:n.string().describe("Expected Buy amount").optional(),expectedBuyAmountMaxSlippage:n.string().describe("Expected Buy amount max slippage").optional(),fees:qe,provider:n.enum(C),sellAmount:n.string().describe("Sell amount"),sellAsset:n.string().describe("Asset to sell")}),rn=Mt.extend({estimatedTime:n.optional(We),expiration:n.optional(n.string().describe("Expiration")),legs:n.array(Mt),providers:n.array(n.enum(C)),routeId:n.string().describe("Route ID"),totalSlippageBps:n.number().describe("Total slippage in bps"),warnings:Zt}).omit({provider:!0}),sn=n.object({method:n.string(),payload:n.optional(n.unknown()),url:n.string()}),Ri=rn.extend({meta:Xt,nextActions:n.optional(n.array(sn))}),aa=n.object({error:n.optional(n.string().describe("Error message")),providerErrors:n.optional(n.array(n.object({errorCode:n.optional(n.enum(oe)),message:n.optional(n.string()),provider:n.enum(C).optional()}))),quoteId:n.string().describe("Quote ID"),routes:n.array(Ri)}),la=n.object({providers:n.array(n.enum(C)).optional().describe("Optional list of providers to query for trading pairs"),sellAsset:n.string().describe("Asset identifier to sell (e.g., 'BTC.BTC' or 'ETH.ETH')")}),vi=n.object({chain:n.enum(Oe).describe("Chain the asset is on"),identifier:n.string().describe("Asset identifier (e.g., 'ETH.USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')"),providers:n.array(n.enum(C)).describe("Providers that support this trading pair"),symbol:n.string().describe("Asset symbol"),ticker:n.string().describe("Asset ticker")}),da=n.object({buyAssets:n.array(vi).describe("List of assets that can be swapped to"),sellAsset:n.string().describe("The input sell asset identifier")}),on=rn.extend({destinationAddress:n.string().describe("Destination address"),inboundAddress:n.optional(n.string().describe("Inbound address")),memo:n.optional(n.string().describe("Memo to include in the transaction")),meta:Jt,sourceAddress:n.string().describe("Source address"),targetAddress:n.optional(n.string().describe("Target address")),tx:c(Qt),txType:n.optional(n.enum(Pe))}),Ii=n.object({data:n.optional(n.record(n.string(),n.string().optional())),errorCode:n.enum(oe),message:n.string().optional(),provider:n.enum(C).optional()}),ca=n.object({error:n.optional(n.string().describe("Error message")),providerErrors:n.optional(n.array(Ii)),quoteId:n.string().describe("Quote ID"),routes:n.array(on)}),an=on.extend({approvalTx:xi.optional().describe("Optional approval transaction required before swap execution"),nextActions:n.optional(n.array(sn)),swapId:n.string().describe("The unique swap ID for tracking")}),Ci={CANCELLED:"CANCELLED",EXPIRED:"EXPIRED",FAILED:"FAILED",FILLED:"FILLED",OPEN:"OPEN",PARTIAL:"PARTIAL",PENDING:"PENDING",SUBMITTED:"SUBMITTED"},Oi={Cardano:"cardano",Evm:"evm",Near:"near",Psbt:"psbt",Ripple:"ripple",Solana:"solana",Starknet:"starknet",Stellar:"stellar",Sui:"sui",Ton:"ton",Tron:"tron"};function D(e){return n.union([e,n.string()])}var Ge=D(n.enum(Ci)),je=n.object({method:n.string(),payload:n.optional(n.unknown()),url:n.string()}),ln=n.array(n.object({code:n.string(),display:n.string(),tooltip:n.string().optional()})),dn=n.array(n.object({amount:n.string(),amountBps:n.number().optional(),asset:n.string(),chain:n.string(),protocol:D(n.enum(C)),type:D(n.enum(_e))})),cn=n.object({crossChain:n.array(n.object({assets:n.array(n.string()),chainIds:n.array(D(n.enum(q))),provider:D(n.enum(C))})),singleChain:n.array(n.object({assets:n.array(n.string()),chainId:D(n.enum(q)),provider:D(n.enum(C))}))}),pa=n.object({affiliateFee:n.number().min(0).max(1000).optional(),buyAmount:n.string().optional(),buyAsset:n.string(),destinationAddress:n.string().optional(),expiresAt:n.number().int().positive().optional(),limitPrice:n.string().optional().describe("buyAsset per 1 sellAsset"),providers:n.array(n.enum(C)).optional(),sellAmount:n.string().optional(),sellAsset:n.string(),sourceAddress:n.string().optional()}),Pi=n.object({buyAmount:n.string(),buyAsset:n.string(),effectiveFillPrice:n.string(),fees:dn.optional(),integratorFeeBps:n.number(),limitPrice:n.string(),maxExpirationSeconds:n.number(),minExpirationSeconds:n.number(),nextActions:n.optional(n.array(je)),provider:D(n.enum(C)),routeId:n.string(),sellAmount:n.string(),sellAsset:n.string(),spotPrice:n.string(),spotPriceDeviationBps:n.number(),takerFeeBps:n.number(),warnings:ln.optional()}),pn=n.object({error:n.string().optional(),providerErrors:n.optional(n.array(n.object({errorCode:n.optional(n.string()),message:n.optional(n.string()),provider:D(n.enum(C)).optional()}))),quoteId:n.string(),routes:n.array(Pi)}),ua=n.object({allowMultipleFills:n.boolean().optional(),allowPartialFill:n.boolean().optional(),destinationAddress:n.string().min(1),expiresAt:n.number().int().positive().describe("Unix timestamp in seconds"),routeId:n.string(),sourceAddress:n.string().min(1)}),ki=n.object({domain:n.looseObject({chainId:n.number(),name:n.string(),verifyingContract:n.string(),version:n.string()}),message:n.record(n.string(),n.unknown()),primaryType:n.string(),types:n.record(n.string(),n.array(n.object({name:n.string(),type:n.string()})))}),Li=n.strictObject({data:n.string(),from:n.string().optional(),gas:H.optional(),gasPrice:H.optional(),maxFeePerGas:H.optional(),maxPriorityFeePerGas:H.optional(),to:n.string(),type:H.optional(),value:H}),Ei=n.object({chainId:n.number().optional(),memo:n.string().optional(),txType:n.enum(Oi)}),Ni=n.object({data:n.string(),from:n.string(),gasLimit:n.string().optional(),gasPrice:n.string().optional(),to:n.string(),value:n.string()}),un=n.object({approvalTx:Ni.optional(),depositAddress:n.string().optional(),depositAmount:n.string().optional(),depositMemo:n.string().optional(),isApproved:n.boolean().optional(),nextActions:n.array(je),orderHash:n.string(),orderId:n.string(),tx:n.union([n.string(),Li,n.record(n.string(),n.unknown()),n.array(n.unknown())]).nullable(),txMeta:Ei.nullable(),typedData:ki.nullable(),warnings:ln.optional()}),mn=n.object({createdAt:n.string(),orderHash:n.string(),orderId:n.string(),status:Ge}),Di=n.object({blockNumber:n.number().int().optional(),chainId:D(n.enum(q)),txHash:n.string(),type:D(n.enum(["fill","cancel","deposit","withdraw","refund"]))}),Ye=n.object({buyAmount:n.string(),buyAsset:n.string(),cancelRequestedAt:n.string().optional(),chainId:D(n.enum(q)),createdAt:n.string(),depositHash:n.string().optional(),expiresAt:n.string(),fees:dn,filledBuyAmount:n.string(),filledSellAmount:n.string(),limitPrice:n.string(),maker:n.string(),orderHash:n.string(),orderId:n.string(),provider:D(n.enum(C)),receiver:n.string().nullable(),sellAmount:n.string(),sellAsset:n.string(),status:Ge,txHashes:n.array(Di).optional(),updatedAt:n.string(),usdValueClose:n.string().nullable().optional(),usdValueOpen:n.string().nullable().optional(),withdrawHash:n.string().optional()}),ze=n.object({nextCursor:n.string().optional(),orders:n.array(Ye)}),Mi=n.object({domain:n.looseObject({name:n.string(),version:n.string()}),message:n.looseObject({action:n.literal("cancel_and_withdraw"),chain:n.string(),expiry:n.number(),l1Address:n.string(),nonce:n.number(),payload:n.looseObject({orderId:n.string()})}),primaryType:n.literal("CancelAndWithdraw"),types:n.looseObject({CancelAndWithdraw:n.array(n.object({name:n.string(),type:n.string()})),CancelAndWithdrawPayload:n.array(n.object({name:n.string(),type:n.string()})),EIP712Domain:n.array(n.object({name:n.string(),type:n.string()}))})}),Vi=n.strictObject({chainId:n.number(),data:n.string(),from:n.string(),to:n.string(),value:n.string()}),gn=n.object({btcSignaturePreimage:n.string().nullable(),cancelTx:Vi.nullable(),nextActions:n.array(je),orderId:n.string(),typedData:Mi.nullable()}),_n=n.object({cancelRequestedAt:n.string().optional(),orderId:n.string(),status:Ge,txHash:n.string().optional(),withdrawId:n.string().optional()});var P=_.extend({dynamicHeader:async()=>{let e=A.get("widgetId"),t=A.get("widgetKey");if(e&&t&&typeof window<"u"){let i=Math.floor(Date.now()/1000),s=window.location.origin,a=await dt(t,e,s,i);return{Origin:s,"X-Signature":a,"X-Timestamp":i.toString(),"x-widget-id":e}}let{swapKit:r}=A.get("apiKeys");return r?{"x-api-key":r}:{}}});async function Ui(e){let t=await P.post(O("/track"),{json:e});try{let r=Yt.safeParse(t);if(!r.success)throw new b("api_v2_invalid_response",r.error);return r.data}catch(r){return t}}async function Bi(e){let{getQuote:t}=A.get("endpoints");if(t)return t(e);let i=A.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",s=await P.post(O(i),{json:e});if(s.error)throw new b("api_v2_server_error",{message:s.error});try{let a=en.safeParse(s);if(!a.success)throw new b("api_v2_invalid_response",a.error);return a.data}catch{return s}}async function $i(e){let{getRouteWithTx:t}=A.get("endpoints");if(t)return t(e);let i=A.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",s=await P.post(O(i),{json:e});try{let a=an.safeParse(s);if(!a.success)throw new b("api_v2_invalid_response",a.error);return a.data}catch(a){return console.error(new b("api_v2_invalid_response",a)),s}}async function Fi({chain:e,address:t,scamFilter:r=!0}){let{getBalance:i}=A.get("endpoints");if(i)return i({address:t,chain:e});let s=O(`/balance?chain=${e}&address=${t}`),a=await P.get(s),l=Array.isArray(a)?a:[];return r?ls(l):l}function Ki(e){let t=Hi(e).with({routeId:pe.string,spender:pe.string},({routeId:r,spender:i})=>O(`/approve?routeId=${r}&sourceAddress=${i}`)).with({assetValue:pe.instanceOf(N),spender:pe.string,userWallet:pe.string},({spender:r,userWallet:i,assetValue:s})=>O(`/approve?tokenIdentifier=${s.toString()}&userWalletAddress=${i}&spender=${r}&amount=${s.getValue("string")}`)).exhaustive();return P.get(t)}function qi(){let e=O("/providers");return P.get(e)}function Wi(e){let t=O(`/tokens?provider=${e}`);return P.get(t)}function Gi({query:e,chain:t,page:r,limit:i}){let s=new URLSearchParams({query:e});if(t!==void 0)s.set("chain",t);if(r!==void 0)s.set("page",r.toString());if(i!==void 0)s.set("limit",i.toString());let a=O(`/tokens/search?${s.toString()}`);return P.get(a)}async function ji(e){let t=O("/price"),r=await P.post(t,{json:e});try{let i=qt.safeParse(r);if(!i.success)throw new b("api_v2_invalid_response",i.error);return i.data}catch(i){throw new b("api_v2_invalid_response",i)}}async function Yi(){let e=O("/gas"),t=await P.get(e);try{let r=nn.safeParse(t);if(!r.success)throw new b("api_v2_invalid_response",r.error);return Array.isArray(r)?r:[r]}catch(r){throw new b("api_v2_invalid_response",r)}}async function zi(e){let{destinationAddress:t}=e;if(!t)throw new b("chainflip_broker_invalid_params");let r=A.get("integrations").chainflip?.brokerUrl||O("/chainflip/broker/channel"),i=await P.post(r,{json:e});try{let s=Gt.safeParse(i);if(!s.success)throw new b("api_v2_invalid_response",s.error);return s.data}catch(s){throw new b("api_v2_invalid_response",s)}}async function Qi(e){let{destinationAddress:t}=e;if(!t)throw new b("chainflip_broker_invalid_params");let r=O("/near/channel"),i=await P.post(r,{json:e});try{let s=jt.safeParse(i);if(!s.success)throw new b("api_v2_invalid_response",s.error);return s.data}catch(s){throw new b("api_v2_invalid_response",s)}}function W(e,t){let r=e.safeParse(t);if(!r.success)throw new b("api_v2_invalid_response",r.error);return r.data}async function Xi(){let{getLimitOrderTokens:e}=A.get("endpoints"),t=e?await e():await P.get(O("/v3/limit/tokens"));return W(cn,t)}async function Ji(e){let{getLimitOrderQuote:t}=A.get("endpoints"),r=t?await t(e):await P.post(O("/v3/limit/quote"),{json:e});return W(pn,r)}async function Zi(e){let{buildLimitOrder:t}=A.get("endpoints"),r=t?await t(e):await P.post(O("/v3/limit/build"),{json:e,retry:{maxRetries:0}});return W(un,r)}async function es(e){let{submitLimitOrder:t}=A.get("endpoints"),r=t?await t(e):await P.post(O("/v3/limit/submit"),{json:e,retry:{maxRetries:0}});return W(mn,r)}async function ts(e={}){let{getLimitOrders:t}=A.get("endpoints");if(t)return W(ze,await t(e));let{status:r,...i}=e,s=new URLSearchParams;for(let[p,g]of Object.entries(i))if(g!==void 0)s.set(p,String(g));for(let p of r===void 0?[]:[r].flat())s.append("status",p);let a=s.toString(),l=await P.get(O(`/v3/limit/orders${a?`?${a}`:""}`));return W(ze,l)}async function ns(e){let{getLimitOrder:t}=A.get("endpoints"),r=t?await t(e):await P.get(O(`/v3/limit/orders/${encodeURIComponent(e)}`));return W(Ye,r)}async function rs(e){let{buildLimitOrderCancel:t}=A.get("endpoints"),r=t?await t(e):await P.post(O("/v3/limit/cancel/build"),{json:e,retry:{maxRetries:0}});return W(gn,r)}async function is(e){let{submitLimitOrderCancel:t}=A.get("endpoints"),r=t?await t(e):await P.post(O("/v3/limit/cancel/submit"),{json:e,retry:{maxRetries:0}});return W(_n,r)}function O(e){let{isDev:t,apiUrl:r,devApiUrl:i}=A.get("envs"),{enabled:s,quoteUrl:a,swapUrl:l}=A.get("localMode");if(s&&e){let[g]=e.split("?");if(g==="/quote"||g==="/v3/quote")return`${a}${e}`;if(g==="/swap"||g==="/v3/swap")return`${l}${e}`}return`${t?i:r}${e}`}function ss(e){try{return N.from({asset:e.identifier})}catch{return}}var os=new Set(["OP.OP"]),as=/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/im;function ls(e){return e.filter((t)=>{let r=ss(t);if(!r)return!1;if(os.has(r.toString().toUpperCase()))return!0;return(!Qe.includes(r.chain)||r.isGasAsset||!!r.address)&&!as.test(r.ticker)})}async function ds(e){let{getSwapTo:t}=A.get("endpoints");if(t)return t(e);let r=new URLSearchParams({sellAsset:e.sellAsset});if(e.providers?.length)for(let l of e.providers)r.append("providers",l);let i=O(`/swapTo?${r.toString()}`),s=await P.get(i);if(!Array.isArray(s))return{buyAssets:[],sellAsset:e.sellAsset};let a=[];for(let l of s)try{let p=N.from({asset:l});a.push({chain:p.chain,identifier:p.toString(),providers:[],symbol:p.symbol,ticker:p.ticker})}catch{}return{buyAssets:a,sellAsset:e.sellAsset}}var Je={};nt(Je,{getInboundAddresses:()=>_s,getLastBlock:()=>ps,getMimirInfo:()=>gs,getNodes:()=>ms,getRunePoolInfo:()=>fs,getRunePoolProviderInfo:()=>ys,getTHORNodeTNSDetails:()=>hn,getTNSPreferredAsset:()=>hs,getTcyClaimer:()=>As,getTcyClaimers:()=>Ts,getTcyStaker:()=>bs,getTcyStakers:()=>Ss,getThorchainQueue:()=>us});function V(e){let t=A.get("thornodeUrls");return`${e==="mayachain"?t.MAYA:t.THOR}/${e??"thorchain"}`}function cs(e){let t=e==="mayachain"?"mayaname":"thorname";return`${V(e)}/${t}`}function ps(e="thorchain"){return _.get(`${V(e)}/lastblock`)}function us(e){return _.get(`${V(e)}/queue`)}function ms(e){return _.get(`${V(e)}/nodes`)}function gs(e){return _.get(`${V(e)}/mimir`)}function _s(e){return _.get(`${V(e)}/inbound_addresses`)}async function hn({type:e,name:t}){try{return await _.get(`${cs(e)}/${t}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:t,owner:"",preferred_asset:""}}}async function hs({type:e,tns:t}){let r=await hn({name:t,type:e});if(!r.preferred_asset||r.preferred_asset===".")return;return N.from({asset:r.preferred_asset,asyncTokenLookup:!0})}function fs(e){return _.get(`${V(e)}/runepool`)}function ys({type:e,thorAddress:t}){return _.get(`${V(e)}/rune_provider/${t}`)}function bs({type:e,address:t}){return _.get(`${V(e)}/tcy_staker/${t}`)}function Ss(e){return _.get(`${V(e)}/tcy_stakers`)}function As({type:e,address:t}){return _.get(`${V(e)}/tcy_claimer/${t}`)}function Ts(e){return _.get(`${V(e)}/tcy_claimers`)}var Ra={...Xe,mayachainMidgard:Et,thorchainMidgard:Lt,thornode:Je};
5
+ export{Rs as a,oe as b,Le as c,C as d,_e as e,wn as f,xn as g,Rn as h,b as i,Os as j,he as k,st as l,Ls as m,vn as n,Es as o,L as p,A as q,_ as r,dt as s,zs as t,ae as u,De as v,Fn as w,J as x,no as y,ro as z,io as A,ho as B,Qn as C,wt as D,xt as E,Rt as F,Se as G,Ve as H,Y as I,de as J,fo as K,yo as L,Z as M,K as N,ar as O,N as P,Po as Q,Ie as R,Ht as S,Pe as T,Ut as U,Bt as V,$t as W,Ft as X,Fo as Y,Ko as Z,qo as _,Wo as $,ie as aa,Kt as ba,Go as ca,qt as da,jo as ea,Yo as fa,Wt as ga,Gr as ha,Gt as ia,Nt as ja,zo as ka,jt as la,Yt as ma,Qo as na,Xo as oa,qe as pa,We as qa,ti as ra,Jo as sa,Zo as ta,ni as ua,ri as va,ii as wa,ea as xa,di as ya,ci as za,pi as Aa,ui as Ba,ta as Ca,mi as Da,gi as Ea,zt as Fa,na as Ga,hi as Ha,ra as Ia,fi as Ja,yi as Ka,Xt as La,Jt as Ma,Zt as Na,Si as Oa,en as Pa,tn as Qa,nn as Ra,sa as Sa,oa as Ta,Ti as Ua,wi as Va,xi as Wa,aa as Xa,la as Ya,vi as Za,da as _a,on as $a,Ii as ab,ca as bb,an as cb,Ci as db,Oi as eb,cn as fb,pa as gb,Pi as hb,pn as ib,ua as jb,ki as kb,Li as lb,Ei as mb,Ni as nb,un as ob,mn as pb,Di as qb,Ye as rb,ze as sb,Mi as tb,Vi as ub,gn as vb,_n as wb,Ra as xb};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{$ as yr,$a as En,A as qt,Aa as Xr,B as Gt,Ba as qr,C as Yt,Ca as Gr,D as Jt,Da as Yr,E as Qt,Ea as Jr,F as Zt,Fa as Qr,G as er,Ga as Zr,H as tr,Ha as en,I as rr,Ia as tn,J as nr,Ja as rn,K as or,Ka as nn,L as ir,La as on,M as ar,Ma as an,N as sr,Na as sn,O as ur,Oa as un,P as cr,Pa as cn,Q as f,Qa as pn,R as pr,Ra as dn,S as dr,Sa as mn,T as mr,Ta as ln,U as lr,Ua as hn,V as hr,Va as fn,W as fr,Wa as wn,X as wr,Xa as gn,Y as gr,Ya as Pn,Z as Pr,Za as vn,_ as vr,_a as yn,a as v,aa as Er,ab as bn,b as Mt,ba as br,bb as Tn,c as $t,ca as Tr,cb as An,d as Wt,da as Ar,e as Rt,ea as xr,f as L,fa as Sr,g as Dt,ga as _r,h as re,ha as Cr,i as m,ia as Mr,j as Ot,ja as $r,k as c,ka as Wr,l as It,la as Rr,m as Nt,ma as Dr,n as kt,na as Or,o as Ft,oa as Ir,p as x,pa as Nr,q as Lt,qa as kr,r as Bt,ra as Fr,s as Ut,sa as Lr,t as W,ta as Br,u as Kt,ua as Ur,v as Ht,va as Kr,w as jt,wa as Hr,x as zt,xa as jr,y as Vt,ya as zr,z as Xt,za as Vr}from"./chunk-d8rmhscp.js";export*from"@swapkit/tokens";export*from"@swapkit/types";var B={average:1,fast:1.5,fastest:2};function S(e="average"){let t=x.get("feeMultipliers");if(t&&t[e]!==void 0)return t[e];return B[e]}function U(e="average"){let t=S(e),r=10n,n=BigInt(Math.round(t*10));return{denominator:r,numerator:n}}function he(e,t="average"){let{numerator:r,denominator:n}=U(t);return e*r/n}function fe(e,t="average",r=!1){let n=S(t),o=e*n;return r?Math.floor(o):o}import{Chain as P,EVMChains as K}from"@swapkit/types";import{match as H}from"ts-pattern";function w(e,t){let r=e.length-1;return e.map((o,i)=>{if(i===r&&t.index!==void 0)return t.index;if(i===0&&t.purpose!==void 0)return t.purpose;if(i===2&&t.account!==void 0)return t.account;if(i===3&&t.change!==void 0)return t.change;return o})}var h={bech32:84,legacy:44,p2sh:49,taproot:86},_;((o)=>{o.P2PKH="P2PKH";o.P2SH_P2WPKH="P2SH_P2WPKH";o.P2WPKH="P2WPKH";o.P2TR="P2TR"})(_||={});var j=Object.freeze({["P2PKH"]:{inputSize:148,outputSize:34,purpose:h.legacy,witness:!1},["P2SH_P2WPKH"]:{inputSize:91,outputSize:32,purpose:h.p2sh,witness:!0},["P2WPKH"]:{inputSize:68,outputSize:31,purpose:h.bech32,witness:!0},["P2TR"]:{inputSize:58,outputSize:43,purpose:h.taproot,witness:!0}}),z=Object.values(_);function V(e){if(e===void 0)return;return z.find((t)=>j[t].purpose===e)}function X(e){if(!e)return;if(typeof e!=="string")return e[0];let t=Number.parseInt(e.replace(/^[mM]'?\//,"").split("/")[0]??"",10);return Number.isNaN(t)?void 0:t}function ye(e){return V(X(e))}var q=Object.freeze([P.Near,P.Stellar,P.Sui]),Ee=Object.freeze([P.Ton]);function G({chain:e,derivationPath:t,index:r=0}){if(t)return t;return w(v[e],q.includes(e)?{account:r}:{index:r})}function Y([e,t,r,n,o],{allHardened:i}={}){let s=i?"'":"",a=typeof o!=="number";if(typeof n!=="number")return`m/${e}'/${t}'/${r}'`;return`m/${e}'/${t}'/${r}'/${n}${s}${a?"":`/${o}${s}`}`}function be({chain:e,index:t,addressIndex:r=0,type:n}){let o=v[e],i=K.includes(e)?"evm":e===P.Solana?"solana":"other";return H([i,n]).with(["evm","legacy"],["evm","account"],()=>[44,60,0,t]).with(["evm","ledgerLive"],()=>[44,60,t,0,r]).with(["evm","nativeSegwitMiddleAccount"],["evm","segwit"],["evm",void 0],()=>w(o,{index:t})).with(["solana","account"],()=>[44,501,0,t]).with(["solana","legacy"],["solana","ledgerLive"],["solana","nativeSegwitMiddleAccount"],["solana","segwit"],["solana",void 0],()=>w(o,{index:t})).with(["other","nativeSegwitMiddleAccount"],()=>w(o,{account:t,index:r,purpose:h.bech32})).with(["other","segwit"],()=>w(o,{account:0,index:t,purpose:h.p2sh})).with(["other","legacy"],()=>w(o,{account:0,index:t,purpose:h.legacy})).with(["other","account"],["other","ledgerLive"],["other",void 0],()=>G({chain:e,index:t})).exhaustive()}function Te(e){let[t,r]=e.split("/").map((n)=>Number.parseInt(n,10));switch(r){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var Ae=Object.freeze(Object.fromEntries(Object.keys(v).map((e)=>[e,Y(v[e])])));import{Chain as J,getChainConfig as Q}from"@swapkit/types";function Z({liquidityUnits:e,poolUnits:t,runeDepth:r}){let n=p(e),o=p(t),i=p(r),s=n.mul(i),a=o.mul(o).mul(2),u=o.mul(n).mul(2),d=n.mul(n),l=o.mul(o).mul(o);return s.mul(a.sub(u).add(d)).div(l)}function ee({liquidityUnits:e,poolUnits:t,assetDepth:r}){let n=p(e),o=p(t),i=p(r),s=n.mul(i),a=o.mul(o).mul(2),u=o.mul(n).mul(2),d=n.mul(n),l=s.mul(a.sub(u).add(d)),g=o.mul(o).mul(o);return l.div(g)}function Ce({percent:e,runeDepth:t,liquidityUnits:r,poolUnits:n}){return Z({liquidityUnits:r,poolUnits:n,runeDepth:t}).mul(e)}function Me({percent:e,assetDepth:t,liquidityUnits:r,poolUnits:n}){return ee({assetDepth:t,liquidityUnits:r,poolUnits:n}).mul(e)}function p(e){return f.fromBigInt(BigInt(e),Q(J.THORChain).baseDecimal)}function te({liquidityUnits:e,poolUnits:t,runeDepth:r,assetDepth:n}){return{assetAmount:p(n).mul(e).div(t),runeAmount:p(r).mul(e).div(t)}}function $e({liquidityUnits:e,poolUnits:t,runeDepth:r,assetDepth:n,percent:o}){return Object.fromEntries(Object.entries(te({assetDepth:n,liquidityUnits:e,poolUnits:t,runeDepth:r})).map(([i,s])=>[i,s.mul(o)]))}function We({runeDepth:e,poolUnits:t,assetDepth:r,liquidityUnits:n,runeAmount:o,assetAmount:i}){let s=new f({decimal:8,value:e}),a=new f({decimal:8,value:r}),u=new f({decimal:8,value:t}),d=new f({decimal:8,value:o}),l=new f({decimal:8,value:i}),g=d.mul(a),T=l.mul(s),O=d.mul(l),I=s.mul(a),N=u.mul(g.add(T.add(O.mul(2)))),k=g.add(T.add(I.mul(2))),A=N.div(k),b=p(n).add(A);if(A.getBaseValue("number")===0)return b.div(u).getBaseValue("number");let F=u.add(b);return b.div(F).getBaseValue("number")}function Re({runeAmount:e,assetAmount:t,runeDepth:r,assetDepth:n}){if(e==="0"||t==="0"||r==="0"||n==="0")return 0;let o=p(r),i=p(n),s=p(t),a=p(e),u=s.mul(o).sub(i.mul(a)),d=i.mul(a).add(o.mul(i));return Math.abs(u.div(d).getBaseValue("number"))}import{Chain as y}from"@swapkit/types";import{match as ne}from"ts-pattern";function Fe({type:e,address:t}){return`${e}:${t}`}function Le({address:e,unbondAmount:t}){return`${"UNBOND"}:${e}:${t}`}function Be(e){return E("POOL+",e)}function Ue({chain:e,symbol:t,address:r,...n}){let o=oe({chain:e,symbol:t}),i=r?`:${r}:`:":";return E(`${"+"}:${o}${i}`,n)}function Ke({chain:e,symbol:t,ticker:r,basisPoints:n,targetAsset:o}){let i=e==="ETH"&&r!=="ETH"?`${r}-${t.slice(-3)}`:t,s=o?`:${o}`:"";return`${"-"}:${e}.${i}:${n}${s}`}function He({basisPoints:e,...t}){return E(`${"POOL-"}:${e}`,t)}function je({name:e,chain:t,address:r,owner:n}){let o=`${"~"}:${e}:${t}:${r}`,i=n?`:${n}`:"";return`${o}${i}`}function ze({name:e,chain:t,asset:r,payout:n,owner:o}){return`${"~"}:${e}:${t}:${n}:${o}:${r}`}function Ve(e,{address:t}){return`${e}:${t}`}function Xe(e,{unstakeBps:t,...r}){let n=t?`:${t}`:"",o=`${e}${n}`;return E(`${o}`,r)}function E(e,{affiliateAddress:t,affiliateBasisPoints:r}={}){let n=`${e}${t?`:${t}:${r||0}`:""}`;return n.endsWith(":")?n.slice(0,-1):n}function oe({chain:e,symbol:t}){return ne(e).with(y.Bitcoin,y.Dogecoin,y.Litecoin,()=>e.slice(0,1).toLowerCase()).with(y.BitcoinCash,()=>"c").otherwise(()=>`${e}.${t}`)}function qe(e){if(e<0)throw new m({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:e}});return Math.round((10+Math.max(0,e-1)*1.0512)*1e8)/1e8}function Ge(e){if(e<0)throw new m({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:e}});return Math.round((10+Math.max(0,e-1)*1.0512)*10000000000)/10000000000}function Ye(e){if(e.length>30)return!1;let t=/^[a-zA-Z0-9+_-]+$/g;return!!e.match(t)}import{getChainConfig as R}from"@swapkit/types";function rt(){return typeof window.ethereum<"u"}function nt(e){return ie().includes(e)}function ie(){let e=window?.ethereum&&!window.ethereum?.isBraveWallet,t=window?.vultisig,r=window?.ethereum?.isBraveWallet,n=window?.ethereum?.isTrust||window?.trustwallet,o=window?.ethereum?.overrideIsMetaMask&&window?.ethereum?.selectedProvider?.isCoinbaseWallet||window?.coinbaseWalletExtension,i=window?.bitkeep?.ethereum,s=window?.$onekey?.ethereum,a=[];if(e)a.push(c.METAMASK);if(t)a.push(c.VULTISIG);if(r)a.push(c.BRAVE);if(n)a.push(c.TRUSTWALLET_WEB);if(o)a.push(c.COINBASE_WEB);if(de())a.push(c.OKX_MOBILE);if(i)a.push(c.BITGET);if(s)a.push(c.ONEKEY);return a}var C=new Set([4001,5000,"ACTION_REJECTED"]);function M(e){if(!e||typeof e!=="object")return!1;let{code:t,error:r,info:n,data:o}=e;if(C.has(t))return!0;return[r,n?.error,o?.originalError].some((i)=>!!i&&typeof i==="object"&&C.has(i.code))}async function ae(e,t){if(!t)return!1;try{let{chainId:r}=await e.getNetwork();return BigInt(r)===BigInt(t)}catch{return!1}}async function se(e,t,r){let n=R(t);try{await D({method:"wallet_switchEthereumChain",params:[{chainId:n.chainIdHex}],provider:e})}catch(o){if(M(o))throw new m("helpers_failed_to_switch_network",{chain:t,error:o,reason:"user rejected request"});if(!r)throw new m("helpers_failed_to_switch_network",{chain:t,error:o,reason:"networkParams not provided"});try{await pe(e,r)}catch(i){throw new m("helpers_failed_to_switch_network",{chain:t,error:i,reason:M(i)?"user rejected adding the network":"failed to add the network"})}}}function ot({chains:e,supportedChains:t,walletType:r}){let n=e.filter((i)=>!i||t.includes(i));if(n.length===0)throw new m("wallet_chain_not_supported",{chain:e.join(", "),wallet:r});let o=e.filter((i)=>!t.includes(i));return W({condition:o.length>0,id:`wallet_chain_not_supported_${r}`,warning:`${r} wallet does not support the following chains: ${o.join(", ")}. These chains will be ignored.`}),n}function ue(e,t,r,n){return async(...o)=>{let{chainIdHex:i}=R(r);if(await ae(t,i))return e(...o);try{await se(t,r,n)}catch(s){if(s instanceof m)throw s;throw new m({errorKey:"helpers_failed_to_switch_network",info:{chain:r,error:s}})}return e(...o)}}function it({toolbox:e,chain:t,provider:r,methodNames:n=[],networkParams:o=ce(e)}){let s=[...n,"approve","approvedAmount","call","sendTransaction","transfer","isApproved","approvedAmount","EIP1193SendTransaction","getFeeData","broadcastTransaction","estimateCall","estimateGasLimit","estimateGasPrices","createContractTxObject"].reduce((a,u)=>{if(!e[u])return a;let d=e[u];if(typeof d!=="function")return a;let l=ue(d,r,t,o);return{...a,[u]:l}},{});return{...e,...s}}function ce(e){let t=e.getNetworkParams;if(typeof t!=="function")return;try{let r=t();return r&&typeof r==="object"&&"chainId"in r?r:void 0}catch{return}}function pe(e,t){return D({method:"wallet_addEthereumChain",params:[t],provider:e})}function at(e){window.ethereum?.on("accountsChanged",()=>e())}function st(){let{isTrust:e,isBraveWallet:t,overrideIsMetaMask:r,selectedProvider:n}=window?.ethereum||{};if(e)return c.TRUSTWALLET_WEB;if(t)return c.BRAVE;if(r&&n?.isCoinbaseWallet)return c.COINBASE_WEB;if(window?.$onekey?.ethereum)return c.ONEKEY;return c.METAMASK}function ut(){let e=[];function t(n){if(e.map((o)=>o.info.uuid).includes(n.detail.info.uuid))return;e.push(n.detail)}window.addEventListener("eip6963:announceProvider",t),window.dispatchEvent(new Event("eip6963:requestProvider"));function r(){window.removeEventListener("eip6963:announceProvider",t)}return{providers:e,removeEIP6963EventListener:r}}function de(){let e=navigator.userAgent,t=/iphone|ipad|ipod|ios/i.test(e),r=/android|XiaoMi|MiuiBrowser/i.test(e),n=t||r,o=/OKApp/i.test(e);return n&&o}function D({provider:e,params:t,method:r}){if(!e?.send)throw new m("helpers_not_found_provider");let n=t?Array.isArray(t)?t:[t]:[];return e.send(r,n)}export{q as ACCOUNT_INDEXED_CHAINS,vr as ApiV2ErrorSchema,ln as ApprovalTransactionSchema,Dt as ApproveMode,dn as ApproveRequestParams,mn as ApproveResponseSchema,ur as AssetValue,yr as AssetValueSchema,ar as BigIntArithmetics,_r as BrokerDepositChannelParamsSchema,rn as ChainflipMetadataSchema,Er as CoinGeckoMetadataSchema,qt as CommonAssetStrings,jr as CosmosTransactionSchema,B as DEFAULT_FEE_MULTIPLIERS,Sr as DepositChannelParamsSchema,Cr as DepositChannelResponseSchema,Ae as DerivationPath,Kr as EVMTransactionDetailsParamsSchema,Hr as EVMTransactionDetailsSchema,Br as EVMTransactionSchema,Mt as ErrorCode,Nr as EstimatedTimeSchema,L as FeeOption,Rt as FeeTypeEnum,Ir as FeesSchema,pn as GasResponseSchema,cn as GasSchema,qr as HYPERCORE_USDC_TOKEN_ID,Gr as HyperCoreEip712TypedDataSchema,Yr as HyperCoreSendAssetActionSchema,Qr as HyperCoreSendAssetTransactionSchema,Jr as HyperCoreTypedDataTransactionSchema,kt as LedgerErrorCode,re as MemoType,Mr as NearDepositChannelParamsSchema,$r as NearDepositChannelResultSchema,Wr as NearSwapResponseSchema,v as NetworkDerivationPath,xr as PriceRequestSchema,Tr as PriceResponseSchema,pr as PriorityLabel,lr as ProviderAction,Wt as ProviderName,Ar as QuoteRequestSchema,sn as QuoteResponseRouteItem,un as QuoteResponseSchema,yn as QuoteRouteV2Response,bn as QuoteV2ResponseSchema,wn as QuoteV3ResponseSchema,Lt as RequestClient,Zr as RouteLegSchema,en as RouteLegWithoutAddressesSchema,tn as RouteQuoteMetadataAssetSchema,nn as RouteQuoteMetadataSchema,on as RouteQuoteMetadataV2Schema,En as RouteQuoteProviderErrorSchema,dr as RouteQuoteTxType,an as RouteQuoteWarningSchema,Ee as SINGLE_WALLET_CHAINS,x as SKConfig,zr as StarknetTransactionSchema,hn as StellarApprovalTransactionSchema,fn as SwapApprovalTransactionSchema,An as SwapKitApi,m as SwapKitError,f as SwapKitNumber,Tn as SwapRouteV2ResponseSchema,Pn as SwapToAssetSchema,gn as SwapToRequestSchema,vn as SwapToResponseSchema,Vr as TONTransactionMessageSchema,Xr as TONTransactionSchema,br as TokenDetailsMetadataSchema,wr as TokenSchema,Rr as TrackerResponseSchema,Pr as TrackingRequestQuerySchema,gr as TrackingRequestSchema,fr as TrackingStatus,Or as TransactionDTOSchema,Dr as TransactionSchema,Ur as TronTransactionSchema,hr as TxnStatus,mr as TxnType,h as UTXOPurpose,_ as UTXOScriptType,j as UTXO_SCRIPT_TYPES,z as UTXO_SCRIPT_TYPE_LIST,c as WalletOption,$t as WarningCodeEnum,Kt as _rpcCache,at as addAccountsChangedCallback,pe as addEVMWalletNetwork,fe as applyFeeMultiplier,he as applyFeeMultiplierToBigInt,tr as assetFromString,Yt as decodeABIDynamicString,Gt as decodeABIString,Y as derivationPathToString,Jt as fetchTokenInfo,ot as filterSupportedChains,or as findAssetBy,ir as formatBigIntToSafeValue,er as getAssetType,ee as getAsymmetricAssetShare,Me as getAsymmetricAssetWithdrawAmount,Z as getAsymmetricRuneShare,Ce as getAsymmetricRuneWithdrawAmount,Xt as getChainIdentifier,Zt as getCommonAssetInfo,be as getDerivationPathFor,ut as getEIP6963Wallets,st as getETHDefaultWallet,We as getEstimatedPoolShare,Vt as getExplorerAddressUrl,zt as getExplorerTxUrl,S as getFeeMultiplier,U as getFeeMultiplierAsBigInt,Re as getLiquiditySlippage,Ge as getMAYANameCost,Ue as getMemoForDeposit,Fe as getMemoForLeaveAndBond,ze as getMemoForNamePreferredAssetRegister,je as getMemoForNameRegister,Be as getMemoForRunePoolDeposit,He as getMemoForRunePoolWithdraw,Ve as getMemoForTcyClaim,Xe as getMemoForTcyStake,Le as getMemoForUnbond,Ke as getMemoForWithdraw,cr as getMinAmountByChain,X as getPurposeFromPath,jt as getRPCUrl,Ht as getRPCUrlSync,te as getSymmetricPoolShare,$e as getSymmetricWithdraw,qe as getTHORNameCost,nr as getTokenLogoURI,ye as getUTXOScriptTypeForPath,V as getUTXOScriptTypeForPurpose,Te as getWalletFormatFor,nt as isDetected,Qt as isGasAsset,kr as isTransactionValue,M as isUserRejectedRequest,rt as isWeb3Detected,ie as listWeb3EVMWallets,de as okxMobileEnabled,rr as parseSymbolForAddress,Fr as parseTransactionValue,it as prepareNetworkSwitch,D as providerRequest,Ot as registerErrorCodes,Nt as registerWalletOption,G as resolveDerivationPath,Bt as signWidgetRequest,It as subscribeWalletOptionRegistration,Ft as swapKitConfigStore,se as switchEVMWalletNetwork,Lr as toHexTransactionValue,w as updateDerivationPath,sr as validateIdentifier,Ye as validateTNS,W as warnOnce,ue as wrapMethodWithNetworkSwitch,Ut as wrapWithThrow};
1
+ import{$ as Er,$a as bn,A as Gt,Aa as qr,B as Yt,Ba as Gr,C as Jt,Ca as Yr,D as Qt,Da as Jr,E as Zt,Ea as Qr,F as er,Fa as Zr,G as tr,Ga as en,H as rr,Ha as tn,I as nr,Ia as rn,J as or,Ja as nn,K as ir,Ka as on,L as ar,La as an,M as sr,Ma as sn,N as ur,Na as un,O as cr,Oa as cn,P as pr,Pa as pn,Q as dr,Qa as dn,R as f,Ra as mn,S as mr,Sa as ln,T as lr,Ta as hn,U as hr,Ua as fn,V as fr,Va as gn,W as gr,Wa as wn,X as wr,Xa as Pn,Y as Pr,Ya as vn,Z as vr,Za as yn,_ as yr,_a as En,a as v,aa as br,ab as Tn,b as Wt,ba as Tr,bb as An,c as $t,ca as Ar,cb as xn,d as Rt,da as xr,db as Sn,e as Dt,ea as Sr,eb as _n,f as L,fa as _r,fb as Cn,g as Ot,ga as Cr,gb as Mn,h as re,ha as Mr,hb as Wn,i as m,ia as Wr,ib as $n,j as kt,ja as $r,jb as Rn,k as c,ka as Rr,kb as Dn,l as It,la as Dr,lb as On,m as Nt,ma as Or,mb as kn,n as Ft,na as kr,nb as In,o as Lt,oa as Ir,ob as Nn,p as Bt,pa as Nr,pb as Fn,q as x,qa as Fr,qb as Ln,r as Ut,ra as Lr,rb as Bn,s as Kt,sa as Br,sb as Un,t as Ht,ta as Ur,tb as Kn,u as W,ua as Kr,ub as Hn,v as jt,va as Hr,vb as jn,w as zt,wa as jr,wb as zn,x as Vt,xa as zr,xb as Vn,y as Xt,ya as Vr,z as qt,za as Xr}from"./chunk-8wabqp6d.js";export*from"@swapkit/tokens";export*from"@swapkit/types";var B={average:1,fast:1.5,fastest:2};function S(e="average"){let t=x.get("feeMultipliers");if(t&&t[e]!==void 0)return t[e];return B[e]}function U(e="average"){let t=S(e),r=10n,n=BigInt(Math.round(t*10));return{denominator:r,numerator:n}}function he(e,t="average"){let{numerator:r,denominator:n}=U(t);return e*r/n}function fe(e,t="average",r=!1){let n=S(t),o=e*n;return r?Math.floor(o):o}import{Chain as P,EVMChains as K}from"@swapkit/types";import{match as H}from"ts-pattern";function g(e,t){let r=e.length-1;return e.map((o,i)=>{if(i===r&&t.index!==void 0)return t.index;if(i===0&&t.purpose!==void 0)return t.purpose;if(i===2&&t.account!==void 0)return t.account;if(i===3&&t.change!==void 0)return t.change;return o})}var h={bech32:84,legacy:44,p2sh:49,taproot:86},_;((o)=>{o.P2PKH="P2PKH";o.P2SH_P2WPKH="P2SH_P2WPKH";o.P2WPKH="P2WPKH";o.P2TR="P2TR"})(_||={});var j=Object.freeze({["P2PKH"]:{inputSize:148,outputSize:34,purpose:h.legacy,witness:!1},["P2SH_P2WPKH"]:{inputSize:91,outputSize:32,purpose:h.p2sh,witness:!0},["P2WPKH"]:{inputSize:68,outputSize:31,purpose:h.bech32,witness:!0},["P2TR"]:{inputSize:58,outputSize:43,purpose:h.taproot,witness:!0}}),z=Object.values(_);function V(e){if(e===void 0)return;return z.find((t)=>j[t].purpose===e)}function X(e){if(!e)return;if(typeof e!=="string")return e[0];let t=Number.parseInt(e.replace(/^[mM]'?\//,"").split("/")[0]??"",10);return Number.isNaN(t)?void 0:t}function ye(e){return V(X(e))}var q=Object.freeze([P.Near,P.Stellar,P.Sui]),Ee=Object.freeze([P.Ton]);function G({chain:e,derivationPath:t,index:r=0}){if(t)return t;return g(v[e],q.includes(e)?{account:r}:{index:r})}function Y([e,t,r,n,o],{allHardened:i}={}){let s=i?"'":"",a=typeof o!=="number";if(typeof n!=="number")return`m/${e}'/${t}'/${r}'`;return`m/${e}'/${t}'/${r}'/${n}${s}${a?"":`/${o}${s}`}`}function be({chain:e,index:t,addressIndex:r=0,type:n}){let o=v[e],i=K.includes(e)?"evm":e===P.Solana?"solana":"other";return H([i,n]).with(["evm","legacy"],["evm","account"],()=>[44,60,0,t]).with(["evm","ledgerLive"],()=>[44,60,t,0,r]).with(["evm","nativeSegwitMiddleAccount"],["evm","segwit"],["evm",void 0],()=>g(o,{index:t})).with(["solana","account"],()=>[44,501,0,t]).with(["solana","legacy"],["solana","ledgerLive"],["solana","nativeSegwitMiddleAccount"],["solana","segwit"],["solana",void 0],()=>g(o,{index:t})).with(["other","nativeSegwitMiddleAccount"],()=>g(o,{account:t,index:r,purpose:h.bech32})).with(["other","segwit"],()=>g(o,{account:0,index:t,purpose:h.p2sh})).with(["other","legacy"],()=>g(o,{account:0,index:t,purpose:h.legacy})).with(["other","account"],["other","ledgerLive"],["other",void 0],()=>G({chain:e,index:t})).exhaustive()}function Te(e){let[t,r]=e.split("/").map((n)=>Number.parseInt(n,10));switch(r){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var Ae=Object.freeze(Object.fromEntries(Object.keys(v).map((e)=>[e,Y(v[e])])));import{Chain as J,getChainConfig as Q}from"@swapkit/types";function Z({liquidityUnits:e,poolUnits:t,runeDepth:r}){let n=p(e),o=p(t),i=p(r),s=n.mul(i),a=o.mul(o).mul(2),u=o.mul(n).mul(2),d=n.mul(n),l=o.mul(o).mul(o);return s.mul(a.sub(u).add(d)).div(l)}function ee({liquidityUnits:e,poolUnits:t,assetDepth:r}){let n=p(e),o=p(t),i=p(r),s=n.mul(i),a=o.mul(o).mul(2),u=o.mul(n).mul(2),d=n.mul(n),l=s.mul(a.sub(u).add(d)),w=o.mul(o).mul(o);return l.div(w)}function Ce({percent:e,runeDepth:t,liquidityUnits:r,poolUnits:n}){return Z({liquidityUnits:r,poolUnits:n,runeDepth:t}).mul(e)}function Me({percent:e,assetDepth:t,liquidityUnits:r,poolUnits:n}){return ee({assetDepth:t,liquidityUnits:r,poolUnits:n}).mul(e)}function p(e){return f.fromBigInt(BigInt(e),Q(J.THORChain).baseDecimal)}function te({liquidityUnits:e,poolUnits:t,runeDepth:r,assetDepth:n}){return{assetAmount:p(n).mul(e).div(t),runeAmount:p(r).mul(e).div(t)}}function We({liquidityUnits:e,poolUnits:t,runeDepth:r,assetDepth:n,percent:o}){return Object.fromEntries(Object.entries(te({assetDepth:n,liquidityUnits:e,poolUnits:t,runeDepth:r})).map(([i,s])=>[i,s.mul(o)]))}function $e({runeDepth:e,poolUnits:t,assetDepth:r,liquidityUnits:n,runeAmount:o,assetAmount:i}){let s=new f({decimal:8,value:e}),a=new f({decimal:8,value:r}),u=new f({decimal:8,value:t}),d=new f({decimal:8,value:o}),l=new f({decimal:8,value:i}),w=d.mul(a),T=l.mul(s),O=d.mul(l),k=s.mul(a),I=u.mul(w.add(T.add(O.mul(2)))),N=w.add(T.add(k.mul(2))),A=I.div(N),b=p(n).add(A);if(A.getBaseValue("number")===0)return b.div(u).getBaseValue("number");let F=u.add(b);return b.div(F).getBaseValue("number")}function Re({runeAmount:e,assetAmount:t,runeDepth:r,assetDepth:n}){if(e==="0"||t==="0"||r==="0"||n==="0")return 0;let o=p(r),i=p(n),s=p(t),a=p(e),u=s.mul(o).sub(i.mul(a)),d=i.mul(a).add(o.mul(i));return Math.abs(u.div(d).getBaseValue("number"))}import{Chain as y}from"@swapkit/types";import{match as ne}from"ts-pattern";function Fe({type:e,address:t}){return`${e}:${t}`}function Le({address:e,unbondAmount:t}){return`${"UNBOND"}:${e}:${t}`}function Be(e){return E("POOL+",e)}function Ue({chain:e,symbol:t,address:r,...n}){let o=oe({chain:e,symbol:t}),i=r?`:${r}:`:":";return E(`${"+"}:${o}${i}`,n)}function Ke({chain:e,symbol:t,ticker:r,basisPoints:n,targetAsset:o}){let i=e==="ETH"&&r!=="ETH"?`${r}-${t.slice(-3)}`:t,s=o?`:${o}`:"";return`${"-"}:${e}.${i}:${n}${s}`}function He({basisPoints:e,...t}){return E(`${"POOL-"}:${e}`,t)}function je({name:e,chain:t,address:r,owner:n}){let o=`${"~"}:${e}:${t}:${r}`,i=n?`:${n}`:"";return`${o}${i}`}function ze({name:e,chain:t,asset:r,payout:n,owner:o}){return`${"~"}:${e}:${t}:${n}:${o}:${r}`}function Ve(e,{address:t}){return`${e}:${t}`}function Xe(e,{unstakeBps:t,...r}){let n=t?`:${t}`:"",o=`${e}${n}`;return E(`${o}`,r)}function E(e,{affiliateAddress:t,affiliateBasisPoints:r}={}){let n=`${e}${t?`:${t}:${r||0}`:""}`;return n.endsWith(":")?n.slice(0,-1):n}function oe({chain:e,symbol:t}){return ne(e).with(y.Bitcoin,y.Dogecoin,y.Litecoin,()=>e.slice(0,1).toLowerCase()).with(y.BitcoinCash,()=>"c").otherwise(()=>`${e}.${t}`)}function qe(e){if(e<0)throw new m({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:e}});return Math.round((10+Math.max(0,e-1)*1.0512)*1e8)/1e8}function Ge(e){if(e<0)throw new m({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:e}});return Math.round((10+Math.max(0,e-1)*1.0512)*10000000000)/10000000000}function Ye(e){if(e.length>30)return!1;let t=/^[a-zA-Z0-9+_-]+$/g;return!!e.match(t)}import{getChainConfig as R}from"@swapkit/types";function rt(){return typeof window.ethereum<"u"}function nt(e){return ie().includes(e)}function ie(){let e=window?.ethereum&&!window.ethereum?.isBraveWallet,t=window?.vultisig,r=window?.ethereum?.isBraveWallet,n=window?.ethereum?.isTrust||window?.trustwallet,o=window?.ethereum?.overrideIsMetaMask&&window?.ethereum?.selectedProvider?.isCoinbaseWallet||window?.coinbaseWalletExtension,i=window?.bitkeep?.ethereum,s=window?.$onekey?.ethereum,a=[];if(e)a.push(c.METAMASK);if(t)a.push(c.VULTISIG);if(r)a.push(c.BRAVE);if(n)a.push(c.TRUSTWALLET_WEB);if(o)a.push(c.COINBASE_WEB);if(de())a.push(c.OKX_MOBILE);if(i)a.push(c.BITGET);if(s)a.push(c.ONEKEY);return a}var C=new Set([4001,5000,"ACTION_REJECTED"]);function ot(e){return(e?.signing?.direct??e?.supportsDirectSigning)===!0}function M(e){if(!e||typeof e!=="object")return!1;let{code:t,error:r,info:n,data:o}=e;if(C.has(t))return!0;return[r,n?.error,o?.originalError].some((i)=>!!i&&typeof i==="object"&&C.has(i.code))}async function ae(e,t){if(!t)return!1;try{let{chainId:r}=await e.getNetwork();return BigInt(r)===BigInt(t)}catch{return!1}}async function se(e,t,r){let n=R(t);try{await D({method:"wallet_switchEthereumChain",params:[{chainId:n.chainIdHex}],provider:e})}catch(o){if(M(o))throw new m("helpers_failed_to_switch_network",{chain:t,error:o,reason:"user rejected request"});if(!r)throw new m("helpers_failed_to_switch_network",{chain:t,error:o,reason:"networkParams not provided"});try{await pe(e,r)}catch(i){throw new m("helpers_failed_to_switch_network",{chain:t,error:i,reason:M(i)?"user rejected adding the network":"failed to add the network"})}}}function it({chains:e,supportedChains:t,walletType:r}){let n=e.filter((i)=>!i||t.includes(i));if(n.length===0)throw new m("wallet_chain_not_supported",{chain:e.join(", "),wallet:r});let o=e.filter((i)=>!t.includes(i));return W({condition:o.length>0,id:`wallet_chain_not_supported_${r}`,warning:`${r} wallet does not support the following chains: ${o.join(", ")}. These chains will be ignored.`}),n}function ue(e,t,r,n){return async(...o)=>{let{chainIdHex:i}=R(r);if(await ae(t,i))return e(...o);try{await se(t,r,n)}catch(s){if(s instanceof m)throw s;throw new m({errorKey:"helpers_failed_to_switch_network",info:{chain:r,error:s}})}return e(...o)}}function at({toolbox:e,chain:t,provider:r,methodNames:n=[],networkParams:o=ce(e)}){let s=[...n,"approve","approvedAmount","call","sendTransaction","transfer","isApproved","approvedAmount","EIP1193SendTransaction","getFeeData","broadcastTransaction","estimateCall","estimateGasLimit","estimateGasPrices","createContractTxObject","signTypedData"].reduce((a,u)=>{if(!e[u])return a;let d=e[u];if(typeof d!=="function")return a;let l=ue(d,r,t,o);return{...a,[u]:l}},{});return{...e,...s}}function ce(e){let t=e.getNetworkParams;if(typeof t!=="function")return;try{let r=t();return r&&typeof r==="object"&&"chainId"in r?r:void 0}catch{return}}function pe(e,t){return D({method:"wallet_addEthereumChain",params:[t],provider:e})}function st(e){window.ethereum?.on("accountsChanged",()=>e())}function ut(){let{isTrust:e,isBraveWallet:t,overrideIsMetaMask:r,selectedProvider:n}=window?.ethereum||{};if(e)return c.TRUSTWALLET_WEB;if(t)return c.BRAVE;if(r&&n?.isCoinbaseWallet)return c.COINBASE_WEB;if(window?.$onekey?.ethereum)return c.ONEKEY;return c.METAMASK}function ct(){let e=[];function t(n){if(e.map((o)=>o.info.uuid).includes(n.detail.info.uuid))return;e.push(n.detail)}window.addEventListener("eip6963:announceProvider",t),window.dispatchEvent(new Event("eip6963:requestProvider"));function r(){window.removeEventListener("eip6963:announceProvider",t)}return{providers:e,removeEIP6963EventListener:r}}function de(){let e=navigator.userAgent,t=/iphone|ipad|ipod|ios/i.test(e),r=/android|XiaoMi|MiuiBrowser/i.test(e),n=t||r,o=/OKApp/i.test(e);return n&&o}function D({provider:e,params:t,method:r}){if(!e?.send)throw new m("helpers_not_found_provider");let n=t?Array.isArray(t)?t:[t]:[];return e.send(r,n)}export{q as ACCOUNT_INDEXED_CHAINS,Er as ApiV2ErrorSchema,fn as ApprovalTransactionSchema,Ot as ApproveMode,ln as ApproveRequestParams,hn as ApproveResponseSchema,pr as AssetValue,br as AssetValueSchema,ur as BigIntArithmetics,Mr as BrokerDepositChannelParamsSchema,on as ChainflipMetadataSchema,Tr as CoinGeckoMetadataSchema,Yt as CommonAssetStrings,Vr as CosmosTransactionSchema,B as DEFAULT_FEE_MULTIPLIERS,Cr as DepositChannelParamsSchema,Wr as DepositChannelResponseSchema,Ae as DerivationPath,jr as EVMTransactionDetailsParamsSchema,zr as EVMTransactionDetailsSchema,Kr as EVMTransactionSchema,Wt as ErrorCode,Fr as EstimatedTimeSchema,L as FeeOption,Dt as FeeTypeEnum,Nr as FeesSchema,mn as GasResponseSchema,dn as GasSchema,Yr as HYPERCORE_USDC_TOKEN_ID,Jr as HyperCoreEip712TypedDataSchema,Qr as HyperCoreSendAssetActionSchema,en as HyperCoreSendAssetTransactionSchema,Zr as HyperCoreTypedDataTransactionSchema,Ft as LedgerErrorCode,In as LimitOrderApprovalTxSchema,Rn as LimitOrderBuildRequestSchema,Nn as LimitOrderBuildResponseSchema,jn as LimitOrderCancelBuildResponseSchema,zn as LimitOrderCancelSubmitResponseSchema,Hn as LimitOrderCancelTxSchema,Kn as LimitOrderCancelTypedDataSchema,On as LimitOrderEVMTransactionSchema,Un as LimitOrderListResponseSchema,Mn as LimitOrderQuoteRequestSchema,$n as LimitOrderQuoteResponseSchema,Wn as LimitOrderQuoteRouteSchema,Bn as LimitOrderSchema,Sn as LimitOrderStatus,Fn as LimitOrderSubmitResponseSchema,Cn as LimitOrderTokensResponseSchema,Ln as LimitOrderTxHashSchema,kn as LimitOrderTxMetaSchema,_n as LimitOrderTxType,Dn as LimitOrderTypedDataSchema,re as MemoType,$r as NearDepositChannelParamsSchema,Rr as NearDepositChannelResultSchema,Dr as NearSwapResponseSchema,v as NetworkDerivationPath,_r as PriceRequestSchema,xr as PriceResponseSchema,mr as PriorityLabel,fr as ProviderAction,Rt as ProviderName,Sr as QuoteRequestSchema,cn as QuoteResponseRouteItem,pn as QuoteResponseSchema,bn as QuoteRouteV2Response,An as QuoteV2ResponseSchema,Pn as QuoteV3ResponseSchema,Ut as RequestClient,tn as RouteLegSchema,rn as RouteLegWithoutAddressesSchema,nn as RouteQuoteMetadataAssetSchema,an as RouteQuoteMetadataSchema,sn as RouteQuoteMetadataV2Schema,Tn as RouteQuoteProviderErrorSchema,lr as RouteQuoteTxType,un as RouteQuoteWarningSchema,Ee as SINGLE_WALLET_CHAINS,x as SKConfig,Lt as SigningCapability,Xr as StarknetTransactionSchema,gn as StellarApprovalTransactionSchema,wn as SwapApprovalTransactionSchema,Vn as SwapKitApi,m as SwapKitError,f as SwapKitNumber,xn as SwapRouteV2ResponseSchema,yn as SwapToAssetSchema,vn as SwapToRequestSchema,En as SwapToResponseSchema,qr as TONTransactionMessageSchema,Gr as TONTransactionSchema,Ar as TokenDetailsMetadataSchema,Pr as TokenSchema,Or as TrackerResponseSchema,yr as TrackingRequestQuerySchema,vr as TrackingRequestSchema,wr as TrackingStatus,Ir as TransactionDTOSchema,kr as TransactionSchema,Hr as TronTransactionSchema,gr as TxnStatus,hr as TxnType,h as UTXOPurpose,_ as UTXOScriptType,j as UTXO_SCRIPT_TYPES,z as UTXO_SCRIPT_TYPE_LIST,c as WalletOption,$t as WarningCodeEnum,jt as _rpcCache,st as addAccountsChangedCallback,pe as addEVMWalletNetwork,fe as applyFeeMultiplier,he as applyFeeMultiplierToBigInt,nr as assetFromString,Qt as decodeABIDynamicString,Jt as decodeABIString,Y as derivationPathToString,Zt as fetchTokenInfo,it as filterSupportedChains,ar as findAssetBy,sr as formatBigIntToSafeValue,rr as getAssetType,ee as getAsymmetricAssetShare,Me as getAsymmetricAssetWithdrawAmount,Z as getAsymmetricRuneShare,Ce as getAsymmetricRuneWithdrawAmount,Gt as getChainIdentifier,tr as getCommonAssetInfo,be as getDerivationPathFor,ct as getEIP6963Wallets,ut as getETHDefaultWallet,$e as getEstimatedPoolShare,qt as getExplorerAddressUrl,Xt as getExplorerTxUrl,S as getFeeMultiplier,U as getFeeMultiplierAsBigInt,Re as getLiquiditySlippage,Ge as getMAYANameCost,Ue as getMemoForDeposit,Fe as getMemoForLeaveAndBond,ze as getMemoForNamePreferredAssetRegister,je as getMemoForNameRegister,Be as getMemoForRunePoolDeposit,He as getMemoForRunePoolWithdraw,Ve as getMemoForTcyClaim,Xe as getMemoForTcyStake,Le as getMemoForUnbond,Ke as getMemoForWithdraw,dr as getMinAmountByChain,X as getPurposeFromPath,Vt as getRPCUrl,zt as getRPCUrlSync,te as getSymmetricPoolShare,We as getSymmetricWithdraw,qe as getTHORNameCost,ir as getTokenLogoURI,ye as getUTXOScriptTypeForPath,V as getUTXOScriptTypeForPurpose,Te as getWalletFormatFor,nt as isDetected,er as isGasAsset,Lr as isTransactionValue,M as isUserRejectedRequest,rt as isWeb3Detected,ie as listWeb3EVMWallets,de as okxMobileEnabled,or as parseSymbolForAddress,Br as parseTransactionValue,at as prepareNetworkSwitch,D as providerRequest,kt as registerErrorCodes,Nt as registerWalletOption,G as resolveDerivationPath,Kt as signWidgetRequest,It as subscribeWalletOptionRegistration,Bt as swapKitConfigStore,se as switchEVMWalletNetwork,Ur as toHexTransactionValue,g as updateDerivationPath,cr as validateIdentifier,Ye as validateTNS,ot as walletSupportsDirectSigning,W as warnOnce,ue as wrapMethodWithNetworkSwitch,Ht as wrapWithThrow};