@swapkit/helpers 6.1.2 → 6.3.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,21 @@
1
1
  # @swapkit/helpers
2
2
 
3
+ ## 6.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#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.
8
+ - [#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.
9
+ - [#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.
10
+ - [#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)
11
+
12
+ ## 6.2.0
13
+
14
+ ### Minor Changes
15
+
16
+ - [#373](https://github.com/swapkit/sdk/pull/373) [`218e46d`](https://github.com/swapkit/sdk/commit/218e46d12d423e0420143ec410f0a4c8d102ab8d) Thanks [@ice-chillios](https://github.com/ice-chillios)! - Add the `toolbox_lightspark_*` block (91301 to 91313) to `SwapKitError.ErrorCode` for the new Lightning toolbox: `toolbox_lightspark_missing_credentials`, `toolbox_lightspark_invalid_invoice`, `toolbox_lightspark_invoice_amount_mismatch`, `toolbox_lightspark_invoice_destination_mismatch`, `toolbox_lightspark_invoice_expired`, `toolbox_lightspark_invoice_already_settled`, `toolbox_lightspark_fee_limit_exceeded`, `toolbox_lightspark_invalid_params`, `toolbox_lightspark_api_error`, `toolbox_lightspark_invalid_amount`, `toolbox_lightspark_invalid_destination`, `toolbox_lightspark_network_mismatch` and `toolbox_lightspark_signing_key_unavailable`. An unloadable node signing key is reported as `toolbox_lightspark_signing_key_unavailable`, distinct from `toolbox_lightspark_missing_credentials`, so an integrator branching on the code can tell an unloaded key from an absent credential.
17
+ - [#447](https://github.com/swapkit/sdk/pull/447) [`b827853`](https://github.com/swapkit/sdk/commit/b827853cd1bfa68a9bd733843b3740f10ecab359) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/tokens@5.0.15)
18
+
3
19
  ## 6.1.2
4
20
 
5
21
  ### Patch 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-8nb97rpv.js";export{j as ApiV2ErrorSchema,da as ApprovalTransactionSchema,ba as ApproveRequestParams,ca as ApproveResponseSchema,k as AssetValueSchema,r as BrokerDepositChannelParamsSchema,U as ChainflipMetadataSchema,l as CoinGeckoMetadataSchema,I as CosmosTransactionSchema,q as DepositChannelParamsSchema,s as DepositChannelResponseSchema,G as EVMTransactionDetailsParamsSchema,H as EVMTransactionDetailsSchema,E as EVMTransactionSchema,A as EstimatedTimeSchema,z as FeesSchema,aa as GasResponseSchema,_ as GasSchema,M as HYPERCORE_USDC_TOKEN_ID,N as HyperCoreEip712TypedDataSchema,O as HyperCoreSendAssetActionSchema,Q as HyperCoreSendAssetTransactionSchema,P as HyperCoreTypedDataTransactionSchema,t as NearDepositChannelParamsSchema,u as NearDepositChannelResultSchema,v as NearSwapResponseSchema,p as PriceRequestSchema,n as PriceResponseSchema,a as PriorityLabel,d as ProviderAction,o as QuoteRequestSchema,Y as QuoteResponseRouteItem,Z as QuoteResponseSchema,ka as QuoteRouteV2Response,ma as QuoteV2ResponseSchema,ga as QuoteV3ResponseSchema,R as RouteLegSchema,S as RouteLegWithoutAddressesSchema,T as RouteQuoteMetadataAssetSchema,V as RouteQuoteMetadataSchema,W as RouteQuoteMetadataV2Schema,la as RouteQuoteProviderErrorSchema,b as RouteQuoteTxType,X as RouteQuoteWarningSchema,J as StarknetTransactionSchema,ea as StellarApprovalTransactionSchema,fa as SwapApprovalTransactionSchema,oa as SwapKitApi,na as SwapRouteV2ResponseSchema,ia as SwapToAssetSchema,ha as SwapToRequestSchema,ja as SwapToResponseSchema,K as TONTransactionMessageSchema,L as TONTransactionSchema,m as TokenDetailsMetadataSchema,g as TokenSchema,w as TrackerResponseSchema,i as TrackingRequestQuerySchema,h as TrackingRequestSchema,f as TrackingStatus,y as TransactionDTOSchema,x as TransactionSchema,F as TronTransactionSchema,e as TxnStatus,c as TxnType,B as isTransactionValue,C as parseTransactionValue,D as toHexTransactionValue};
1
+ import{$ as j,$a as ka,Aa as K,Ba as L,Ca as M,Da as N,Ea as O,Fa as P,Ga as Q,Ha as R,Ia as S,Ja as T,Ka as U,La as V,Ma as W,Na as X,Oa as Y,Pa as Z,Qa as _,Ra as aa,S as a,Sa as ba,T as b,Ta as ca,U as c,Ua as da,V as d,Va as ea,W as e,Wa as fa,X as f,Xa as ga,Y as g,Ya as ha,Z as h,Za as ia,_ as i,_a as ja,aa as k,ab as la,ba as l,bb as ma,ca as m,cb as na,da as n,db as oa,ea as o,fa as p,ga as q,ha as r,ia as s,ja as t,ka as u,la as v,ma as w,na as x,oa as y,pa as z,qa as A,ra as B,sa as C,ta as D,ua as E,va as F,wa as G,xa as H,ya as I,za as J}from"../chunk-yft3rsg6.js";export{j as ApiV2ErrorSchema,da as ApprovalTransactionSchema,ba as ApproveRequestParams,ca as ApproveResponseSchema,k as AssetValueSchema,r as BrokerDepositChannelParamsSchema,U as ChainflipMetadataSchema,l as CoinGeckoMetadataSchema,I as CosmosTransactionSchema,q as DepositChannelParamsSchema,s as DepositChannelResponseSchema,G as EVMTransactionDetailsParamsSchema,H as EVMTransactionDetailsSchema,E as EVMTransactionSchema,A as EstimatedTimeSchema,z as FeesSchema,aa as GasResponseSchema,_ as GasSchema,M as HYPERCORE_USDC_TOKEN_ID,N as HyperCoreEip712TypedDataSchema,O as HyperCoreSendAssetActionSchema,Q as HyperCoreSendAssetTransactionSchema,P as HyperCoreTypedDataTransactionSchema,t as NearDepositChannelParamsSchema,u as NearDepositChannelResultSchema,v as NearSwapResponseSchema,p as PriceRequestSchema,n as PriceResponseSchema,a as PriorityLabel,d as ProviderAction,o as QuoteRequestSchema,Y as QuoteResponseRouteItem,Z as QuoteResponseSchema,ka as QuoteRouteV2Response,ma as QuoteV2ResponseSchema,ga as QuoteV3ResponseSchema,R as RouteLegSchema,S as RouteLegWithoutAddressesSchema,T as RouteQuoteMetadataAssetSchema,V as RouteQuoteMetadataSchema,W as RouteQuoteMetadataV2Schema,la as RouteQuoteProviderErrorSchema,b as RouteQuoteTxType,X as RouteQuoteWarningSchema,J as StarknetTransactionSchema,ea as StellarApprovalTransactionSchema,fa as SwapApprovalTransactionSchema,oa as SwapKitApi,na as SwapRouteV2ResponseSchema,ia as SwapToAssetSchema,ha as SwapToRequestSchema,ja as SwapToResponseSchema,K as TONTransactionMessageSchema,L as TONTransactionSchema,m as TokenDetailsMetadataSchema,g as TokenSchema,w as TrackerResponseSchema,i as TrackingRequestQuerySchema,h as TrackingRequestSchema,f as TrackingStatus,y as TransactionDTOSchema,x as TransactionSchema,F as TronTransactionSchema,e as TxnStatus,c as TxnType,B as isTransactionValue,C as parseTransactionValue,D as toHexTransactionValue};
@@ -0,0 +1,5 @@
1
+ var nn=Object.defineProperty;var rn=(e)=>e;function sn(e,t){this[e]=rn.bind(null,t)}var Xe=(e,t)=>{for(var n in t)nn(e,n,{get:t[n],enumerable:!0,configurable:!0,set:sn.bind(t,n)})};var ze=((e)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{Chain as Re,getChainConfig as ti}from"@swapkit/types";import{AllChains as Kn,Chain as R,EVMChains as Wn,getChainConfig as oe}from"@swapkit/types";import{match as Ve}from"ts-pattern";import{Chain as d,EVMChains as Pn,getChainConfig as K,UTXOChains as En}from"@swapkit/types";import{match as re}from"ts-pattern";import{AllChains as et,Chain as Ze,getChainConfig as un,MAYAConfig as gn,THORConfig as mn}from"@swapkit/types";import{createStore as _n}from"zustand/vanilla";import{AllChains as on,getChainConfig as an}from"@swapkit/types";var Gr=Object.freeze(Object.fromEntries(on.map((e)=>[e,Object.freeze(an(e).networkDerivationPath)])));var ne;((l)=>{l.unknownError="unknownError";l.test_error="test_error";l.providerDetailsError="providerDetailsError";l.blockHeaderNotFound="blockHeaderNotFound";l.blockHashNotFoundAtHeight="blockHashNotFoundAtHeight";l.blockHashNotFoundAtHash="blockHashNotFoundAtHash";l.txHashMissing="txHashMissing";l.assetValueMissingInfo="assetValueMissingInfo";l.invalidAsset="invalidAsset";l.blockIsRequired="blockIsRequired";l.currentBlockHeaderNotFound="currentBlockHeaderNotFound";l.failedToRetrieveBalance="failedToRetrieveBalance";l.failedToRetrieveBlock="failedToRetrieveBlock";l.failedToRetrieveFees="failedToRetrieveFees";l.notImplementedBCH="notImplementedBCH";l.notImplementedDoge="notImplementedDoge";l.noPoolsFound="noPoolsFound";l.noVaultsFound="noVaultsFound";l.noTxFound="noTxFound";l.noInputCoinFound="noInputCoinFound";l.noBlockDataFound="noBlockDataFound";l.multipleCosmosMessages="multipleCosmosMessages";l.heightOrHashNotProvided="heightOrHashNotProvided";l.unknownDenom="unknownDenom";l.invalidBlockHeight="invalidBlockHeight";l.timestampExtrinsicNoArgumentsForBlock="timestampExtrinsicNoArgumentsForBlock";l.timestampExtrinsicNoTimestampForBlock="timestampExtrinsicNoTimestampForBlock";l.noTimestampExtrinsicForHash="noTimestampExtrinsicForHash";l.timestampExtrinsicNoArgumentsForHash="timestampExtrinsicNoArgumentsForHash";l.txMemoUndefined="txMemoUndefined";l.txMemoIncorrect="txMemoIncorrect";l.txTypeNotFound="txTypeNotFound";l.txNoMessage="txNoMessage";l.txNotFound="txNotFound";l.txReceiptNotFound="txReceiptNotFound";l.txParsingError="txParsingError";l.txLogsParsingError="txLogsParsingError";l.blockNotFound="blockNotFound";l.balanceNotFound="balanceNotFound";l.configError="configError";l.synthSwapDisallowed="synthSwapDisallowed";l.providerQuoteTimeout="providerQuoteTimeout";l.noQuoteResponse="noQuoteResponse";l.noPoolAssetsFound="noPoolAssetsFound";l.noThorchainPools="noThorchainPools";l.noMayachainPools="noMayachainPools";l.noThorchainNetworkInfo="noThorchainNetworkInfo";l.invalidAffiliateFee="invalidAffiliateFee";l.invalidBuyAssetAddress="invalidBuyAssetAddress";l.invalidSellAssetAddress="invalidSellAssetAddress";l.invalidSourceAddress="invalidSourceAddress";l.invalidDestinationAddress="invalidDestinationAddress";l.sourceAddressIsSmartContract="sourceAddressIsSmartContract";l.destinationAddressIsSmartContract="destinationAddressIsSmartContract";l.invalidChainId="invalidChainId";l.unsupportedChainId="unsupportedChainId";l.unsupportedEVMChainId="unsupportedEVMChainId";l.unsupportedMethod="unsupportedMethod";l.unsupportedProvider="unsupportedProvider";l.invalidParamsForMethod="invalidParamsForMethod";l.unsupportedAdapter="unsupportedAdapter";l.noWhitelistTokens="noWhitelistTokens";l.failedFetchGasPrice="failedFetchGasPrice";l.failedToCreateDepositChannel="failedToCreateDepositChannel";l.noProviderDetailsFound="noProviderDetailsFound";l.noTokenListsFound="noTokenListsFound";l.tokenNotFound="tokenNotFound";l.tokenPriceNotFound="tokenPriceNotFound";l.tokenPriceFailedToUpdate="tokenPriceFailedToUpdate";l.swapAmountTooSmall="swapAmountTooSmall";l.legsArrayIsEmpty="legsArrayIsEmpty";l.failedToFetchQuoteForLeg="failedToFetchQuoteForLeg";l.noBlockHeaderFound="noBlockHeaderFound";l.failedToSimulateSwap="failedToSimulateSwap";l.addressScreeningFailed="addressScreeningFailed";l.noLiquidtyProvidersFound="noLiquidtyProvidersFound";l.insufficientLiquidity="insufficientLiquidity";l.noInboundDataFound="noInbounDataFound";l.noInboundAddressesFound="noInboundAddressesFound";l.noInboundAddressFoundForChain="noInboundAddressFoundForChain";l.noLastBlocksFound="noLastBlocksFound";l.noVersionFound="noVersionFound";l.noConstantsFound="noConstantsFound";l.noMimirsFound="noMimirsFound";l.noRoutesFound="noRoutesFound";l.quoteNotFound="quoteNotFound";l.ledgerSignFailed="ledgerSignFailed";l.ledgerWrongPayload="ledgerWrongPayload";l.ledgerFetchSwapFailed="ledgerFetchSwapFailed";l.failedToFetchTx="failedToFetchTx";l.failedBuildTransactionDetails="failedBuildTransactionDetails";l.noLegsForRoute="noLegsForRoute";l.noRouterAddressFound="noRouterAddressFound";l.noAggregatorAddressFound="noAggregatorAddressFound";l.noContractInstanceFound="noContractInstanceFound";l.noContractAddressFound="noContractAddressFound";l.invalidAffiliate="invalidAffiliate";l.thornameAffiliate="thornameAffiliate";l.providerNotfound="No provider found";l.noRecordFound="No Record found";l.slippageTooLow="Slippage too low";l.tradingHalted="tradingHalted";l.noWrappedGasAsset="noWrappedGasAsset";l.aggregatorAddressNotFound="aggregatorAddressNotFound";l.routerAddressNotFound="routerAddressNotFound";l.dummyAddressNotFound="dummyAddressNotFound";l.trackerError="trackerError";l.thorchainPoolUnavailable="thorchainPoolUnavailable";l.noOhlcvDataFound="noOhlcvDataFound";l.noTradingPairs="noTradingPairs";l.noLendingAvailability="noLendingAvailability";l.lendingRepayTooSmall="lendingRepayTooSmall";l.missingState="missingState";l.ledgerSwapNotFound="ledgerSwapNotFound";l.ledgerSwapNotReadyForTracking="ledgerSwapNotReadyForTracking";l.errorEstimatingGas="errorEstimatingGas";l.apiKeyInvalid="apiKeyInvalid";l.apiKeyFailedToUpdate="apiKeyFailedToUpdate";l.apiKeyExpired="apiKeyExpired";l.unauthorized="unauthorized";l.failedToCreateMemo="failedToCreateMemo";l.radixIncorrectInstructions="radixIncorrectInstructions";l.radixTxMissedParam="radixTxMissedParam";l.radixTxMissedAccount="radixTxMissedAccount";l.radixManifestParseError="radixManifestParseError";l.radixManifestBuildError="radixManifestBuildError";l.invalidAddressForChain="invalidAddressForChain";l.riskyAddress="riskyAddress";l.noRoutesToProcess="noRoutesToProcess";l.sellAssetAmountTooSmall="sellAssetAmountTooSmall";l.missingPrivateKey="missingPrivateKey";l.noMemoPriceProtection="noMemoPriceProtection"})(ne||={});var ke;((i)=>{i.highSlippage="highSlippage";i.highPriceImpact="highPriceImpact";i.insufficientBalance="insufficientBalance"})(ke||={});var k;((w)=>{w.CHAINFLIP="CHAINFLIP";w.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";w.JUPITER="JUPITER";w.MAYACHAIN="MAYACHAIN";w.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";w.ONEINCH="ONEINCH";w.PANCAKESWAP="PANCAKESWAP";w.SUSHISWAP_V2="SUSHISWAP_V2";w.THORCHAIN="THORCHAIN";w.THORCHAIN_STREAMING="THORCHAIN_STREAMING";w.TRADERJOE_V2="TRADERJOE_V2";w.UNISWAP_V2="UNISWAP_V2";w.UNISWAP_V3="UNISWAP_V3";w.NEAR="NEAR";w.GARDEN="GARDEN";w.OKX="OKX";w.HARBOR="HARBOR";w.FLASHNET="FLASHNET";w.MAYAN="MAYAN";w.PACTSWAP="PACTSWAP";w.RELAY="RELAY"})(k||={});var Pe;((_)=>{_.LIQUIDITY="liquidity";_.NETWORK="network";_.INBOUND="inbound";_.OUTBOUND="outbound";_.AFFILIATE="affiliate";_.TAX="tax";_.PRIORITY="priority";_.SERVICE="service"})(Pe||={});var ln;((i)=>{i.Average="average";i.Fast="fast";i.Fastest="fastest"})(ln||={});var cn;((n)=>{n.Approve="approve";n.CheckOnly="checkOnly"})(cn||={});var dn;((T)=>{T.NAME_REGISTER="~";T.BOND="BOND";T.DEPOSIT="+";T.LEAVE="LEAVE";T.UNBOND="UNBOND";T.WITHDRAW="-";T.RUNEPOOL_DEPOSIT="POOL+";T.RUNEPOOL_WITHDRAW="POOL-";T.CLAIM_TCY="tcy";T.STAKE_TCY="tcy+";T.UNSTAKE_TCY="tcy-"})(dn||={});var Qe={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,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,n)=>typeof n==="bigint"?n.toString():n)}class b extends Error{static ErrorCode=Qe;errorKey;info;constructor(e,t){let n=typeof e==="string",i=n?e:e.errorKey,s=n?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 c=t instanceof Error?`${t.message}${t.cause?` (${t.cause})`:""}`:Ee(t);console.error(`SwapKitError [${i}]: ${c}`)}else if(s)console.error(`SwapKitError [${i}]: ${Ee(s)}`)}}function Xr(e){let t=Qe;for(let[n,i]of Object.entries(e)){if(Object.hasOwn(t,n)){if(t[n]===i)continue;throw new b({errorKey:"helpers_invalid_params",info:{code:i,existingCode:t[n],key:n}})}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:n}});t[n]=i}}var ge={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 Je(e){return Ne.add(e),()=>Ne.delete(e)}function Jr(e,t){let n=ge;if(Object.hasOwn(n,e)){if(n[e]===t)return;throw new b({errorKey:"helpers_invalid_params",info:{existingValue:n[e],key:e,value:t}})}n[e]=t;for(let i of Ne)i(t)}var pn;((i)=>{i[i.NoError=36864]="NoError";i[i.LockedDevice=21781]="LockedDevice";i[i.TC_NotFound=65535]="TC_NotFound"})(pn||={});var Zr={BtcMessage:"btcMessage",Direct:"direct",TypedData:"typedData"};var hn=et.reduce((e,t)=>(e[t]=un(t).rpcUrls,e),{}),fn={[Ze.THORChain]:mn.nodeUrl,[Ze.Maya]:gn.nodeUrl},tt={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:et,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:hn,thornodeUrls:fn,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(ge),widgetId:"",widgetKey:""},P=_n((e)=>({...tt,setApiKey:(t,n)=>e((i)=>({apiKeys:{...i.apiKeys,[t]:n}})),setConfig:(t)=>e((n)=>({apiKeys:{...n.apiKeys,...t?.apiKeys},chains:n.chains.concat(t?.chains||[]),endpoints:{...n.endpoints,...t?.endpoints},envs:{...n.envs,...t?.envs},feeMultipliers:t?.feeMultipliers||n.feeMultipliers,integrations:{...n.integrations,...t?.integrations},localMode:{...n.localMode,...t?.localMode},rpcUrls:{...n.rpcUrls,...t?.rpcUrls},thornodeUrls:{...n.thornodeUrls,...t?.thornodeUrls},v3SwapFlow:{...n.v3SwapFlow,...t?.v3SwapFlow},wallets:n.wallets.concat(t?.wallets||[]),widgetId:t?.widgetId||n.widgetId,widgetKey:t?.widgetKey||n.widgetKey})),setEndpoint:(t,n)=>e((i)=>({endpoints:{...i.endpoints,[t]:n}})),setEnv:(t,n)=>e((i)=>({envs:{...i.envs,[t]:n}})),setFeeMultipliers:(t)=>e(()=>({feeMultipliers:t})),setIntegrationConfig:(t,n)=>e((i)=>({integrations:{...i.integrations,[t]:n}})),setRequestOptions:(t)=>e((n)=>({requestOptions:{retry:{...n.requestOptions.retry,...t.retry},timeoutMs:t.timeoutMs||n.requestOptions.timeoutMs}})),setRpcUrl:(t,n)=>e((i)=>({rpcUrls:{...i.rpcUrls,[t]:n}})),setThornodeUrl:(t,n)=>e((i)=>({thornodeUrls:{...i.thornodeUrls,[t]:n}})),setWidgetId:(t)=>e({widgetId:t}),setWidgetKey:(t)=>e({widgetKey:t})}));Je((e)=>{P.setState((t)=>t.wallets.includes(e)?t:{wallets:[...t.wallets,e]})});var x={get:(e)=>P.getState()[e],getState:P.getState,reinitialize:()=>P.setState({...tt,wallets:Object.values(ge)}),set:(e)=>P.getState().setConfig(e),setApiKey:(e,t)=>P.getState().setApiKey(e,t),setEndpoint:(e,t)=>P.getState().setEndpoint(e,t),setEnv:(e,t)=>P.getState().setEnv(e,t),setFeeMultipliers:(e)=>P.getState().setFeeMultipliers(e),setIntegrationConfig:(e,t)=>P.getState().setIntegrationConfig(e,t),setRequestOptions:(e)=>P.getState().setRequestOptions(e),setRpcUrl:(e,t)=>P.getState().setRpcUrl(e,t),setThornodeUrl:(e,t)=>P.getState().setThornodeUrl(e,t),setWidgetId:(e)=>P.getState().setWidgetId(e),setWidgetKey:(e)=>P.getState().setWidgetKey(e)};var yn=(e)=>new Promise((t)=>setTimeout(t,e)),bn=(e,{baseDelay:t,backoffMultiplier:n,maxDelay:i})=>Math.min(t*n**e,i);function An(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 Sn=async(e,t)=>{let n=await fetch(e,t),i;try{i=await n.json()}catch{if(!n.ok)throw new b({errorKey:"helpers_invalid_response",info:{status:n.status,statusText:n.statusText}},{status:n.status,statusText:n.statusText});return{}}if(!n.ok){let a={data:i?.data,error:i?.error,message:i?.message,status:n.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:n.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 me(e,t={}){return async function(i,s={}){let{searchParams:a,json:c,body:u,headers:_,dynamicHeader:A,retry:y,timeoutMs:T,abortController:O,onError:S,onSuccess:M,...C}={...t,...s},I=x.get("requestOptions"),q={...I.retry,...y},de=!!c||i.endsWith(".json"),pe=wn(i,a),qe=A?await A():{},w=Tn(de,{..._,...qe}),Y=de?JSON.stringify(c):u,Ce;for(let ue=0;ue<=q.maxRetries;ue++){let Ye=O||new AbortController,je=setTimeout(()=>Ye.abort(),T||I.timeoutMs);try{let F=await Sn(pe,{...C,body:Y,headers:w,method:e,signal:Ye.signal});return clearTimeout(je),M?.(F)||F}catch(F){clearTimeout(je),Ce=F;let tn=F?.cause?.status;if(ue>=q.maxRetries||!An(F,tn))return S?S(F):Promise.reject(F);await yn(bn(ue,q))}}return S?S(Ce):Promise.reject(Ce)}}function Tn(e,t){return{...t,...e&&{"Content-Type":"application/json"}}}function wn(e,t){let n=new URL(e);if(t)n.search=new URLSearchParams(t).toString();return n.toString()}var m={extend:(e)=>({extend:(t)=>m.extend({...e,...t}),get:me("GET",e),post:me("POST",e)}),get:me("GET"),post:me("POST")};async function nt(e,t,n,i){let s=`${t}:${n}:${i}`,a=new TextEncoder,c=await crypto.subtle.importKey("raw",a.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),u=await crypto.subtle.sign("HMAC",c,a.encode(s));return Array.from(new Uint8Array(u)).map((_)=>_.toString(16).padStart(2,"0")).join("")}import{Chain as f,CosmosChains as ot,EVMChains as at,getChainConfig as lt,SubstrateChains as xn,UTXOChains as ct}from"@swapkit/types";import{match as _e}from"ts-pattern";function _s(e,t){try{return e()}catch(n){if(t)throw new b(t,n);return}}var it=new Set;function ie({condition:e,id:t,warning:n}){if(e){if(it.has(t))return;console.warn(n),it.add(t)}}function Rn(e){return _e(e).with(...at,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...ct,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...ot,()=>({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 rt(e){return _e(e).with(f.Aptos,()=>"/-/healthy").with(f.Aleo,()=>"/mainnet/block/height/latest").with(f.Hype,()=>"/info").with(f.Radix,()=>"/status/network-configuration").with(f.Stellar,()=>"").with(f.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function st(e,t){try{let n=t.startsWith("wss")?t.replace("wss","https"):t;if(e===f.Aleo||e===f.Stellar)return(await fetch(`${n}${rt(e)}`,{cache:"no-store",method:"GET",signal:AbortSignal.timeout(3000)})).ok;return(await fetch(`${n}${rt(e)}`,{body:JSON.stringify(Rn(e)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var Oe=new Map,vn=120000;function In(e){let[t=""]=x.get("rpcUrls")[e];if(!t)throw ie({condition:!0,id:"helpers_chain_no_public_or_set_rpc_url",warning:`No public or set RPC URL found for chain. Please ensure you configured rpcUrls for ${e}.`}),new b("helpers_chain_no_public_or_set_rpc_url",{chain:e});let n=Oe.get(e);if(n&&Date.now()-n.timestamp<vn)return n.url;return Oe.set(e,{timestamp:Date.now(),url:t}),t}async function j(e){let t=In(e),[,...n]=x.get("rpcUrls")[e];if(await st(e,t))return t;for(let s of n)if(await st(e,s))return Oe.set(e,{timestamp:Date.now(),url:s}),s;throw new b("helpers_chain_rpc_connection_failed",{chain:e,fallbackUrls:n,primaryRpcUrl:t})}function Ts({chain:e,txHash:t}){let{explorerUrl:n}=lt(e);return _e(e).with(...ot,f.Solana,()=>`${n}/tx/${t.startsWith("0x")?t.slice(2):t}`).with(...at,...xn,()=>`${n}/tx/${t.startsWith("0x")?t:`0x${t}`}`).with(...ct,f.Radix,f.Tron,()=>`${n}/transaction/${t.toLowerCase()}`).with(f.Near,()=>`${n}/txns/${t}`).with(f.Ripple,()=>`${n}/transactions/${t}`).with(f.Stellar,()=>`${n}/explorer/public/tx/${t}`).with(f.Sui,()=>`${n}/txblock/${t}`).with(f.Cardano,f.Hype,f.Spark,f.Ton,()=>`${n}/tx/${t}`).otherwise(()=>"")}function ws({chain:e,address:t}){let{explorerUrl:n}=lt(e);return _e(e).with(f.Solana,f.Sui,f.Radix,()=>`${n}/account/${t}`).with(f.Stellar,()=>`${n}/explorer/public/account/${t}`).otherwise(()=>`${n}/address/${t}`)}function xs(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 Cn}from"@noble/hashes/sha3.js";import{bytesToHex as kn}from"@noble/hashes/utils.js";var dt=/^(0x)?[0-9a-fA-F]{40}$/;function he(e){if(typeof e!=="string"||!dt.test(e))throw Error(`invalid address: ${e}`);let t=e.toLowerCase().replace(/^0x/,""),n=kn(Cn(new TextEncoder().encode(t))),i=[...t].map((a,c)=>Number.parseInt(n[c]??"0",16)>=8?a.toUpperCase():a).join(""),s=e.replace(/^0x/,"");if(/[A-F]/.test(s)&&/[a-f]/.test(s)&&s!==i)throw Error(`bad address checksum: ${e}`);return`0x${i}`}function pt(e){if(typeof e!=="string"||!dt.test(e))return!1;try{return he(e),!0}catch{return!1}}var Ms=[`${d.Maya}.MAYA`,`${d.Maya}.CACAO`,`${d.Ethereum}.THOR`,`${d.Ethereum}.vTHOR`,`${d.Kujira}.USK`,`${d.Ethereum}.FLIP`,`${d.Radix}.XRD`],mt=[d.Arbitrum,d.Aurora,d.Base,d.Ethereum,d.Optimism,d.Robinhood];async function Nn(e){let{baseDecimal:t}=K(d.Radix);try{let n=await j(d.Radix),{manager:i}=await m.post(`${n}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:e}),headers:{Accept:"*/*","Content-Type":"application/json"}});return i?.divisibility?.value?.divisibility}catch(n){let i=n instanceof Error?n.message:String(n);return console.warn(`Failed to fetch Radix asset decimals for ${e}: ${i}`),t}}async function On(e){try{let t=await j(d.Radix);return(await m.post(`${t}/state/entity/details`,{body:JSON.stringify({addresses:[e],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((s)=>s.key==="symbol")?.value.typed.value||void 0}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`Failed to fetch Radix asset symbol for ${e}: ${n}`),""}}async function _t({chain:e,address:t,methodHex:n,id:i}){let s=await j(e);return m.post(s,{body:JSON.stringify({id:i,jsonrpc:"2.0",method:"eth_call",params:[{data:n,to:t.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}function Dn(e){if(!e||e==="0x")return"UNKNOWN";try{return ht(e.replace(/^0x/,""))?.trim()||"UNKNOWN"}catch(t){return console.warn(`Failed to decode ABI string from ${e}: ${t}`),"UNKNOWN"}}function Mn(e,t){if(!e||e==="0x")return t;try{return Number(e)}catch(n){return console.warn(`Failed to decode ABI uint8 from ${e}: ${n}`),t}}async function Ln({chain:e,address:t}){let{baseDecimal:n}=K(e),i=t.toLowerCase();if(t===""||!i.startsWith("0x"))return n;let s=await _t({address:t,chain:e,id:2,methodHex:"0x313ce567"}).catch((c)=>(console.warn(`Could not fetch decimals for ${t} on ${e}: ${c.message}`),{result:""}));return Mn(s.result,n)}async function Vn({chain:e,address:t}){let n=t.toLowerCase();if(n===""||!n.startsWith("0x"))return;let i=await _t({address:t,chain:e,id:1,methodHex:"0x95d89b41"}).catch((a)=>(console.warn(`Could not fetch symbol for ${t} on ${e}: ${a.message}`),{result:""}));return Dn(i.result)}async function ut({rpcUrl:e,contractAddress:t,functionSelector:n}){return(await m.post(`${e}/wallet/triggerconstantcontract`,{body:JSON.stringify({contract_address:t,function_selector:n,owner_address:t,parameter:"",visible:!0}),headers:{accept:"application/json","content-type":"application/json"}}).catch(()=>{return}))?.constant_result?.[0]}function gt(e){let t=e.match(/.{2}/g)?.map((n)=>Number.parseInt(n,16))??[];return new TextDecoder().decode(new Uint8Array(t))}function ht(e){return re(e).with(void 0,()=>{return}).when((t)=>t.length>=128,(t)=>{let n=Number.parseInt(t.slice(64,128),16),i=t.slice(128,128+n*2).replace(/(00)+$/,"");return i?gt(i):void 0}).when((t)=>t.length===64,(t)=>{let n=t.replace(/(00)+$/,"");if(n.length>0&&n.length%2===0)return gt(n);return}).otherwise(()=>{return})}function ft({chain:e,address:t}){let{baseDecimal:n}=K(e),i={decimals:n,ticker:void 0};return re(e).with(...Pn,async()=>{try{if(!pt(t.replace(/^0X/,"0x")))return i;let[s,a]=await Promise.all([Vn({address:t,chain:e}),Ln({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(d.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(),c=Array.isArray(a)?a[0]:a;if(c)return{decimals:c.decimals??n,ticker:c.symbol||void 0}}}catch(s){console.warn(`Failed to fetch Solana token info for ${t}: ${s?.code} ${s?.message}`)}return i}).with(d.Tron,async()=>{if(!t)return i;try{let s=await j(d.Tron),[a,c]=await Promise.all([ut({contractAddress:t,functionSelector:"symbol()",rpcUrl:s}),ut({contractAddress:t,functionSelector:"decimals()",rpcUrl:s})]),u=ht(a);return{decimals:a!==void 0&&c?Number(BigInt(`0x${c}`)):n,ticker:u}}catch(s){let a=s instanceof Error?s.message:String(s);return console.warn(`Failed to fetch Tron token info for ${t}: ${a}`),i}}).with(d.Near,async()=>{if(!t)return i;try{let s=await j(d.Near),a=await m.post(s,{body:JSON.stringify({id:"dontcare",jsonrpc:"2.0",method:"query",params:{account_id:t,args_base64:"e30=",finality:"final",method_name:"ft_metadata",request_type:"call_function"}}),headers:{accept:"application/json","content-type":"application/json"}});if(!a.result?.result)throw Error("NEAR ft_metadata returned no result");let c=JSON.parse(new TextDecoder().decode(new Uint8Array(a.result.result)));return{decimals:c?.decimals||n,ticker:c?.symbol}}catch(s){let a=s instanceof Error?s.message:String(s);return console.warn(`Failed to fetch Near token info for ${t}: ${a}`),i}}).with(d.Radix,async()=>{if(!t)return i;try{let[s,a]=await Promise.all([On(t),Nn(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 yt({chain:e,symbol:t}){return re(e).with(...mt,()=>t==="ETH").with(d.Arc,()=>t==="USDC").with(d.Avalanche,()=>t==="AVAX").with(d.Berachain,()=>t==="BERA").with(d.Hyperevm,()=>t==="HYPE").with(d.Hype,()=>t==="HYPE").with(d.Spark,()=>t==="BTC").with(d.BinanceSmartChain,()=>t==="BNB").with(d.Gnosis,()=>t==="xDAI"||t==="XDAI").with(d.Monad,()=>t==="MON").with(d.XLayer,()=>t==="OKB").with(d.Maya,()=>t==="CACAO").with(d.Cosmos,()=>t==="ATOM").with(d.THORChain,()=>t==="RUNE").with(d.Tron,()=>t==="TRX").with(d.Ripple,()=>t==="XRP").with(d.Ton,()=>t==="GRAM"||t==="TON").with(d.Radix,()=>`${e}.${t}`===fe(e).identifier).otherwise(()=>t===e)}var fe=(e)=>{let{baseDecimal:t}=K(e);return re(e.toUpperCase()).with(...mt,(i)=>({decimal:t,identifier:`${i}.ETH`})).with(d.Arc,(i)=>({decimal:t,identifier:`${i}.USDC`})).with(d.THORChain,(i)=>({decimal:t,identifier:`${i}.RUNE`})).with(d.Cosmos,(i)=>({decimal:t,identifier:`${i}.ATOM`})).with(d.Maya,(i)=>({decimal:10,identifier:`${i}.CACAO`})).with(d.BinanceSmartChain,(i)=>({decimal:t,identifier:`${i}.BNB`})).with(d.Monad,(i)=>({decimal:t,identifier:`${i}.MON`})).with(d.Avalanche,(i)=>({decimal:t,identifier:`${i}.AVAX`})).with(d.Gnosis,(i)=>({decimal:t,identifier:`${i}.xDAI`})).with(d.XLayer,(i)=>({decimal:t,identifier:`${i}.OKB`})).with(d.Berachain,(i)=>({decimal:t,identifier:`${i}.BERA`})).with(d.Hyperevm,(i)=>({decimal:t,identifier:`${i}.HYPE`})).with(d.Hype,(i)=>({decimal:t,identifier:`${i}.HYPE`})).with(d.Spark,(i)=>({decimal:t,identifier:`${i}.BTC`})).with(d.Tron,(i)=>({decimal:t,identifier:`${i}.TRX`})).with(d.Ton,(i)=>({decimal:t,identifier:`${i}.GRAM`})).with(d.Solana,d.Chainflip,d.Kujira,d.Ripple,d.Polkadot,d.Near,...En,(i)=>({decimal:t,identifier:`${i}.${i}`})).with(d.Radix,"XRD.XRD",()=>({decimal:t,identifier:"XRD.XRD"})).with(d.Polygon,"POL.POL",()=>({decimal:t,identifier:"POL.POL"})).with("KUJI.USK",(i)=>({decimal:6,identifier:i})).with("ETH.FLIP",()=>({decimal:K(d.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:K(d.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:K(d.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(i)=>({decimal:10,identifier:i})).with("MAYA.MAYA",(i)=>({decimal:4,identifier:i})).otherwise(()=>({decimal:t,identifier:e}))};function De({chain:e,symbol:t}){if(t.includes("/"))return"Synth";if(t.includes("~"))return"Trade";return re(e).with(d.Radix,()=>t===d.Radix||`${e}.${t}`===fe(e).identifier).with(d.Arbitrum,d.Optimism,d.Base,d.Aurora,d.Robinhood,()=>t===d.Ethereum).with(d.Arc,()=>t==="USDC").with(d.Cosmos,()=>t==="ATOM").with(d.BinanceSmartChain,()=>t==="BNB").with(d.Maya,()=>t==="CACAO").with(d.Monad,()=>t==="MON").with(d.THORChain,()=>t==="RUNE").with(d.Tron,()=>t==="TRX").with(d.Hyperevm,()=>t==="HYPE").with(d.Hype,()=>t==="HYPE").with(d.Spark,()=>t==="BTC").with(d.XLayer,()=>t==="OKB").with(d.Ton,()=>t==="GRAM"||t==="TON").otherwise(()=>t===e)?"Native":e}var W=(e)=>{let[t,...n]=e.split("."),i=e.includes("/"),s=n.join("."),a=s?.split("-"),c=a?.length?a.length===1?a[0]:a.slice(0,-1).join("-"):void 0;return{chain:t,symbol:s,synth:i,ticker:c}};function se(e,t){let i=t===d.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 Ls(e){return`https://tokens.swapkit.dev/images/${e.toLowerCase()}.png`}async function Vs(e){let{loadTokenLists:t}=await import("./tokens.js"),n=await t(void 0,{source:x.get("envs").isDev?"dev":"prod"}),i=Object.values(n).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:c,symbol:u}=W(a.identifier);if(c!==e.chain)continue;let{address:_}=se(u,c);if(_?.toLowerCase()===s)return a.identifier}return}import{match as ye}from"ts-pattern";var G=8,Hn=10,Un=64;function X({value:e,bigIntDecimal:t=G,decimal:n=G}){if(n===0)return e.toString();let i=Math.min(t,n),s=i<n?bt(e,U(n-i)):e,a=s<0n,c=(a?-s:s).toString().padStart(i+1,"0"),u=c.length-i;return`${a?"-":""}${c.slice(0,u)}.${c.slice(u)}`.replace(/\.?0*$/,"")}class B{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(e,t){return new B({decimal:t,value:X({bigIntDecimal:t,decimal:t,value:e})})}static shiftDecimals({value:e,from:t,to:n}){return B.fromBigInt(e.getBaseValue("bigint")*U(n)/U(t),n)}constructor(e){this.decimal=typeof e==="object"?e.decimal:void 0;let t=be(typeof e==="object"&&"value"in e?e.value:e),n=typeof e==="object"&&"decimalMultiplier"in e?e.decimalMultiplier:U(this.decimal??0);this.decimalMultiplier=n!==void 0&&n>t.decimalMultiplier?n:t.decimalMultiplier,this.bigIntValue=t.bigIntValue*this.decimalMultiplier/t.decimalMultiplier}toString(e={}){return this.getValue("string")}set(e){return this.#n({decimal:this.decimal,value:new B(e)})}#n(e){return new this.constructor({...e,identifier:this.toString({includeSynthProtocol:!0})})}add(...e){return this.#t("add",...e)}sub(...e){return this.#t("sub",...e)}mul(...e){return this.#t("mul",...e)}div(...e){return this.#t("div",...e)}gt(e){return this.#e("gt",e)}gte(e){return this.#e("gte",e)}lt(e){return this.#e("lt",e)}lte(e){return this.#e("lte",e)}eqValue(e){return this.#e("eqValue",e)}getValue(e,t){let n=Ae(this.decimalMultiplier),i=t!==void 0?t:this.decimal,s=i!==void 0?i:n;if(i!==void 0&&i<n){if(this.formatBigIntToSafeValue(this.bigIntValue,i)==="0"&&this.bigIntValue!==0n)s=n}let a=this.formatBigIntToSafeValue(this.bigIntValue,s);return ye(e).with("number",()=>Number(a)).with("string",()=>a).with("bigint",()=>this.bigIntValue*U(this.decimal??G)/this.decimalMultiplier).otherwise(()=>a)}getBaseValue(e,t){let n=U(t??this.decimal??G),i=bt(this.bigIntValue*n,this.decimalMultiplier);return ye(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 n=be(e),i=t===void 0?this.decimalMultiplier:U(t);return n.bigIntValue*i/n.decimalMultiplier}toSignificant(e=6){let t=this.getValue("string"),n=t.startsWith("-"),i=n?t.slice(1):t,[s="",a=""]=i.split("."),c=Number.parseInt(s,10)>0;if((c?s.length+a.length:a.length)<=e)return H(n,i);if(s.length>=e)return H(n,s.slice(0,e).padEnd(s.length,"0"));if(c)return H(n,`${s}.${a.slice(0,e-s.length)}`);let _=a.replace(/^0+/,"")||"0",A=_.slice(0,e),y=a.length-_.length;return H(n,`0.${A.padStart(y+A.length,"0")}`)}toFixed(e=6){let t=this.getValue("string"),n=t.startsWith("-"),[i="0",s=""]=(n?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 H(n,y)}if(!s)return H(n,`${i}.${"0".repeat(e)}`);let a=s[e];if(!(a&&Number.parseInt(a,10)>=5))return H(n,`${i}.${s.slice(0,e).padEnd(e,"0")}`);let u=BigInt(s.slice(0,e).padEnd(e,"0"))+1n,_=10n**BigInt(e);if(u>=_)return H(n,`${BigInt(i)+1n}.${"0".repeat(e)}`);return H(n,`${i}.${u.toString().padStart(e,"0")}`)}toAbbreviation(e=2){let t=this.getValue("string"),n=Number(t),i=["","K","M","B","T","Q","Qi","S"],s=Math.floor(Math.log10(Math.abs(n))/3);if(s===0||!i[s])return t;return`${(n/10**(s*3)).toFixed(e)}${i[s]}`}toCurrency(e="$",{currencyPosition:t="start",decimal:n=2,decimalSeparator:i=".",thousandSeparator:s=",",trimTrailingZeros:a=!0}={}){let c=this.toFixed(n),u=t==="end",[_="0",A=""]=c.split("."),y=_.replace(/\B(?=(\d{3})+(?!\d))/g,s),T=A&&Number.parseInt(A,10)>0,O=T?`${y}${i}${A}`:y,M=O.length<100&&a&&T?O.replace(/\.?0*$/,""):O;return u?`${M}${e}`:`${e}${M}`}formatBigIntToSafeValue(e,t){return X({bigIntDecimal:t||this.decimal||G,decimal:Ae(this.decimalMultiplier),value:e})}#t(e,...t){let n=t.map(be),i=Math.max(G,Ae(this.decimalMultiplier),...n.map(({decimalMultiplier:A})=>Ae(A))),s=Math.min(i+Hn,Un),a=U(s),c=n.reduce((A,y)=>{let T=A.decimalMultiplier*y.decimalMultiplier,O=ye(e).with("add",()=>A.bigIntValue*y.decimalMultiplier+y.bigIntValue*A.decimalMultiplier).with("sub",()=>A.bigIntValue*y.decimalMultiplier-y.bigIntValue*A.decimalMultiplier).with("mul",()=>A.bigIntValue*y.bigIntValue).with("div",()=>{if(y.bigIntValue===0n)throw RangeError("Division by zero");return A.bigIntValue*y.decimalMultiplier}).exhaustive(),S=e==="div"?A.decimalMultiplier*y.bigIntValue:T;return{bigIntValue:O*a/S,decimalMultiplier:a}},this),u=this.decimal===void 0?void 0:Math.min(this.decimal,s),_=c.decimalMultiplier===a?c:{bigIntValue:c.bigIntValue*a/c.decimalMultiplier,decimalMultiplier:a};return this.#n({decimal:u,value:_})}#e(e,t){let n=be(t),i=this.bigIntValue*n.decimalMultiplier,s=n.bigIntValue*this.decimalMultiplier;return ye(e).with("gt",()=>i>s).with("gte",()=>i>=s).with("lt",()=>i<s).with("lte",()=>i<=s).with("eqValue",()=>i===s).exhaustive()}}var $n=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function Bn(e){let n=`${typeof e==="number"?$n.format(e):e}`.replaceAll(",",".").split(".");return n.length>1?`${n.slice(0,-1).join("")}.${n.at(-1)}`:n[0]||"0"}function Fn(e){let t=e.split(".")[1]?.length||0;return Math.max(t,G)}function be(e){if(typeof e==="object")return e;let t=e==="undefined"?"0":Bn(e),n=Fn(t),[i="",s=""]=t.split(".");return{bigIntValue:BigInt(`${i}${s.padEnd(n,"0")}`),decimalMultiplier:U(n)}}function H(e,t){return e&&!/^0(?:\.0*)?$/.test(t)?`-${t}`:t}function bt(e,t){if(t===0n)throw Error("Cannot divide by zero");let n=t/2n;return e>=0n&&t>=0n||e<0n&&t<0n?(e+n)/t:(e-n)/t}function U(e){return 10n**BigInt(e)}function Ae(e){return e.toString().length-1}function Gn(e=""){let t=e.toUpperCase(),n=x.get("chains"),[i]=t.split(".");if(n.includes(i))return!0;let[s]=t.split("/");if(n.includes(s))return!0;throw new b({errorKey:"helpers_invalid_identifier",info:{identifier:e,message:`Invalid identifier: ${e}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}var J=[R.Hype,R.Near,R.Ripple,R.Solana,R.Stellar,R.Sui,R.Ton,R.Tron],He=[R.THORChain,R.Maya];function Se(e,t){return J.includes(e)?t:t.toUpperCase()}var z=new Map,Te=new Map,Q=new Map,qn=3600000;function Yn(e){let t=Q.get(e);if(t?.timestamp&&Date.now()-t.timestamp>qn){Q.delete(e);return}return t}function jn(e,t){if(Q.size>1000){let n=Q.keys().next().value;if(n)Q.delete(n)}Q.set(e,{...t,timestamp:Date.now()})}class D extends B{address;chain;isGasAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:e,decimal:t,tax:n,chain:i,symbol:s,identifier:a}){super({decimal:t,value:e});let c=At(a||`${i}.${s}`);this.type=De(c),this.tax=n,this.chain=c.chain,this.ticker=c.ticker,this.symbol=c.symbol,this.address=c.address,this.isSynthetic=c.isSynthetic,this.isTradeAsset=c.isTradeAsset,this.isGasAsset=c.isGasAsset,this.chainId=oe(c.chain).chainId}toString({includeSynthProtocol:e}={}){return(this.isSynthetic||this.isTradeAsset)&&!e?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){if(this.isSynthetic)return`${this.chain}.${this.symbol.replace(/\//g,".")}`;if(this.isTradeAsset)return`${this.chain}.${this.symbol.replace(/~/g,"..")}`;let e=this.symbol.replace(/\./g,"__");return`${this.chain}.${e}`}getIconUrl(){return z.get(Se(this.chain,this.toString()))?.logoURI}eqAsset({chain:e,symbol:t}){return this.chain===e&&this.symbol===t}eq(e){return this.eqAsset(e)&&this.eqValue(e)}static fromUrl(e,t=0){let n=e.indexOf(".");if(n===-1)throw new b({errorKey:"helpers_invalid_asset_url",info:{urlAsset:e}});let i=e.slice(0,n),s=e.slice(n+1),a=Ve({chain:i,rest:s}).when(({rest:c})=>c.includes(".."),({chain:c,rest:u})=>`${c}.${u.replace(/\.\./g,"~")}`).when(({chain:c,rest:u})=>He.includes(c)&&u.includes("."),({chain:c,rest:u})=>`${c}.${u.replace(/\./g,"/")}`).otherwise(({chain:c,rest:u})=>`${c}.${u.replace(/__/g,".")}`);return D.from({asset:a,value:t})}static from({value:e=0,fromBaseDecimal:t,asyncTokenLookup:n,...i}){let s="address"in i&&"chain"in i,a=Jn(i);if(a===null&&n&&s){let{chain:w,address:Y}=i;return zn({address:Y,chain:w,fromBaseDecimal:t,parsedValue:e})}let c=s&&!a?`${i.chain}.UNKNOWN-${i.address}`:a,{identifier:u,decimal:_}=fe(c),{chain:A,isSynthetic:y,isTradeAsset:T,address:O}=At(u),{baseDecimal:S}=oe(A),M=z.get(Se(A,u));if(!M&&n&&!y&&!T)return(async()=>{let{ticker:w}=W(u),Y=await St({address:O,chain:A,ticker:w});return Me({decimal:Y.decimals,identifier:Y.identifier,value:t?Le(e,t):e})})();let C=M?.decimal||_;ie({condition:!C&&!n,id:`assetValue_static_decimal_not_found_${A}`,warning:`Couldn't find static decimal for one or more tokens on ${A} (Using default ${S} decimal as fallback).
2
+ This can result in incorrect calculations and mess with amount sent on transactions.
3
+ You can load static assets by installing @swapkit/tokens package and calling AssetValue.loadStaticAssets()
4
+ or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`});let{decimal:I,identifier:q,tax:de}=M||{decimal:C||S,identifier:u},pe=t?Le(e,t):we(e,I);return y||T?Xn(q,pe):Me({decimal:I,identifier:q,tax:de,value:pe})}static async loadStaticAssets(e){let{loadTokenLists:t}=await import("@swapkit/tokens"),n=await t(e,{source:x.get("envs").isDev?"dev":"prod"});for(let{tokens:i}of Object.values(n))for(let s of i){let{identifier:a}=s,{chain:c,symbol:u}=W(a),{address:_}=se(u,c),{baseDecimal:A}=oe(c),y=Se(c,a),T="decimals"in s&&s.decimals!==void 0?s.decimals:A,O="logoURI"in s&&s.logoURI?s.logoURI:`https://tokens.swapkit.dev/images/${a.toLowerCase()}.png`,S={decimal:T,identifier:a,logoURI:O,tax:"tax"in s?s.tax:void 0};if(z.set(y,S),_){let M=J.includes(c)?`${c}:${_}`:`${c}:${_.toUpperCase()}`;Te.set(M,a)}}return!0}static setStaticAssets(e){z.clear(),Te.clear();for(let[t,n]of e.entries()){let{identifier:i}=n,{chain:s,symbol:a}=W(i),{address:c}=se(a,s),{baseDecimal:u}=oe(s),_=n.chain??s,A=n.address??c,y=Se(_,i),T=n.decimals??n.decimal??u,O=n.logoURI??`https://tokens.swapkit.dev/images/${i.toLowerCase()}.png`,S={decimal:T,identifier:y,logoURI:O,tax:n.tax};if(z.set(y,S),A){let M=J.includes(_)?`${_}:${A}`:`${_}:${A.toUpperCase()}`;Te.set(M,i)}}return!0}static get staticAssets(){return z}}function Xs(e){let t=D.from({chain:e});return Ve(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 St({chain:e,address:t,ticker:n}){let s=J.includes(e)?`${e}:${t||n}`:`${e}:${t||n}`.toUpperCase(),a=Yn(s);if(a)return a;if(!t){let{baseDecimal:_}=oe(e);return{decimals:_,identifier:`${e}.${n||"UNKNOWN"}`}}let c=await ft({address:t,chain:e}),u=`${e}.${c.ticker||n||"UNKNOWN"}-${t}`;return ie({condition:!!(!c.ticker&&n),id:`async_token_lookup_failed_${e}_${t}`,warning:`Could not fetch token metadata for ${e}:${t} from chain. Using user-provided ticker (${n}) with baseDecimal (${c.decimals}).`}),c.ticker&&jn(s,{decimals:c.decimals,identifier:u}),{decimals:c.decimals,identifier:u}}function Me({identifier:e,decimal:t,value:n,tax:i}){return Gn(e),new D({decimal:t,identifier:e,tax:i,value:we(n,t)})}function Xn(e,t=0){let n=e.includes(".")?e.split(".")?.[0]?.toUpperCase():void 0,i=n?He.includes(n):!1,s=e.slice(0,14).includes("~")?"~":"/",[a,c]=i?e.split(".").slice(1).join().split(s):e.split(s);if(!(a&&c))throw new b({errorKey:"helpers_invalid_asset_identifier",info:{identifier:e}});return new D({decimal:8,identifier:`${n||R.THORChain}.${a}${s}${c}`,value:we(t,8)})}async function zn({address:e,chain:t,fromBaseDecimal:n,parsedValue:i}){let{decimals:s,identifier:a}=await St({address:e,chain:t}),c=n?Le(i,n):i;return Me({decimal:s,identifier:a,value:c})}function Le(e,t){let n=e instanceof B?e.getValue("string"):e;return we(BigInt(n),t)}function we(e,t){return typeof e==="bigint"?X({bigIntDecimal:t,decimal:t,value:e}):e}function Qn(e){let t=Ve(e).when((n)=>("chain"in n)&&n.chain!==void 0,({chain:n})=>n).otherwise((n)=>{let i=W(n.asset);return i.synth?R.THORChain:i.chain});if(!Kn.includes(t.toUpperCase())){let n="asset"in e?e.asset:t;throw new b({errorKey:"helpers_invalid_asset_identifier",info:{identifier:n,message:`Unsupported chain "${t}" - use the AssetValue constructor directly`}})}}function Jn(e){if(Qn(e),"chain"in e){let{chain:s,address:a}=e;if(a){let c=J.includes(s)?`${s}:${a}`:`${s}:${a.toUpperCase()}`,u=Te.get(c);if(u)return u;return null}return s}let{chain:t,symbol:n}=W(e.asset);return De({chain:t,symbol:n})==="Native"?t:e.asset}function Zn(e,t,n){let i=e.split("."),s=i[0]?.toUpperCase(),a=He.includes(s),c=n?"~":"/",[u,_=""]=a?i.slice(1).join(".").split(c):e.split(c);if(!(u&&_))throw new b({errorKey:"helpers_invalid_asset_identifier",info:{identifier:e}});let{ticker:A,address:y}=Tt({chain:u,symbol:_}),T=`${u}${c}${_}`;return{address:y,chain:s,isGasAsset:!1,isSynthetic:t,isTradeAsset:n,symbol:T,ticker:A}}function ei(e){let t=e.indexOf("."),n=(t===-1?e:e.slice(0,t)).toUpperCase(),i=t===-1?e:e.slice(t+1),{address:s,ticker:a}=Tt({chain:n,symbol:i}),c;try{c=s&&Wn.includes(n)&&he(s)?he(s):s}catch{c=s}let u=c?`${a}-${c}`:i;return{address:c,chain:n,isGasAsset:yt({chain:n,symbol:i}),isSynthetic:!1,isTradeAsset:!1,symbol:u,ticker:a}}function At(e){let t=e.slice(0,14),n=t.includes("/"),i=t.includes("~");if(n||i)return Zn(e,n,i);return ei(e)}function Tt({symbol:e,chain:t}){let{ticker:n,address:i}=se(e,t);return{address:i&&!J.includes(t)?i.toLowerCase():i,ticker:n}}class xe extends B{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new xe({decimal:t,value:X({bigIntDecimal:t,decimal:t,value:e})})}}function wt(e=!0){return e?"https://gateway.liquify.com/chain/thorchain_midgard":"https://midgard.mayachain.info"}function ni(e=!0){let t=wt(e);return e?`${t}/v2/thorname`:`${t}/v2/mayaname`}function ii(e){return function(n){let i=n?`?status=${n}`:"";return m.get(`${e}/v2/pools${i}`)}}function ri(e){return function(n){return m.get(`${e}/v2/pool/${n}`)}}function si(e){return function(n,i){let s=i?`?period=${i}`:"";return m.get(`${e}/v2/pool/${n}/stats${s}`)}}function oi(e){return function(n,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 m.get(`${e}/v2/history/depths/${n}${a}`)}}function ai(e){return function(){return m.get(`${e}/v2/network`)}}function li(e){return function(){return m.get(`${e}/v2/health`)}}function ci(e){return function(){return m.get(`${e}/v2/nodes`)}}function di(e){return function(n){return m.get(`${e}/v2/node/${n}`)}}function pi(e){return function(){return m.get(`${e}/v2/mimir/votes`)}}function ui(e){return function(){return m.get(`${e}/v2/mimir`)}}function gi(e){return function(){return m.get(`${e}/v2/constants`)}}function mi(e){return function(){return m.get(`${e}/v2/stats`)}}function _i(e){return function(n){let i=new URLSearchParams;if(n?.interval)i.append("interval",n.interval);if(n?.count)i.append("count",n.count.toString());if(n?.from)i.append("from",n.from.toString());if(n?.to)i.append("to",n.to.toString());let s=i.toString()?`?${i.toString()}`:"";return m.get(`${e}/v2/history/earnings${s}`)}}function hi(e){return function(n,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()}`:"",c=n?`/swaps/${n}`:"/swaps";return m.get(`${e}/v2/history${c}${a}`)}}function fi(e){return function(n){let i=new URLSearchParams;if(n?.interval)i.append("interval",n.interval);if(n?.count)i.append("count",n.count.toString());if(n?.from)i.append("from",n.from.toString());if(n?.to)i.append("to",n.to.toString());let s=i.toString()?`?${i.toString()}`:"";return m.get(`${e}/v2/history/tvl${s}`)}}function yi(e){if(!e)return"";let t=new URLSearchParams,n=(i,s)=>{if(s!==void 0)t.append(i,typeof s==="number"?s.toString():s)};return n("address",e.address),n("txid",e.txid),n("asset",e.asset),n("type",e.type),n("affiliate",e.affiliate),n("limit",e.limit),n("offset",e.offset),t.toString()?`?${t.toString()}`:""}function bi(e){return function(n){let i=yi(n);return m.get(`${e}/v2/actions${i}`)}}function Ai(e){return function(n){return m.get(`${e}/v2/member/${n}`)}}function Si(e){return function(n){let i=n?`/${n}`:"";return m.get(`${e}/v2/members${i}`)}}function Ti(e){return function(n,i){let s=i?`&asset=${i}`:"";return m.get(`${e}/v2/saver/${n}${s?`?${s.substring(1)}`:""}`)}}function wi(e){return function(n){return m.get(`${e}/v2/savers/${n}`)}}function xi(e){return function(n,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()}`:"",c=n?`/savers/${n}`:"/savers";return m.get(`${e}/v2/history${c}${a}`)}}function Ri(e){return function(n){return m.get(`${e}/v2/balance/${n}`)}}function vi(e){return async function(n){let i=(s)=>{if(s?.cause?.status===404)return;throw s};return await m.get(`${e}/lookup/${n}`,{onError:i,retry:{maxRetries:1}})}}function Ii(e){return async function(n){let i=(s)=>{if(s?.cause?.status===404)return[];throw s};return await m.get(`${e}/rlookup/${n}`,{onError:i,retry:{maxRetries:1}})}}function Ci(e){return async function(n){let i=(s)=>{if(s?.cause?.status===404)return[];throw s};return await m.get(`${e}/owner/${n}`,{onError:i,retry:{maxRetries:1}})}}function Z({asset:e,value:t}){return D.from({asset:e,fromBaseDecimal:ti(Re.THORChain).baseDecimal,value:t})}function ki({liquidityPositionGetter:e,isThorchain:t}){return async function(i){let s=await e(i),a=t?"rune":"cacao";return s.pools.map((c)=>({[`${a}Pending`]:Z({asset:"THOR.RUNE",value:c.runePending}),[`${a}RegisteredAddress`]:c.runeAddress,[`${a}Withdrawn`]:Z({asset:"THOR.RUNE",value:c.runeWithdrawn}),[a]:Z({asset:"THOR.RUNE",value:c.runeAdded}),asset:Z({asset:c.pool,value:c.assetAdded}),assetPending:Z({asset:c.pool,value:c.assetPending}),assetRegisteredAddress:c.assetAddress,assetWithdrawn:Z({asset:c.pool,value:c.assetWithdrawn}),dateFirstAdded:c.dateFirstAdded,dateLastAdded:c.dateLastAdded,poolShare:new xe(c.liquidityUnits).div(c.pool)}))}}function xt(e){let t=e===Re.THORChain,n=wt(t),i=ni(t),s=Ai(n);return{getActions:bi(n),getBalance:Ri(n),getConstants:gi(n),getEarningsHistory:_i(n),getHealth:li(n),getLiquidityPosition:ki({isThorchain:t,liquidityPositionGetter:s}),getLiquidityPositionRaw:s,getMembers:Si(n),getMimir:ui(n),getMimirVotes:pi(n),getNameDetails:vi(i),getNamesByAddress:Ii(i),getNamesByOwner:Ci(i),getNetworkInfo:ai(n),getNode:di(n),getNodes:ci(n),getPool:ri(n),getPoolDepthHistory:oi(n),getPoolStats:si(n),getPools:ii(n),getSaverDetails:Ti(n),getSavers:wi(n),getSaversHistory:xi(n),getStats:mi(n),getSwapHistory:hi(n),getTVLHistory:fi(n)}}var Rt=xt(Re.THORChain),vt=xt(Re.Maya);var We={};Xe(We,{SKRequestClient:()=>N,getChainBalance:()=>hr,getChainflipDepositChannel:()=>wr,getGasRate:()=>Tr,getNearDepositChannel:()=>xr,getPrice:()=>Sr,getRouteWithTx:()=>_r,getSwapQuote:()=>mr,getSwapTo:()=>kr,getTokenApproval:()=>fr,getTokenList:()=>br,getTokenListProviders:()=>yr,getTrackerDetails:()=>gr,searchTokens:()=>Ar});import{EVMChains as Ke}from"@swapkit/types";import{match as ur,P as ce}from"ts-pattern";import{Chain as ve,ChainId as ae}from"@swapkit/types";import{array as v,boolean as V,coerce as Pt,number as h,object as g,optional as p,string as o,union as Ue,unknown as $e,z as r}from"zod";var Et;((i)=>{i.CHEAPEST="CHEAPEST";i.FASTEST="FASTEST";i.RECOMMENDED="RECOMMENDED"})(Et||={});var Ie;((y)=>{y.PSBT="PSBT";y.EVM="EVM";y.COSMOS="COSMOS";y.RADIX="RADIX";y.NEAR="NEAR";y.STELLAR="STELLAR";y.TON="TON";y.TRON="TRON";y.EIP_712_HYPE_SEND_ASSET="EIP_712_HYPE_SEND_ASSET";y.EIP_712_HYPE_WITHDRAW="EIP_712_HYPE_WITHDRAW"})(Ie||={});var Nt;((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"})(Nt||={});var Ot;((S)=>{S.swap="swap";S.aggregation="aggregation";S.addLiquidity="addLiquidity";S.withdrawLiquidity="withdrawLiquidity";S.addSavers="addSavers";S.withdrawSavers="withdrawSavers";S.borrow="borrow";S.repay="repay";S.name="name";S.donate="donate";S.claim="claim";S.stake="stake";S.unstake="unstake"})(Ot||={});var Dt;((u)=>{u.unknown="unknown";u.not_started="not_started";u.pending="pending";u.swapping="swapping";u.completed="completed";u.refunded="refunded";u.failed="failed"})(Dt||={});var Mt;((C)=>{C.not_started="not_started";C.starting="starting";C.broadcasted="broadcasted";C.mempool="mempool";C.inbound="inbound";C.outbound="outbound";C.swapping="swapping";C.completed="completed";C.refunded="refunded";C.partially_refunded="partially_refunded";C.dropped="dropped";C.reverted="reverted";C.replaced="replaced";C.retries_exceeded="retries_exceeded";C.parsing_error="parsing_error"})(Mt||={});var ao=g({address:p(o()),chain:r.enum(ve).optional(),chainId:r.enum(ae),coingeckoId:p(o()),decimals:Pt.number(),extensions:p(r.looseObject({})),identifier:o(),logoURI:p(o()),name:p(o()),shortCode:p(o()),symbol:p(o()),ticker:o()}),lo=r.object({block:r.optional(r.number().describe("Block number. Required for Polkadot chain. e.g. `123456`")),chainId:r.optional(r.string().describe("ChainId for the hash. e.g. `thorchain-1`")),depositChannelId:r.optional(r.string().describe("Deposit channel ID, required for Chainflip if tx was broadcasted without wallet connection")),hash:r.optional(r.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"}),co=r.object({forceUpdate:r.string().toLowerCase().transform((e)=>e==="true").pipe(r.boolean()).optional()}),po=g({error:o(),message:o()}),ee=g({address:p(o()),chain:r.enum(ve),decimal:p(h()),isGasAsset:V(),isSynthetic:V(),symbol:o(),tax:p(g({buy:h(),sell:h()})),ticker:o()}),Lt=g({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(),uo=g({cg:p(Lt),identifier:o(),price_usd:h(),provider:o(),timestamp:h()}),Vt=v(g({cg:p(Lt),identifier:o(),price_usd:h(),provider:o(),timestamp:h()}).partial()),go=g({affiliate:p(o().describe("Affiliate thorname")),affiliateFee:p(h().describe("Affiliate fee in basis points").refine((e)=>e===Math.floor(e)&&e>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:p(V().describe("Allow smart contract as recipient")),allowSmartContractSender:p(V().describe("Allow smart contract as sender")),buyAsset:o().describe("Asset to buy"),cfBoost:p(V().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:p(o().describe("Address to send asset to")),disableSecurityChecks:p(V().describe("Disable security checks")),includeTx:p(V().describe("Set to true to include an transaction object (EVM only)")),providers:p(v(o().describe("List of providers to use").refine((e)=>k[e]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:p(o().describe("Referrer address (referral program)")),sellAmount:o().describe("Amount of asset to sell").refine((e)=>+e>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:o().describe("Asset to sell"),slippage:p(h().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:p(o().describe("Address to send asset from"))}).refine((e)=>e.sellAsset!==e.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),mo=g({metadata:V(),tokens:v(g({identifier:o()}))}),Ht=g({destinationAddress:o()}),Pi=Ht.extend({affiliateFees:v(g({brokerAddress:o(),feeBps:h()})).optional(),brokerCommissionBps:h().optional(),buyAsset:g({asset:o(),chain:o()}),channelMetadata:g({cfParameters:o().optional(),gasBudget:o().optional(),message:o().optional()}).optional(),dcaParameters:g({chunkInterval:h().optional(),numberOfChunks:h().optional()}).optional(),maxBoostFeeBps:h().optional(),refundParameters:g({minPrice:o().optional(),refundAddress:o().optional(),retryDuration:h().optional()}).optional(),sellAsset:g({asset:o(),chain:o()})}),Ut=g({channelId:o(),depositAddress:o()}),It=Ht.extend({affiliateFees:g({feeBps:h(),nearId:o()}).optional(),buyAsset:o(),sellAmount:o(),sellAsset:o(),slippage:Pt.number(),sourceAddress:o()}),Ct=g({amountIn:o(),amountInFormatted:o(),amountInUsd:o(),amountOut:o(),amountOutFormatted:o(),amountOutUsd:o(),deadline:o().optional(),minAmountIn:o(),minAmountOut:o(),timeEstimate:h().optional(),timeWhenInactive:o().optional()}),_o=Ct.extend({depositAddress:o(),quote:Ct,signature:o(),timestamp:o(),tx:$e()}),$t=g({buyAsset:o(),buyAssetAmount:o(),buyAssetAmountMaxSlippage:o(),deadline:o().optional(),depositAddress:o(),depositAmount:o(),depositAsset:o(),tx:$e()}),Ei=g({evmCalldata:r.optional(r.string()),intentHash:r.optional(r.string()),logs:r.optional(r.unknown()),manifest:r.optional(r.unknown()),memo:r.optional(r.string()),spender:r.optional(r.string()),thorname:r.optional(r.string())}),Ni=g({currentStage:o(),inboundConfirmation:h(),inboundObservation:h(),outboundDelay:h(),outboundObservation:h(),streamingSwap:h()}),Oi=g({count:p(h()),interval:p(h()),quantity:p(h()),subSwapsMap:p(v(h()))}),Di=r.object({currentLegIndex:r.optional(r.number()),estimatedTimeToComplete:r.number(),estimates:r.optional(Ni),providerDetails:r.optional(r.object({streamingDetails:r.optional(Oi)}))}),Mi=g({affiliate:p(ee),liquidity:p(ee),network:p(ee),protocol:p(ee),tax:p(ee)}),Li=g({affiliate:o(),bps:o(),isReferrer:V()}),Vi=g({affiliate:p(o()),affiliateFees:p(v(Li)),broadcastedAt:p(h()),explorerUrl:p(o()),fees:p(Mi),images:p(g({chain:p(o()),from:p(o()),provider:p(o()),to:p(o())})),provider:p(r.enum(k)),providerAction:r.optional(r.enum(Ot)),quoteId:p(o()),wallet:p(o())}),te=r.object({block:r.number(),chainId:r.enum(ae),finalAddress:r.optional(r.string()),finalAsset:r.optional(ee),finalisedAt:r.number(),fromAddress:r.string(),fromAmount:r.string(),fromAsset:r.string(),hash:r.string(),meta:r.optional(Vi),payload:r.optional(Ei),status:r.enum(Dt),toAddress:r.string(),toAmount:r.string(),toAsset:r.string(),trackingStatus:r.optional(r.enum(Mt)),transient:r.optional(Di),type:r.enum(Nt)}),Bt=te.extend({legs:r.array(te)}),ho=te.extend({legs:v(te)}),fo=te.extend({legs:v(te)}),Be=v(g({amount:o(),asset:o(),chain:o(),protocol:r.enum(k),type:r.enum(Pe)})),Fe=r.object({inbound:r.optional(r.number().describe("Time to receive inbound asset in seconds")),outbound:r.optional(r.number().describe("Time to receive outbound asset in seconds")),swap:r.optional(r.number().describe("Time to swap assets in seconds")),total:r.number().describe("Total time in seconds")}),Hi=/^(?:0x[0-9a-fA-F]+|[0-9]+)$/;function Ui(e){return e===""||Hi.test(e)}function yo(e){return e?BigInt(e):0n}function bo(e){let t=typeof e==="bigint"?e:BigInt(e);return t>0n?`0x${t.toString(16)}`:"0x0"}var le=o().refine(Ui,{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"),$i=g({data:o().describe("Data to send"),from:o().describe("Address of the sender"),to:o().describe("Address of the recipient"),value:le}),Bi=r.object({data:r.string().optional(),raw_data:r.object({contract:r.any(),data:r.string().optional(),expiration:r.number(),fee_limit:r.number().optional(),ref_block_bytes:r.string(),ref_block_hash:r.string(),timestamp:r.number()}).passthrough(),raw_data_hex:r.string(),txID:r.string(),value:le.optional(),visible:r.boolean()}),Fi=v(Ue([o(),h(),v(o()),g({from:o(),value:le}).describe("Parameters to pass to the contract method")])),Ao=g({approvalSpender:p(o().describe("Address of the spender to approve")),approvalToken:p(o().describe("Address of the token to approve spending of")),contractAddress:o().describe("Address of the contract to interact with"),contractMethod:o().describe("Name of the method to call"),contractParamNames:v(o().describe("Names of the parameters to pass to the contract method")),contractParams:Fi}),Ki=g({typeUrl:o("/types.MsgDeposit"),value:g({coins:v(g({amount:o(),asset:g({chain:o(),symbol:o(),synth:V(),ticker:o()})})),memo:o(),signer:o()})}),Wi=g({typeUrl:o("/types.MsgSend"),value:g({amount:v(g({amount:o(),denom:o()})),fromAddress:o(),toAddress:o()})}),Gi=g({typeUrl:o(),value:Wi.shape.value.or(Ki.shape.value)}),qi=g({amount:v(g({amount:o(),denom:o()})),gas:o()}),Yi=g({accountNumber:h(),chainId:r.enum(ae),fee:qi,memo:o(),msgs:v(Gi),sequence:h()}),ji=r.array(r.object({calldata:r.array(r.string()),contractAddress:r.string(),entrypoint:r.string()})),Xi=r.object({address:r.string().describe("Destination address in friendly format"),amount:r.string().describe("Amount in nanotons"),payload:r.string().optional().describe("Base64 BOC of body cell"),stateInit:r.string().optional().describe("Base64 BOC of state init")}),zi=r.object({messages:r.array(Xi),sendMode:r.number().describe("TON wallet send mode for the whole transfer")}),So="USDC:0x6d1e7cde53ba9467b783cb7c530ce054",Qi=r.looseObject({domain:r.looseObject({chainId:p(Ue([h(),o()])),name:p(o()),verifyingContract:p(o()),version:p(o())}),message:r.record(o(),$e()),primaryType:o(),types:r.record(o(),v(r.looseObject({name:o(),type:o()})))}),Ji=r.looseObject({amount:o(),destination:o(),destinationDex:o(),fromSubAccount:o(),hyperliquidChain:o(),nonce:h().int(),signatureChainId:o(),sourceDex:o(),token:o(),type:r.literal("sendAsset")}),Ft=r.looseObject({action:r.looseObject({type:o()}),submitTo:o(),typedData:Qi}),To=Ft.extend({action:Ji}),Kt=Ue([$i,Yi,Bi,zi,Ft,o()]),Zi=Kt.or(ji),er=g({affiliate:o().describe("Affiliate address").optional(),affiliateFee:h().describe("Affiliate fee").optional(),buyAsset:o().describe("Asset to buy"),destinationAddress:o().describe("Destination address"),estimatedTime:Fe.optional(),provider:r.enum(k),sellAsset:o().describe("Asset to sell"),slipPercentage:h().describe("Slippage as a percentage"),sourceAddress:o().describe("Source address")}),wo=er.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),tr=g({asset:o().describe("Asset name"),image:o().describe("Asset image"),price:h().describe("Price in USD")}),nr=Pi,Wt=g({assets:p(v(tr)),maxStreamingQuantity:h().optional(),referrer:o().optional(),streamingInterval:h().optional(),tags:v(r.enum(Et))}),Gt=Wt.extend({affiliate:p(o()),affiliateFee:p(o()),approvalAddress:p(o().describe("Approval address for swap")),chainflip:nr.optional(),garden:It.optional(),near:It.optional(),priceImpact:p(h().describe("Price impact")),referrer:p(o()),txType:p(r.enum(Ie))}),qt=v(g({code:r.enum(ke),display:o(),tooltip:o().optional()})),ir=g({buyAmount:o().describe("Buy amount"),buyAmountMaxSlippage:o().describe("Buy amount max slippage"),buyAsset:o().describe("Asset to buy"),fees:p(Be),provider:r.enum(k),sellAmount:o().describe("Sell amount"),sellAsset:o().describe("Asset to sell")}),rr=g({buyAsset:o().describe("Asset to buy"),destinationAddress:p(o().describe("Destination address")),estimatedTime:p(Fe),expectedBuyAmount:o().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:o().describe("Expected Buy amount max slippage"),expiration:p(o().describe("Expiration")),fees:Be,inboundAddress:p(o().describe("Inbound address")),legs:v(ir),memo:p(o().describe("Memo")),meta:Gt,providers:v(r.enum(k)),routeId:o().describe("Route ID"),sellAmount:o().describe("Sell amount"),sellAsset:o().describe("Asset to sell"),sourceAddress:p(o().describe("Source address")),targetAddress:p(o().describe("Target address")),totalSlippageBps:h().describe("Total slippage in bps"),tx:p(Zi),txType:p(r.enum(Ie)),warnings:qt}),Yt=g({error:p(o().describe("Error message")),providerErrors:p(v(g({errorCode:p(r.enum(ne)),message:p(o()),provider:r.enum(k).optional()}))),quoteId:o().describe("Quote ID"),routes:v(rr)}),jt=r.object({chainId:r.enum(ae),createdAt:r.date(),id:r.number(),unit:r.string(),value:r.string()}),sr=r.array(jt),Xt=r.union([jt,sr]),xo=v(g({chain:r.enum(ve),decimal:h(),identifier:o(),symbol:o(),ticker:o(),value:o()})),Ro=r.union([r.object({amount:r.string(),spender:r.string(),tokenIdentifier:r.string(),userWalletAddress:r.string()}),r.object({amount:r.string(),chainId:r.enum(ae),spender:r.string(),tokenContractAddress:r.string(),userWalletAddress:r.string()}),r.object({routeId:r.string()})]),vo=r.object({approvalTransaction:r.optional(r.object({data:r.string(),from:r.string(),gasLimit:r.optional(r.string()),gasPrice:r.optional(r.string()),to:r.string(),value:le})),approvedAmount:r.string(),isApproved:r.boolean()}),or=r.object({data:r.string().describe("Encoded approval call data"),from:r.string().describe("User wallet address"),gasLimit:r.string().optional().describe("Estimated gas limit"),gasPrice:r.string().optional().describe("Current gas price"),to:r.string().describe("Token contract address"),value:le.describe("ETH value (always '0' for approvals)")}),ar=r.object({tx:r.string(),txType:r.literal("STELLAR")}),lr=r.union([or,ar]),kt=r.object({buyAmount:r.string().describe("Buy amount").optional(),buyAmountMaxSlippage:r.string().describe("Buy amount max slippage").optional(),buyAsset:r.string().describe("Asset to buy"),expectedBuyAmount:r.string().describe("Expected Buy amount").optional(),expectedBuyAmountMaxSlippage:r.string().describe("Expected Buy amount max slippage").optional(),fees:Be,provider:r.enum(k),sellAmount:r.string().describe("Sell amount"),sellAsset:r.string().describe("Asset to sell")}),zt=kt.extend({estimatedTime:r.optional(Fe),expiration:r.optional(r.string().describe("Expiration")),legs:r.array(kt),providers:r.array(r.enum(k)),routeId:r.string().describe("Route ID"),totalSlippageBps:r.number().describe("Total slippage in bps"),warnings:qt}).omit({provider:!0}),Qt=r.object({method:r.string(),payload:r.optional(r.unknown()),url:r.string()}),cr=zt.extend({meta:Wt,nextActions:r.optional(r.array(Qt))}),Io=r.object({error:r.optional(r.string().describe("Error message")),providerErrors:r.optional(r.array(r.object({errorCode:r.optional(r.enum(ne)),message:r.optional(r.string()),provider:r.enum(k).optional()}))),quoteId:r.string().describe("Quote ID"),routes:r.array(cr)}),Co=r.object({providers:r.array(r.enum(k)).optional().describe("Optional list of providers to query for trading pairs"),sellAsset:r.string().describe("Asset identifier to sell (e.g., 'BTC.BTC' or 'ETH.ETH')")}),dr=r.object({chain:r.enum(ve).describe("Chain the asset is on"),identifier:r.string().describe("Asset identifier (e.g., 'ETH.USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')"),providers:r.array(r.enum(k)).describe("Providers that support this trading pair"),symbol:r.string().describe("Asset symbol"),ticker:r.string().describe("Asset ticker")}),ko=r.object({buyAssets:r.array(dr).describe("List of assets that can be swapped to"),sellAsset:r.string().describe("The input sell asset identifier")}),Jt=zt.extend({destinationAddress:r.string().describe("Destination address"),inboundAddress:r.optional(r.string().describe("Inbound address")),memo:r.optional(r.string().describe("Memo to include in the transaction")),meta:Gt,sourceAddress:r.string().describe("Source address"),targetAddress:r.optional(r.string().describe("Target address")),tx:p(Kt),txType:r.optional(r.enum(Ie))}),pr=r.object({data:r.optional(r.record(r.string(),r.string().optional())),errorCode:r.enum(ne),message:r.string().optional(),provider:r.enum(k).optional()}),Po=r.object({error:r.optional(r.string().describe("Error message")),providerErrors:r.optional(r.array(pr)),quoteId:r.string().describe("Quote ID"),routes:r.array(Jt)}),Zt=Jt.extend({approvalTx:lr.optional().describe("Optional approval transaction required before swap execution"),nextActions:r.optional(r.array(Qt)),swapId:r.string().describe("The unique swap ID for tracking")});var N=m.extend({dynamicHeader:async()=>{let e=x.get("widgetId"),t=x.get("widgetKey");if(e&&t&&typeof window<"u"){let i=Math.floor(Date.now()/1000),s=window.location.origin,a=await nt(t,e,s,i);return{Origin:s,"X-Signature":a,"X-Timestamp":i.toString(),"x-widget-id":e}}let{swapKit:n}=x.get("apiKeys");return n?{"x-api-key":n}:{}}});async function gr(e){let t=await N.post(E("/track"),{json:e});try{let n=Bt.safeParse(t);if(!n.success)throw new b("api_v2_invalid_response",n.error);return n.data}catch(n){return t}}async function mr(e){let{getQuote:t}=x.get("endpoints");if(t)return t(e);let i=x.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",s=await N.post(E(i),{json:e});if(s.error)throw new b("api_v2_server_error",{message:s.error});try{let a=Yt.safeParse(s);if(!a.success)throw new b("api_v2_invalid_response",a.error);return a.data}catch{return s}}async function _r(e){let{getRouteWithTx:t}=x.get("endpoints");if(t)return t(e);let i=x.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",s=await N.post(E(i),{json:e});try{let a=Zt.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 hr({chain:e,address:t,scamFilter:n=!0}){let{getBalance:i}=x.get("endpoints");if(i)return i({address:t,chain:e});let s=E(`/balance?chain=${e}&address=${t}`),a=await N.get(s),c=Array.isArray(a)?a:[];return n?Cr(c):c}function fr(e){let t=ur(e).with({routeId:ce.string,spender:ce.string},({routeId:n,spender:i})=>E(`/approve?routeId=${n}&sourceAddress=${i}`)).with({assetValue:ce.instanceOf(D),spender:ce.string,userWallet:ce.string},({spender:n,userWallet:i,assetValue:s})=>E(`/approve?tokenIdentifier=${s.toString()}&userWalletAddress=${i}&spender=${n}&amount=${s.getValue("string")}`)).exhaustive();return N.get(t)}function yr(){let e=E("/providers");return N.get(e)}function br(e){let t=E(`/tokens?provider=${e}`);return N.get(t)}function Ar({query:e,chain:t,page:n,limit:i}){let s=new URLSearchParams({query:e});if(t!==void 0)s.set("chain",t);if(n!==void 0)s.set("page",n.toString());if(i!==void 0)s.set("limit",i.toString());let a=E(`/tokens/search?${s.toString()}`);return N.get(a)}async function Sr(e){let t=E("/price"),n=await N.post(t,{json:e});try{let i=Vt.safeParse(n);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 Tr(){let e=E("/gas"),t=await N.get(e);try{let n=Xt.safeParse(t);if(!n.success)throw new b("api_v2_invalid_response",n.error);return Array.isArray(n)?n:[n]}catch(n){throw new b("api_v2_invalid_response",n)}}async function wr(e){let{destinationAddress:t}=e;if(!t)throw new b("chainflip_broker_invalid_params");let n=x.get("integrations").chainflip?.brokerUrl||E("/chainflip/broker/channel"),i=await N.post(n,{json:e});try{let s=Ut.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 xr(e){let{destinationAddress:t}=e;if(!t)throw new b("chainflip_broker_invalid_params");let n=E("/near/channel"),i=await N.post(n,{json:e});try{let s=$t.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 E(e){let{isDev:t,apiUrl:n,devApiUrl:i}=x.get("envs"),{enabled:s,quoteUrl:a,swapUrl:c}=x.get("localMode");if(s&&e){let[_]=e.split("?");if(_==="/quote"||_==="/v3/quote")return`${a}${e}`;if(_==="/swap"||_==="/v3/swap")return`${c}${e}`}return`${t?i:n}${e}`}function Rr(e){try{return D.from({asset:e.identifier})}catch{return}}var vr=new Set(["OP.OP"]),Ir=/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/im;function Cr(e){return e.filter((t)=>{let n=Rr(t);if(!n)return!1;if(vr.has(n.toString().toUpperCase()))return!0;return(!Ke.includes(n.chain)||n.isGasAsset||!!n.address)&&!Ir.test(n.ticker)})}async function kr(e){let{getSwapTo:t}=x.get("endpoints");if(t)return t(e);let n=new URLSearchParams({sellAsset:e.sellAsset});if(e.providers?.length)for(let c of e.providers)n.append("providers",c);let i=E(`/swapTo?${n.toString()}`),s=await N.get(i);if(!Array.isArray(s))return{buyAssets:[],sellAsset:e.sellAsset};let a=[];for(let c of s)try{let u=D.from({asset:c});a.push({chain:u.chain,identifier:u.toString(),providers:[],symbol:u.symbol,ticker:u.ticker})}catch{}return{buyAssets:a,sellAsset:e.sellAsset}}var Ge={};Xe(Ge,{getInboundAddresses:()=>Mr,getLastBlock:()=>Er,getMimirInfo:()=>Dr,getNodes:()=>Or,getRunePoolInfo:()=>Vr,getRunePoolProviderInfo:()=>Hr,getTHORNodeTNSDetails:()=>en,getTNSPreferredAsset:()=>Lr,getTcyClaimer:()=>Br,getTcyClaimers:()=>Fr,getTcyStaker:()=>Ur,getTcyStakers:()=>$r,getThorchainQueue:()=>Nr});function L(e){let t=x.get("thornodeUrls");return`${e==="mayachain"?t.MAYA:t.THOR}/${e??"thorchain"}`}function Pr(e){let t=e==="mayachain"?"mayaname":"thorname";return`${L(e)}/${t}`}function Er(e="thorchain"){return m.get(`${L(e)}/lastblock`)}function Nr(e){return m.get(`${L(e)}/queue`)}function Or(e){return m.get(`${L(e)}/nodes`)}function Dr(e){return m.get(`${L(e)}/mimir`)}function Mr(e){return m.get(`${L(e)}/inbound_addresses`)}async function en({type:e,name:t}){try{return await m.get(`${Pr(e)}/${t}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:t,owner:"",preferred_asset:""}}}async function Lr({type:e,tns:t}){let n=await en({name:t,type:e});if(!n.preferred_asset||n.preferred_asset===".")return;return D.from({asset:n.preferred_asset,asyncTokenLookup:!0})}function Vr(e){return m.get(`${L(e)}/runepool`)}function Hr({type:e,thorAddress:t}){return m.get(`${L(e)}/rune_provider/${t}`)}function Ur({type:e,address:t}){return m.get(`${L(e)}/tcy_staker/${t}`)}function $r(e){return m.get(`${L(e)}/tcy_stakers`)}function Br({type:e,address:t}){return m.get(`${L(e)}/tcy_claimer/${t}`)}function Fr(e){return m.get(`${L(e)}/tcy_claimers`)}var Ko={...We,mayachainMidgard:vt,thorchainMidgard:Rt,thornode:Ge};
5
+ export{Gr as a,ne as b,ke as c,k as d,Pe as e,ln as f,cn as g,dn as h,b as i,Xr as j,ge as k,Je as l,Jr as m,pn as n,Zr as o,P as p,x as q,m as r,nt as s,_s as t,ie as u,Oe as v,In as w,j as x,Ts as y,ws as z,xs as A,Ms as B,Dn as C,ht as D,ft as E,yt as F,fe as G,De as H,W as I,se as J,Ls as K,Vs as L,X as M,B as N,Gn as O,D as P,Xs as Q,xe as R,Et as S,Ie as T,Nt as U,Ot as V,Dt as W,Mt as X,ao as Y,lo as Z,co as _,po as $,ee as aa,Lt as ba,uo as ca,Vt as da,go as ea,mo as fa,Ht as ga,Pi as ha,Ut as ia,It as ja,_o as ka,$t as la,Bt as ma,ho as na,fo as oa,Be as pa,Fe as qa,Ui as ra,yo as sa,bo as ta,$i as ua,Bi as va,Fi as wa,Ao as xa,Yi as ya,ji as za,Xi as Aa,zi as Ba,So as Ca,Qi as Da,Ji as Ea,Ft as Fa,To as Ga,er as Ha,wo as Ia,tr as Ja,nr as Ka,Wt as La,Gt as Ma,qt as Na,rr as Oa,Yt as Pa,jt as Qa,Xt as Ra,Ro as Sa,vo as Ta,or as Ua,ar as Va,lr as Wa,Io as Xa,Co as Ya,dr as Za,ko as _a,Jt as $a,pr as ab,Po as bb,Zt as cb,Ko as db};
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-8nb97rpv.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,f as L,fa as _r,g as Ot,ga as Cr,h as re,ha as Mr,i as m,ia as Wr,j as kt,ja as $r,k as c,ka as Rr,l as It,la as Dr,m as Nt,ma as Or,n as Ft,na as kr,o as Lt,oa as Ir,p as Bt,pa as Nr,q as x,qa as Fr,r as Ut,ra as Lr,s as Kt,sa as Br,t as Ht,ta as Ur,u as W,ua as Kr,v as jt,va as Hr,w as zt,wa as jr,x as Vt,xa as zr,y as Xt,ya as Vr,z as qt,za as Xr}from"./chunk-yft3rsg6.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,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,Sn 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};