@swapkit/helpers 4.15.2 → 4.15.3

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.
@@ -0,0 +1,5 @@
1
+ var eA=Object.defineProperty;var aA=(N)=>N;function NH(N,A){this[N]=aA.bind(null,A)}var cN=(N,A)=>{for(var H in A)eA(N,H,{get:A[H],enumerable:!0,configurable:!0,set:NH.bind(A,H)})};var LN=((N)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(N,{get:(A,H)=>(typeof require<"u"?require:A)[H]}):N)(function(N){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+N+'" is not supported')});import{Chain as EN,getChainConfig as iH}from"@swapkit/types";import{AllChains as mH,Chain as b,EVMChains as yH,getChainConfig as $N}from"@swapkit/types";import{getAddress as OA}from"ethers";import{match as qN}from"ts-pattern";import{Chain as $,EVMChains as wH,getChainConfig as f,UTXOChains as zH}from"@swapkit/types";import{match as RN}from"ts-pattern";import{AllChains as rN,Chain as lN,getChainConfig as RH,MAYAConfig as IH,StagenetChain as _N,StagenetMAYAConfig as iN,StagenetTHORConfig as sN,THORConfig as BH}from"@swapkit/types";import{createStore as $H}from"zustand/vanilla";import{AllChains as AH,getChainConfig as HH}from"@swapkit/types";var WP=AH.reduce((N,A)=>{return N[A]=HH(A).networkDerivationPath,N},{});var FN;((R)=>{R.unknownError="unknownError";R.test_error="test_error";R.providerDetailsError="providerDetailsError";R.blockHeaderNotFound="blockHeaderNotFound";R.blockHashNotFoundAtHeight="blockHashNotFoundAtHeight";R.blockHashNotFoundAtHash="blockHashNotFoundAtHash";R.txHashMissing="txHashMissing";R.assetValueMissingInfo="assetValueMissingInfo";R.invalidAsset="invalidAsset";R.blockIsRequired="blockIsRequired";R.currentBlockHeaderNotFound="currentBlockHeaderNotFound";R.failedToRetrieveBalance="failedToRetrieveBalance";R.failedToRetrieveBlock="failedToRetrieveBlock";R.failedToRetrieveFees="failedToRetrieveFees";R.notImplementedBCH="notImplementedBCH";R.notImplementedDoge="notImplementedDoge";R.noPoolsFound="noPoolsFound";R.noVaultsFound="noVaultsFound";R.noTxFound="noTxFound";R.noInputCoinFound="noInputCoinFound";R.noBlockDataFound="noBlockDataFound";R.multipleCosmosMessages="multipleCosmosMessages";R.heightOrHashNotProvided="heightOrHashNotProvided";R.unknownDenom="unknownDenom";R.invalidBlockHeight="invalidBlockHeight";R.timestampExtrinsicNoArgumentsForBlock="timestampExtrinsicNoArgumentsForBlock";R.timestampExtrinsicNoTimestampForBlock="timestampExtrinsicNoTimestampForBlock";R.noTimestampExtrinsicForHash="noTimestampExtrinsicForHash";R.timestampExtrinsicNoArgumentsForHash="timestampExtrinsicNoArgumentsForHash";R.txMemoUndefined="txMemoUndefined";R.txMemoIncorrect="txMemoIncorrect";R.txTypeNotFound="txTypeNotFound";R.txNoMessage="txNoMessage";R.txNotFound="txNotFound";R.txReceiptNotFound="txReceiptNotFound";R.txParsingError="txParsingError";R.txLogsParsingError="txLogsParsingError";R.blockNotFound="blockNotFound";R.balanceNotFound="balanceNotFound";R.configError="configError";R.synthSwapDisallowed="synthSwapDisallowed";R.providerQuoteTimeout="providerQuoteTimeout";R.noQuoteResponse="noQuoteResponse";R.noPoolAssetsFound="noPoolAssetsFound";R.noThorchainPools="noThorchainPools";R.noMayachainPools="noMayachainPools";R.noThorchainNetworkInfo="noThorchainNetworkInfo";R.invalidAffiliateFee="invalidAffiliateFee";R.invalidBuyAssetAddress="invalidBuyAssetAddress";R.invalidSellAssetAddress="invalidSellAssetAddress";R.invalidSourceAddress="invalidSourceAddress";R.invalidDestinationAddress="invalidDestinationAddress";R.sourceAddressIsSmartContract="sourceAddressIsSmartContract";R.destinationAddressIsSmartContract="destinationAddressIsSmartContract";R.invalidChainId="invalidChainId";R.unsupportedChainId="unsupportedChainId";R.unsupportedEVMChainId="unsupportedEVMChainId";R.unsupportedMethod="unsupportedMethod";R.unsupportedProvider="unsupportedProvider";R.invalidParamsForMethod="invalidParamsForMethod";R.unsupportedAdapter="unsupportedAdapter";R.noWhitelistTokens="noWhitelistTokens";R.failedFetchGasPrice="failedFetchGasPrice";R.failedToCreateDepositChannel="failedToCreateDepositChannel";R.noProviderDetailsFound="noProviderDetailsFound";R.noTokenListsFound="noTokenListsFound";R.tokenNotFound="tokenNotFound";R.tokenPriceNotFound="tokenPriceNotFound";R.tokenPriceFailedToUpdate="tokenPriceFailedToUpdate";R.swapAmountTooSmall="swapAmountTooSmall";R.legsArrayIsEmpty="legsArrayIsEmpty";R.failedToFetchQuoteForLeg="failedToFetchQuoteForLeg";R.noBlockHeaderFound="noBlockHeaderFound";R.failedToSimulateSwap="failedToSimulateSwap";R.addressScreeningFailed="addressScreeningFailed";R.noLiquidtyProvidersFound="noLiquidtyProvidersFound";R.insufficientLiquidity="insufficientLiquidity";R.noInboundDataFound="noInbounDataFound";R.noInboundAddressesFound="noInboundAddressesFound";R.noInboundAddressFoundForChain="noInboundAddressFoundForChain";R.noLastBlocksFound="noLastBlocksFound";R.noVersionFound="noVersionFound";R.noConstantsFound="noConstantsFound";R.noMimirsFound="noMimirsFound";R.noRoutesFound="noRoutesFound";R.quoteNotFound="quoteNotFound";R.ledgerSignFailed="ledgerSignFailed";R.ledgerWrongPayload="ledgerWrongPayload";R.ledgerFetchSwapFailed="ledgerFetchSwapFailed";R.failedToFetchTx="failedToFetchTx";R.failedBuildTransactionDetails="failedBuildTransactionDetails";R.noLegsForRoute="noLegsForRoute";R.noRouterAddressFound="noRouterAddressFound";R.noAggregatorAddressFound="noAggregatorAddressFound";R.noContractInstanceFound="noContractInstanceFound";R.noContractAddressFound="noContractAddressFound";R.invalidAffiliate="invalidAffiliate";R.thornameAffiliate="thornameAffiliate";R.providerNotfound="No provider found";R.noRecordFound="No Record found";R.slippageTooLow="Slippage too low";R.tradingHalted="tradingHalted";R.noWrappedGasAsset="noWrappedGasAsset";R.aggregatorAddressNotFound="aggregatorAddressNotFound";R.routerAddressNotFound="routerAddressNotFound";R.dummyAddressNotFound="dummyAddressNotFound";R.trackerError="trackerError";R.thorchainPoolUnavailable="thorchainPoolUnavailable";R.noOhlcvDataFound="noOhlcvDataFound";R.noTradingPairs="noTradingPairs";R.noLendingAvailability="noLendingAvailability";R.lendingRepayTooSmall="lendingRepayTooSmall";R.missingState="missingState";R.ledgerSwapNotFound="ledgerSwapNotFound";R.ledgerSwapNotReadyForTracking="ledgerSwapNotReadyForTracking";R.errorEstimatingGas="errorEstimatingGas";R.apiKeyInvalid="apiKeyInvalid";R.apiKeyFailedToUpdate="apiKeyFailedToUpdate";R.apiKeyExpired="apiKeyExpired";R.unauthorized="unauthorized";R.failedToCreateMemo="failedToCreateMemo";R.radixIncorrectInstructions="radixIncorrectInstructions";R.radixTxMissedParam="radixTxMissedParam";R.radixTxMissedAccount="radixTxMissedAccount";R.radixManifestParseError="radixManifestParseError";R.radixManifestBuildError="radixManifestBuildError";R.invalidAddressForChain="invalidAddressForChain";R.riskyAddress="riskyAddress";R.noRoutesToProcess="noRoutesToProcess";R.sellAssetAmountTooSmall="sellAssetAmountTooSmall";R.missingPrivateKey="missingPrivateKey";R.noMemoPriceProtection="noMemoPriceProtection"})(FN||={});var wN;((H)=>{H.highSlippage="highSlippage";H.highPriceImpact="highPriceImpact"})(wN||={});var J;((t)=>{t.CHAINFLIP="CHAINFLIP";t.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";t.JUPITER="JUPITER";t.MAYACHAIN="MAYACHAIN";t.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";t.ONEINCH="ONEINCH";t.PANCAKESWAP="PANCAKESWAP";t.SUSHISWAP_V2="SUSHISWAP_V2";t.THORCHAIN="THORCHAIN";t.THORCHAIN_STREAMING="THORCHAIN_STREAMING";t.TRADERJOE_V2="TRADERJOE_V2";t.UNISWAP_V2="UNISWAP_V2";t.UNISWAP_V3="UNISWAP_V3";t.NEAR="NEAR";t.GARDEN="GARDEN";t.OKX="OKX";t.HARBOR="HARBOR";t.FLASHNET="FLASHNET";t.MAYAN="MAYAN"})(J||={});var zN;((G)=>{G.LIQUIDITY="liquidity";G.NETWORK="network";G.INBOUND="inbound";G.OUTBOUND="outbound";G.AFFILIATE="affiliate";G.TAX="tax";G.PRIORITY="priority";G.SERVICE="service"})(zN||={});var TH;((T)=>{T.Average="average";T.Fast="fast";T.Fastest="fastest"})(TH||={});var PH;((H)=>{H.Approve="approve";H.CheckOnly="checkOnly"})(PH||={});var LH;((g)=>{g.NAME_REGISTER="~";g.BOND="BOND";g.DEPOSIT="+";g.LEAVE="LEAVE";g.UNBOND="UNBOND";g.WITHDRAW="-";g.RUNEPOOL_DEPOSIT="POOL+";g.RUNEPOOL_WITHDRAW="POOL-";g.CLAIM_TCY="tcy";g.STAKE_TCY="tcy+";g.UNSTAKE_TCY="tcy-"})(LH||={});var QN;((D)=>{D.BITGET="BITGET";D.BRAVE="BRAVE";D.COINBASE_MOBILE="COINBASE_MOBILE";D.COINBASE_WEB="COINBASE_WEB";D.COSMOSTATION="COSMOSTATION";D.CTRL="CTRL";D.EIP6963="EIP6963";D.EXODUS="EXODUS";D.KEEPKEY="KEEPKEY";D.KEEPKEY_BEX="KEEPKEY_BEX";D.KEPLR="KEPLR";D.KEYSTORE="KEYSTORE";D.LEAP="LEAP";D.LEDGER="LEDGER";D.METAMASK="METAMASK";D.OKX="OKX";D.OKX_MOBILE="OKX_MOBILE";D.ONEKEY="ONEKEY";D.PASSKEYS="PASSKEYS";D.PASSKEY_WALLET="PASSKEY_WALLET";D.PETRA="PETRA";D.PHANTOM="PHANTOM";D.POLKADOT_JS="POLKADOT_JS";D.RADIX_WALLET="RADIX_WALLET";D.TALISMAN="TALISMAN";D.TREZOR="TREZOR";D.TRONLINK="TRONLINK";D.TRUSTWALLET_WEB="TRUSTWALLET_WEB";D.VULTISIG="VULTISIG";D.WALLETCONNECT="WALLETCONNECT";D.WALLET_SELECTOR="WALLET_SELECTOR";D.XAMAN="XAMAN"})(QN||={});var FH;((T)=>{T[T.NoError=36864]="NoError";T[T.LockedDevice=21781]="LockedDevice";T[T.TC_NotFound=65535]="TC_NotFound"})(FH||={});var uH=rN.reduce((N,A)=>{if(!N.THOR_STAGENET)N[_N.Maya]=iN.rpcUrls,N[_N.THORChain]=sN.rpcUrls;return N[A]=RH(A).rpcUrls,N},{}),OH={[lN.THORChain]:BH.nodeUrl,[lN.Maya]:IH.nodeUrl,[_N.THORChain]:sN.nodeUrl,[_N.Maya]:iN.nodeUrl},eN={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:rN,endpoints:{},envs:{apiUrl:"https://api.swapkit.dev",devApiUrl:"https://dev-api.swapkit.dev",isDev:!1,isStagenet:!1},feeMultipliers:void 0,integrations:{radix:{applicationName:"Swapkit Playground",applicationVersion:"0.0.1",dAppDefinitionAddress:"account_rdx128r289p58222hcvev7frs6kue76pl7pdcnw8725aw658v0zggkh9ws",network:{dashboardBase:"https://dashboard.radixdlt.com",networkId:1,networkName:"mainnet"}}},localMode:{enabled:!1,quoteUrl:"http://localhost:3000",swapUrl:"http://localhost:3001"},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:uH,thornodeUrls:OH,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(QN),widgetId:"",widgetKey:""},Z=$H((N)=>({...eN,setApiKey:(A,H)=>N((T)=>({apiKeys:{...T.apiKeys,[A]:H}})),setConfig:(A)=>N((H)=>({apiKeys:{...H.apiKeys,...A?.apiKeys},chains:H.chains.concat(A?.chains||[]),endpoints:{...H.endpoints,...A?.endpoints},envs:{...H.envs,...A?.envs},feeMultipliers:A?.feeMultipliers||H.feeMultipliers,integrations:{...H.integrations,...A?.integrations},localMode:{...H.localMode,...A?.localMode},rpcUrls:{...H.rpcUrls,...A?.rpcUrls},thornodeUrls:{...H.thornodeUrls,...A?.thornodeUrls},v3SwapFlow:{...H.v3SwapFlow,...A?.v3SwapFlow},wallets:H.wallets.concat(A?.wallets||[]),widgetId:A?.widgetId||H.widgetId,widgetKey:A?.widgetKey||H.widgetKey})),setEndpoint:(A,H)=>N((T)=>({endpoints:{...T.endpoints,[A]:H}})),setEnv:(A,H)=>N((T)=>({envs:{...T.envs,[A]:H}})),setFeeMultipliers:(A)=>N(()=>({feeMultipliers:A})),setIntegrationConfig:(A,H)=>N((T)=>({integrations:{...T.integrations,[A]:H}})),setRequestOptions:(A)=>N((H)=>({requestOptions:{retry:{...H.requestOptions.retry,...A.retry},timeoutMs:A.timeoutMs||H.requestOptions.timeoutMs}})),setRpcUrl:(A,H)=>N((T)=>({rpcUrls:{...T.rpcUrls,[A]:H}})),setThornodeUrl:(A,H)=>N((T)=>({thornodeUrls:{...T.thornodeUrls,[A]:H}})),setWidgetId:(A)=>N({widgetId:A}),setWidgetKey:(A)=>N({widgetKey:A})})),S={get:(N)=>Z.getState()[N],getState:Z.getState,reinitialize:()=>Z.setState(eN),set:(N)=>Z.getState().setConfig(N),setApiKey:(N,A)=>Z.getState().setApiKey(N,A),setEndpoint:(N,A)=>Z.getState().setEndpoint(N,A),setEnv:(N,A)=>Z.getState().setEnv(N,A),setFeeMultipliers:(N)=>Z.getState().setFeeMultipliers(N),setIntegrationConfig:(N,A)=>Z.getState().setIntegrationConfig(N,A),setRequestOptions:(N)=>Z.getState().setRequestOptions(N),setRpcUrl:(N,A)=>Z.getState().setRpcUrl(N,A),setThornodeUrl:(N,A)=>Z.getState().setThornodeUrl(N,A),setWidgetId:(N)=>Z.getState().setWidgetId(N),setWidgetKey:(N)=>Z.getState().setWidgetKey(N)};var GH={core_estimated_max_spendable_chain_not_supported:10001,core_extend_error:10002,core_inbound_data_not_found:10003,core_approve_asset_address_or_from_not_found:10004,core_plugin_not_found:10005,core_plugin_swap_not_found:10006,core_approve_asset_target_invalid:10007,core_explorer_unsupported_chain:10008,core_verify_message_not_supported:10009,core_chain_halted:10010,core_wallet_connection_not_found:10101,core_wallet_ctrl_not_installed:10102,core_wallet_evmwallet_not_installed:10103,core_wallet_walletconnect_not_installed:10104,core_wallet_keystore_not_installed:10105,core_wallet_ledger_not_installed:10106,core_wallet_trezor_not_installed:10107,core_wallet_keplr_not_installed:10108,core_wallet_okx_not_installed:10109,core_wallet_keepkey_not_installed:10110,core_wallet_talisman_not_installed:10111,core_wallet_not_keypair_wallet:10112,core_wallet_sign_message_not_supported:10113,core_wallet_connection_failed:10114,core_wallet_create_not_supported:10115,core_wallet_sign_typed_data_not_supported:10116,core_swap_invalid_params:10201,core_swap_route_not_complete:10202,core_swap_asset_not_recognized:10203,core_swap_contract_not_found:10204,core_swap_route_transaction_not_found:10205,core_swap_contract_not_supported:10206,core_swap_transaction_error:10207,core_swap_quote_mode_not_supported:10208,core_transaction_deposit_error:10301,core_transaction_create_liquidity_base_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_base_address:10306,core_transaction_add_liquidity_base_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_invalid_sender_address:10313,core_transaction_deposit_server_error:10314,core_transaction_user_rejected:10315,core_transaction_failed:10316,core_transaction_invalid_recipient_address:10317,wallet_connection_rejected_by_user:20001,wallet_missing_api_key:20002,wallet_chain_not_supported:20003,wallet_missing_params:20004,wallet_provider_not_found:20005,wallet_failed_to_add_or_switch_network:20006,wallet_ledger_connection_error:20101,wallet_ledger_connection_claimed:20102,wallet_ledger_get_address_error:20103,wallet_ledger_device_not_found:20104,wallet_ledger_device_locked:20105,wallet_ledger_transport_error:20106,wallet_ledger_public_key_error:20107,wallet_ledger_derivation_path_error:20108,wallet_ledger_signing_error:20109,wallet_ledger_app_not_open:20110,wallet_ledger_invalid_response:20111,wallet_ledger_method_not_supported:20112,wallet_ledger_invalid_params:20113,wallet_ledger_invalid_signature:20114,wallet_ledger_no_provider:20115,wallet_ledger_pubkey_not_found:20116,wallet_ledger_transport_not_defined:20117,wallet_ledger_webusb_not_supported:20118,wallet_ledger_chain_not_supported:20119,wallet_ledger_invalid_asset:20120,wallet_ledger_invalid_account:20121,wallet_ledger_address_not_found:20122,wallet_ledger_failed_to_get_address:20123,wallet_ledger_webhid_not_supported:20124,wallet_phantom_not_found:20201,wallet_ctrl_not_found:20301,wallet_ctrl_send_transaction_no_address:20302,wallet_ctrl_contract_address_not_provided:20303,wallet_ctrl_asset_not_defined:20304,wallet_walletconnect_project_id_not_specified:20401,wallet_walletconnect_connection_not_established:20402,wallet_walletconnect_namespace_not_supported:20403,wallet_walletconnect_chain_not_supported:20404,wallet_walletconnect_invalid_method:20405,wallet_walletconnect_method_not_supported:20406,wallet_trezor_failed_to_sign_transaction:20501,wallet_trezor_derivation_path_not_supported:20502,wallet_trezor_failed_to_get_address:20503,wallet_trezor_transport_error:20504,wallet_trezor_method_not_supported:20505,wallet_trezor_failed_to_get_public_key:20506,wallet_talisman_not_enabled:20601,wallet_talisman_not_found:20602,wallet_polkadot_not_found:20701,wallet_radix_not_found:20801,wallet_radix_transaction_failed:20802,wallet_radix_invalid_manifest:20803,wallet_radix_method_not_supported:20804,wallet_radix_no_account:20805,wallet_keepkey_not_found:20901,wallet_keepkey_asset_not_defined:20902,wallet_keepkey_contract_address_not_provided:20903,wallet_keepkey_send_transaction_no_address:20904,wallet_keepkey_derivation_path_error:20905,wallet_keepkey_signing_error:20906,wallet_keepkey_transport_error:20907,wallet_keepkey_unsupported_chain:20908,wallet_keepkey_invalid_response:20909,wallet_keepkey_chain_not_supported:20910,wallet_keepkey_signer_not_found:20911,wallet_keepkey_no_accounts:20912,wallet_keepkey_method_not_supported:20913,wallet_keepkey_invalid_params:20914,wallet_keepkey_config_not_found:20915,wallet_keepkey_no_provider:20916,wallet_keepkey_account_not_found:20917,wallet_keepkey_failed_to_get_public_key:20918,wallet_bitkeep_not_found:21001,wallet_bitkeep_failed_to_switch_network:21002,wallet_bitkeep_no_accounts:21003,wallet_passkeys_sign_transaction_error:21101,wallet_passkeys_not_found:21102,wallet_passkeys_no_address:21103,wallet_passkeys_request_canceled:21104,wallet_passkeys_signature_canceled:21105,wallet_passkeys_failed_to_switch_network:21106,wallet_passkeys_chain_not_supported:21107,wallet_passkeys_instance_missing:21108,wallet_onekey_not_found:21201,wallet_onekey_sign_transaction_error:21202,wallet_okx_not_found:21301,wallet_okx_chain_not_supported:21302,wallet_okx_failed_to_switch_network:21303,wallet_okx_no_accounts:21304,wallet_keplr_not_found:21401,wallet_keplr_chain_not_supported:21402,wallet_keplr_signer_not_found:21403,wallet_keplr_no_accounts:21404,wallet_cosmostation_not_found:21501,wallet_cosmostation_chain_not_supported:21502,wallet_cosmostation_evm_provider_not_found:21503,wallet_cosmostation_keplr_provider_not_found:21504,wallet_cosmostation_no_accounts:21505,wallet_cosmostation_no_evm_accounts:21506,wallet_cosmostation_no_evm_address:21507,wallet_cosmostation_signer_not_found:21508,wallet_passkey_not_supported:21601,wallet_passkey_connection_failed:21602,wallet_coinbase_not_found:21701,wallet_coinbase_chain_not_supported:21702,wallet_coinbase_method_not_supported:21703,wallet_coinbase_no_accounts:21704,wallet_evm_extensions_failed_to_switch_network:21801,wallet_evm_extensions_no_provider:21802,wallet_evm_extensions_not_found:21803,wallet_keystore_invalid_password:21901,wallet_keystore_unsupported_version:21902,wallet_near_extensions_failed_to_switch_network:22001,wallet_near_extensions_no_provider:22002,wallet_near_extensions_not_found:22003,wallet_near_method_not_supported:22004,wallet_petra_not_found:22201,wallet_vultisig_not_found:22101,wallet_vultisig_contract_address_not_provided:22102,wallet_vultisig_asset_not_defined:22103,wallet_vultisig_send_transaction_no_address:22104,wallet_xaman_not_configured:23001,wallet_xaman_not_connected:23002,wallet_xaman_auth_failed:23003,wallet_xaman_connection_failed:23004,wallet_xaman_transaction_failed:23005,wallet_xaman_monitoring_failed:23006,wallet_tronlink_request_accounts_failed:24001,wallet_tronlink_locked:24002,chainflip_channel_error:30001,chainflip_unknown_asset:30002,chainflip_broker_invalid_params:30101,chainflip_broker_recipient_error:30102,chainflip_broker_register:30103,chainflip_broker_tx_error:30104,chainflip_broker_withdraw:30105,chainflip_broker_fund_only_flip_supported:30106,chainflip_broker_fund_invalid_address:30107,thorchain_chain_halted:40001,thorchain_trading_halted:40002,thorchain_asset_is_not_tcy:40003,thorchain_swapin_router_required:40101,thorchain_swapin_vault_required:40102,thorchain_swapin_memo_required:40103,thorchain_swapin_token_required:40104,thorchain_preferred_asset_payout_required:40105,toolbox_cosmos_account_not_found:50101,toolbox_cosmos_invalid_fee:50102,toolbox_cosmos_invalid_params:50103,toolbox_cosmos_no_signer:50104,toolbox_cosmos_not_supported:50105,toolbox_cosmos_signer_not_defined:50106,toolbox_cosmos_validate_address_prefix_not_found:50107,toolbox_cosmos_verify_signature_no_pubkey:50108,toolbox_evm_error_estimating_gas_limit:50201,toolbox_evm_error_sending_transaction:50202,toolbox_evm_gas_estimation_error:50203,toolbox_evm_invalid_gas_asset_address:50204,toolbox_evm_invalid_params:50205,toolbox_evm_invalid_transaction:50206,toolbox_evm_no_abi_fragment:50207,toolbox_evm_no_contract_address:50208,toolbox_evm_no_fee_data:50209,toolbox_evm_no_from_address:50210,toolbox_evm_no_gas_price:50211,toolbox_evm_no_signer_address:50212,toolbox_evm_no_signer:50213,toolbox_evm_no_to_address:50214,toolbox_evm_not_supported:50215,toolbox_evm_provider_not_eip1193_compatible:50216,toolbox_evm_invalid_eip7702_authorization:50217,toolbox_utxo_api_error:50301,toolbox_utxo_broadcast_failed:50302,toolbox_utxo_insufficient_balance:50303,toolbox_utxo_invalid_address:50304,toolbox_utxo_invalid_params:50305,toolbox_utxo_invalid_transaction:50306,toolbox_utxo_no_signer:50307,toolbox_utxo_not_supported:50308,toolbox_utxo_tx_not_found:50309,toolbox_utxo_rbf_not_supported:50310,toolbox_utxo_tx_not_replaceable:50311,toolbox_utxo_tx_already_confirmed:50312,toolbox_utxo_rbf_fee_too_low:50313,toolbox_utxo_rbf_insufficient_change:50314,toolbox_solana_no_signer:50401,toolbox_substrate_not_supported:50501,toolbox_substrate_transfer_error:50502,toolbox_radix_method_not_supported:50601,toolbox_ripple_get_balance_error:50701,toolbox_ripple_rpc_not_configured:50702,toolbox_ripple_signer_not_found:50703,toolbox_ripple_asset_not_supported:50704,toolbox_ripple_broadcast_error:50705,toolbox_ripple_get_trust_lines_error:50706,toolbox_ripple_invalid_trust_line_limit:50707,toolbox_tron_no_signer:50801,toolbox_tron_invalid_token_identifier:50802,toolbox_tron_token_transfer_failed:50803,toolbox_tron_transaction_creation_failed:50804,toolbox_tron_trongrid_api_error:50805,toolbox_tron_approve_failed:50806,toolbox_tron_invalid_token_contract:50807,toolbox_tron_allowance_check_failed:50808,toolbox_tron_invalid_transaction_integrity:50809,toolbox_tron_broadcast_failed:50810,toolbox_hypercore_no_signer:51001,toolbox_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_not_supported:59901,toolbox_fee_estimation_failed:59902,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,api_v2_invalid_response:60001,api_v2_server_error:60002,api_v2_invalid_method_key_hash:60003,helpers_invalid_number_different_decimals:70001,helpers_invalid_number_of_years:70002,helpers_invalid_identifier:70003,helpers_invalid_asset_url:70004,helpers_invalid_asset_identifier:70005,helpers_invalid_memo_type:70006,helpers_failed_to_switch_network:70007,helpers_not_found_provider:70008,helpers_chain_not_supported:70009,helpers_invalid_params:70010,helpers_invalid_response:70011,helpers_chain_no_public_or_set_rpc_url:70012,helpers_chain_rpc_connection_failed:70013,mcp_wallet_not_configured:90001,not_implemented:99999};function JN(N){return JSON.stringify(N,(A,H)=>typeof H==="bigint"?H.toString():H)}class Y extends Error{static ErrorCode=GH;errorKey;info;constructor(N,A){let H=typeof N==="string",T=H?N:N.errorKey,P=H?void 0:N.info,I=`${T}${P?`: ${JN(P)}`:""}`;super(I);if(Object.setPrototypeOf(this,Y.prototype),this.name="SwapKitError",this.errorKey=T,this.info=P,this.cause=A,A){let B=A instanceof Error?`${A.message}${A.cause?` (${A.cause})`:""}`:JN(A);console.error(`SwapKitError [${T}]: ${B}`)}else if(P)console.error(`SwapKitError [${T}]: ${JN(P)}`)}}var MH=(N)=>new Promise((A)=>setTimeout(A,N)),nH=(N,{baseDelay:A,backoffMultiplier:H,maxDelay:T})=>Math.min(A*H**N,T);function _H(N,A){if(N instanceof Error&&N.name==="AbortError")return!0;if(N instanceof TypeError)return!0;if(A===429)return!0;if(A&&A>=500&&A<600)return!0;return!1}var YH=async(N,A)=>{let H=await fetch(N,A),T;try{T=await H.json()}catch{if(!H.ok)throw new Y({errorKey:"helpers_invalid_response",info:{status:H.status,statusText:H.statusText}},{status:H.status,statusText:H.statusText});return{}}if(!H.ok){let I={data:T?.data,error:T?.error,message:T?.message,status:H.status};throw new Y({errorKey:T?.error||"helpers_invalid_response",info:I},I)}let P=T?.routes?.length||T?.result||T?.data&&!T?.error;if(T?.error&&!P){let I={data:T.data,error:T.error,message:T.message,status:H.status};throw new Y({errorKey:T.error,info:I},I)}if(T?.providerErrors?.length||T?.error&&P)console.warn("[SwapKit] Partial errors in response:",T.providerErrors||T.error);return T};function YN(N,A={}){return async function(T,P={}){let{searchParams:I,json:B,body:u,headers:G,dynamicHeader:U,retry:x,timeoutMs:g,abortController:v,onError:X,onSuccess:k,responseHandler:w,...z}={...A,...P},TN=S.get("requestOptions"),h={...TN.retry,...x},t=!!B||T.endsWith(".json"),MN=DH(T,I),CN=U?await U():{},PN=gH(t,{...G,...CN}),c=t?JSON.stringify(B):u,xN;for(let nN=0;nN<=h.maxRetries;nN++){let dN=v||new AbortController,hN=setTimeout(()=>dN.abort(),g||TN.timeoutMs);try{let m=await YH(MN,{...z,body:c,headers:PN,method:N,signal:dN.signal});return clearTimeout(hN),k?.(m)||w?.(m)||m}catch(m){clearTimeout(hN),xN=m;let sA=m?.cause?.status;if(nN>=h.maxRetries||!_H(m,sA))return X?X(m):Promise.reject(m);await MH(nH(nN,h))}}return X?X(xN):Promise.reject(xN)}}function gH(N,A){return{...A,...N&&{"Content-Type":"application/json"}}}function DH(N,A){let H=new URL(N);if(A)H.search=new URLSearchParams(A).toString();return H.toString()}var n={extend:(N)=>({extend:(A)=>n.extend({...N,...A}),get:YN("GET",N),post:YN("POST",N)}),get:YN("GET"),post:YN("POST")};import{Chain as Q,CosmosChains as UH,EVMChains as XH,StagenetChains as SH,UTXOChains as EH}from"@swapkit/types";import{match as HA}from"ts-pattern";import{Chain as ZN}from"@swapkit/types";function aP(N){if(N<0)throw new Y({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:N}});return 10+N}function NL(N){if(N<0)throw new Y({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:N}});return Math.round((10+N*1.0512)*10000000000)/10000000000}function AL(N,A){try{return N()}catch(H){if(A)throw new Y(A,H);return}}function HL(N){switch(N){case ZN.THORChain:return`${N}.RUNE`;case ZN.Cosmos:return`${N}.ATOM`;case ZN.BinanceSmartChain:return`${N}`;default:return`${N}.${N}`}}var aN=new Set;function l({condition:N,id:A,warning:H}){if(N){if(aN.has(A))return;console.warn(H),aN.add(A)}}function tH(N){return HA(N).with(...XH,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...EH,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...UH,...SH,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(Q.Polkadot,Q.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(Q.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(Q.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(Q.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(Q.Aptos,Q.Tron,Q.Radix,Q.Stellar,()=>"").with(Q.Hype,()=>({type:"meta"})).with(Q.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(Q.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(Q.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new Y("helpers_chain_not_supported",{chain:N})})}function NA(N){return HA(N).with(Q.Aptos,()=>"/-/healthy").with(Q.Hype,()=>"/info").with(Q.Radix,()=>"/status/network-configuration").with(Q.Stellar,()=>"").with(Q.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function AA(N,A){try{let H=A.startsWith("wss")?A.replace("wss","https"):A;if(N===Q.Stellar)return(await fetch(`${H}${NA(N)}`,{cache:"no-store",method:"GET",signal:AbortSignal.timeout(3000)})).ok;return(await fetch(`${H}${NA(N)}`,{body:JSON.stringify(tH(N)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var WN=new Map,bH=120000;function xH(N){let[A=""]=S.get("rpcUrls")[N];if(!A)throw l({condition:!0,id:"helpers_chain_no_public_or_set_rpc_url",warning:`No public or set RPC URL found for chain. Please ensure you configured rpcUrls for ${N}.`}),new Y("helpers_chain_no_public_or_set_rpc_url",{chain:N});let H=WN.get(N);if(H&&Date.now()-H.timestamp<bH)return H.url;return WN.set(N,{timestamp:Date.now(),url:A}),A}async function r(N){let A=xH(N),[,...H]=S.get("rpcUrls")[N];if(await AA(N,A))return A;for(let P of H)if(await AA(N,P))return WN.set(N,{timestamp:Date.now(),url:P}),P;throw new Y("helpers_chain_rpc_connection_failed",{chain:N,fallbackUrls:H,primaryRpcUrl:A})}function BL(N){l({condition:!0,id:"initializeRPCUrlsWithFallback",warning:"initializeRPCUrlsWithFallback is deprecated. Use static { rpcUrls, fallbackRpcUrls } SwapKit init config or dynamic SKConfig.setRpcUrl/setFallbackRpcUrl to configure RPC endpoints."})}var nL=[`${$.Maya}.MAYA`,`${$.Maya}.CACAO`,`${$.Ethereum}.THOR`,`${$.Ethereum}.vTHOR`,`${$.Kujira}.USK`,`${$.Ethereum}.FLIP`,`${$.Radix}.XRD`],LA=[$.Arbitrum,$.Aurora,$.Base,$.Ethereum,$.Optimism];async function QH(N){let{baseDecimal:A}=f($.Radix);try{let H=await r($.Radix),{manager:T}=await n.post(`${H}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:N}),headers:{Accept:"*/*","Content-Type":"application/json"}});return T?.divisibility?.value?.divisibility}catch(H){let T=H instanceof Error?H.message:String(H);return console.warn(`Failed to fetch Radix asset decimals for ${N}: ${T}`),A}}async function JH(N){try{let A=await r($.Radix);return(await n.post(`${A}/state/entity/details`,{body:JSON.stringify({addresses:[N],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((P)=>P.key==="symbol")?.value.typed.value||void 0}catch(A){let H=A instanceof Error?A.message:String(A);return console.warn(`Failed to fetch Radix asset symbol for ${N}: ${H}`),""}}async function FA({chain:N,address:A,methodHex:H,id:T}){let P=await r(N);return n.post(P,{body:JSON.stringify({id:T,jsonrpc:"2.0",method:"eth_call",params:[{data:H,to:A.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}async function ZH(N){if(!N||N==="0x")return"UNKNOWN";try{let{AbiCoder:A}=await import("ethers");return A.defaultAbiCoder().decode(["string"],N)[0].trim()}catch(A){return console.warn(`Failed to decode ABI string from ${N}: ${A}`),"UNKNOWN"}}function WH(N,A){if(!N||N==="0x")return A;try{return Number(N)}catch(H){return console.warn(`Failed to decode ABI uint8 from ${N}: ${H}`),A}}async function jH({chain:N,address:A}){let{baseDecimal:H}=f(N),T=A.toLowerCase();if(A===""||!T.startsWith("0x"))return H;let P=await FA({address:A,chain:N,id:2,methodHex:"0x313ce567"}).catch((B)=>{return console.warn(`Could not fetch decimals for ${A} on ${N}: ${B.message}`),{result:""}});return WH(P.result,H)}async function VH({chain:N,address:A}){let H=A.toLowerCase();if(H===""||!H.startsWith("0x"))return;let T=await FA({address:A,chain:N,id:1,methodHex:"0x95d89b41"}).catch((I)=>{return console.warn(`Could not fetch symbol for ${A} on ${N}: ${I.message}`),{result:""}});return await ZH(T.result)}async function TA({rpcUrl:N,contractAddress:A,functionSelector:H}){return(await n.post(`${N}/wallet/triggerconstantcontract`,{body:JSON.stringify({contract_address:A,function_selector:H,owner_address:A,parameter:"",visible:!0}),headers:{accept:"application/json","content-type":"application/json"}}).catch(()=>{return}))?.constant_result?.[0]}function PA(N){let A=N.match(/.{2}/g)?.map((H)=>Number.parseInt(H,16))??[];return new TextDecoder().decode(new Uint8Array(A))}function vH(N){return RN(N).with(void 0,()=>{return}).when((A)=>A.length>=128,(A)=>{let H=Number.parseInt(A.slice(64,128),16);return PA(A.slice(128,128+H*2))}).when((A)=>A.length===64,(A)=>{let H=A.replace(/0+$/,"");if(H.length>0&&H.length%2===0)return PA(H);return}).otherwise(()=>{return})}function RA({chain:N,address:A}){let{baseDecimal:H}=f(N),T={decimals:H,ticker:void 0};return RN(N).with(...wH,async()=>{try{let{isAddress:P,getAddress:I}=await import("ethers");if(!P(I(A.replace(/^0X/,"0x"))))return T;let[B,u]=await Promise.all([VH({address:A,chain:N}),jH({address:A,chain:N})]);return{decimals:u,ticker:B}}catch(P){return console.warn(`Failed to fetch token info for ${A} on ${N}: ${P?.code} ${P?.message}`),T}}).with($.Solana,async()=>{if(!A)return T;try{let P=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${A}`);if(P.ok){let I=await P.json(),B=Array.isArray(I)?I[0]:I;if(B)return{decimals:B.decimals??H,ticker:B.symbol||void 0}}}catch(P){console.warn(`Failed to fetch Solana token info for ${A}: ${P?.code} ${P?.message}`)}return T}).with($.Tron,async()=>{if(!A)return T;try{let P=await r($.Tron),[I,B]=await Promise.all([TA({contractAddress:A,functionSelector:"symbol()",rpcUrl:P}),TA({contractAddress:A,functionSelector:"decimals()",rpcUrl:P})]),u=vH(I);return{decimals:I!==void 0&&B?Number(BigInt(`0x${B}`)):H,ticker:u}}catch(P){let I=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Tron token info for ${A}: ${I}`),T}}).with($.Near,async()=>{if(!A)return T;try{let{JsonRpcProvider:P}=await import("@near-js/providers"),I=await r($.Near),u=await new P({url:I}).query({account_id:A,args_base64:Buffer.from("{}").toString("base64"),finality:"final",method_name:"ft_metadata",request_type:"call_function"}),G=JSON.parse(Buffer.from(u.result).toString());return{decimals:G?.decimals||H,ticker:G?.symbol}}catch(P){let I=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Near token info for ${A}: ${I}`),T}}).with($.Radix,async()=>{if(!A)return T;try{let[P,I]=await Promise.all([JH(A),QH(A)]);return{decimals:I,ticker:P}}catch(P){let I=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Radix token info for ${A}: ${I}`),T}}).otherwise(async()=>T)}function IA({chain:N,symbol:A}){return RN(N).with(...LA,()=>A==="ETH").with($.Avalanche,()=>A==="AVAX").with($.Berachain,()=>A==="BERA").with($.Hyperevm,()=>A==="HYPE").with($.Hype,()=>A==="HYPE").with($.Spark,()=>A==="BTC").with($.BinanceSmartChain,()=>A==="BNB").with($.Gnosis,()=>A==="xDAI"||A==="XDAI").with($.Monad,()=>A==="MON").with($.XLayer,()=>A==="OKB").with($.Maya,()=>A==="CACAO").with($.Cosmos,()=>A==="ATOM").with($.THORChain,()=>A==="RUNE").with($.Tron,()=>A==="TRX").with($.Ripple,()=>A==="XRP").with($.Radix,()=>`${N}.${A}`===gN(N).identifier).otherwise(()=>A===N)}var gN=(N)=>{let{baseDecimal:A}=f(N);return RN(N.toUpperCase()).with(...LA,(T)=>({decimal:A,identifier:`${T}.ETH`})).with($.THORChain,(T)=>({decimal:A,identifier:`${T}.RUNE`})).with($.Cosmos,(T)=>({decimal:A,identifier:`${T}.ATOM`})).with($.Maya,(T)=>({decimal:10,identifier:`${T}.CACAO`})).with($.BinanceSmartChain,(T)=>({decimal:A,identifier:`${T}.BNB`})).with($.Monad,(T)=>({decimal:A,identifier:`${T}.MON`})).with($.Avalanche,(T)=>({decimal:A,identifier:`${T}.AVAX`})).with($.Gnosis,(T)=>({decimal:A,identifier:`${T}.xDAI`})).with($.XLayer,(T)=>({decimal:A,identifier:`${T}.OKB`})).with($.Berachain,(T)=>({decimal:A,identifier:`${T}.BERA`})).with($.Hyperevm,(T)=>({decimal:A,identifier:`${T}.HYPE`})).with($.Hype,(T)=>({decimal:A,identifier:`${T}.HYPE`})).with($.Spark,(T)=>({decimal:A,identifier:`${T}.BTC`})).with($.Tron,(T)=>({decimal:A,identifier:`${T}.TRX`})).with($.Solana,$.Chainflip,$.Kujira,$.Ripple,$.Polkadot,$.Near,...zH,(T)=>({decimal:A,identifier:`${T}.${T}`})).with($.Radix,"XRD.XRD",()=>({decimal:A,identifier:"XRD.XRD"})).with($.Polygon,"POL.POL",()=>({decimal:A,identifier:"POL.POL"})).with("KUJI.USK",(T)=>({decimal:6,identifier:T})).with("ETH.FLIP",()=>({decimal:f($.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:f($.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:f($.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(T)=>({decimal:10,identifier:T})).with("MAYA.MAYA",(T)=>({decimal:4,identifier:T})).otherwise(()=>({decimal:A,identifier:N}))};function jN({chain:N,symbol:A}){if(A.includes("/"))return"Synth";if(A.includes("~"))return"Trade";return RN(N).with($.Radix,()=>A===$.Radix||`${N}.${A}`===gN(N).identifier).with($.Arbitrum,$.Optimism,$.Base,$.Aurora,()=>A===$.Ethereum).with($.Cosmos,()=>A==="ATOM").with($.BinanceSmartChain,()=>A==="BNB").with($.Maya,()=>A==="CACAO").with($.Monad,()=>A==="MON").with($.THORChain,()=>A==="RUNE").with($.Tron,()=>A==="TRX").with($.Hyperevm,()=>A==="HYPE").with($.Hype,()=>A==="HYPE").with($.Spark,()=>A==="BTC").with($.XLayer,()=>A==="OKB").otherwise(()=>A===N)?"Native":N}var o=(N)=>{let[A,...H]=N.split("."),T=N.includes("/"),P=H.join("."),I=P?.split("-"),B=I?.length?I.length===1?I[0]:I.slice(0,-1).join("-"):void 0;return{chain:A,symbol:P,synth:T,ticker:B}};function IN(N,A){let T=A===$.Near?N.indexOf("-"):N.lastIndexOf("-");if(T===-1)return{address:void 0,ticker:N};return{address:N.slice(T+1),ticker:N.slice(0,T)}}function _L(N){return`https://storage.googleapis.com/token-list-swapkit-dev/images/${N.toLowerCase()}.png`}async function YL(N){let{loadTokenLists:A}=await import("./tokens.js"),H=await A(),T=Object.values(H).flatMap((I)=>I.tokens);if("identifier"in N)return T.find((I)=>I.identifier===N.identifier)?.identifier;let P=N.contract.toLowerCase();for(let I of T){let{chain:B,symbol:u}=o(I.identifier);if(B!==N.chain)continue;let{address:G}=IN(u,B);if(G?.toLowerCase()===P)return I.identifier}return}var BA=["TERRA",...S.get("chains")];function $A(N=""){let A=N.toUpperCase(),[H]=A.split(".");if(BA.includes(H))return!0;let[T]=A.split("/");if(BA.includes(T))return!0;throw new Y({errorKey:"helpers_invalid_identifier",info:{identifier:N,message:`Invalid identifier: ${N}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}function XL(N){if(N.length>30)return!1;let A=/^[a-zA-Z0-9+_-]+$/g;return!!N.match(A)}import{match as DN}from"ts-pattern";var i=8,qH=10;function d({value:N,bigIntDecimal:A=i,decimal:H=i}){if(H===0)return N.toString();let T=N<0n,P=N.toString().substring(T?1:0),I=H-(P.length-1);if(I>0)P="0".repeat(I)+P;let B=P.length-H,u=P.slice(-H);if(Number.parseInt(u[A]||"0",10)>=5){let U=Number.parseInt(u[A-1]||"0",10);u=`${u.substring(0,A-1)}${U+1}`}else u=u.substring(0,A);return`${T?"-":""}${P.slice(0,B)}.${u}`.replace(/\.?0*$/,"")}class y{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(N,A){return new y({decimal:A,value:d({bigIntDecimal:A,decimal:A,value:N})})}static shiftDecimals({value:N,from:A,to:H}){return y.fromBigInt(N.getBaseValue("bigint")*C(H)/C(A),H)}constructor(N){let A=VN(N),H=typeof N==="object";this.decimal=H?N.decimal:void 0,this.decimalMultiplier=H&&"decimalMultiplier"in N?N.decimalMultiplier:C(Math.max(uA(UN(A)),this.decimal||0)),this.#P(A)}set(N){return new this.constructor({decimal:this.decimal,identifier:this.toString?.({includeSynthProtocol:!0}),value:N})}add(...N){return this.#A("add",...N)}sub(...N){return this.#A("sub",...N)}mul(...N){return this.#A("mul",...N)}div(...N){return this.#A("div",...N)}gt(N){return this.#N("gt",N)}gte(N){return this.#N("gte",N)}lt(N){return this.#N("lt",N)}lte(N){return this.#N("lte",N)}eqValue(N){return this.#N("eqValue",N)}getValue(N,A){let H=BN(this.decimalMultiplier),T=A!==void 0?A:this.decimal,P=T!==void 0?T:H;if(T!==void 0&&T<H){if(this.formatBigIntToSafeValue(this.bigIntValue,T)==="0"&&this.bigIntValue!==0n)P=H}let I=this.formatBigIntToSafeValue(this.bigIntValue,P);return DN(N).with("number",()=>Number(I)).with("string",()=>I).with("bigint",()=>{return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}).otherwise(()=>I)}getBaseValue(N,A){let H=this.decimalMultiplier/C(A||this.decimal||i),T=KH(this.bigIntValue,H);return DN(N).with("number",()=>Number(T)).with("string",()=>T.toString()).otherwise(()=>T)}getBigIntValue(N,A){if(!A&&typeof N==="object")return N.bigIntValue;let H=VN(N),T=UN(H);if(T==="0"||T==="undefined")return 0n;return this.#T(T,A)}toSignificant(N=6){let A=this.getValue("string"),[H="",T=""]=A.split("."),P=Number.parseInt(H,10)>0;if((P?H.length+T.length:T.length)<=N)return A;if(H.length>=N)return H.slice(0,N).padEnd(H.length,"0");if(P)return`${H}.${T.slice(0,N-H.length)}`;let B=Number.parseInt(T,10).toString(),u=B.slice(0,N),G=T.length-B.length;return`0.${u.padStart(G+u.length,"0")}`}toFixed(N=6){let A=this.getValue("string"),H=A.startsWith("-"),[T="0",P=""]=(H?A.slice(1):A).split("."),I=T==="0"&&Number.parseInt(P.slice(0,N),10)===0,B=H&&!I?"-":"";if(N===0){if(T==="0"&&!P)return"0";return P&&Number.parseInt(P[0]||"0",10)>=5?`${B}${BigInt(T)+1n}.0`:`${B}${T}.0`}if(!P)return`${B}${T}.${"0".repeat(N)}`;let u=P[N];if(!(u&&Number.parseInt(u,10)>=5))return`${B}${T}.${P.slice(0,N).padEnd(N,"0")}`;let U=BigInt(P.slice(0,N).padEnd(N,"0"))+1n,x=10n**BigInt(N);if(U>=x)return`${B}${BigInt(T)+1n}.${"0".repeat(N)}`;return`${B}${T}.${U.toString().padStart(N,"0")}`}toAbbreviation(N=2){let A=this.getValue("string"),H=Number(A),T=["","K","M","B","T","Q","Qi","S"],P=Math.floor(Math.log10(Math.abs(H))/3);if(P===0||!T[P])return A;return`${(H/10**(P*3)).toFixed(N)}${T[P]}`}toCurrency(N="$",{currencyPosition:A="start",decimal:H=2,decimalSeparator:T=".",thousandSeparator:P=",",trimTrailingZeros:I=!0}={}){let B=this.toFixed(H),u=A==="end",[G="0",U=""]=B.split("."),x=G.replace(/\B(?=(\d{3})+(?!\d))/g,P),g=U&&Number.parseInt(U,10)>0,v=g?`${x}${T}${U}`:x,k=v.length<100&&I&&g?v.replace(/\.?0*$/,""):v;return u?`${k}${N}`:`${N}${k}`}formatBigIntToSafeValue(N,A){let H=A||this.decimal||i,T=Math.max(H,BN(this.decimalMultiplier));return d({bigIntDecimal:H,decimal:T,value:N})}#A(N,...A){let H=this.#H(this,...A),T=BN(this.decimalMultiplier),I=Math.max(H,T)+qH,B=C(I),u=A.reduce((U,x)=>{let g=this.getBigIntValue(x,I);return DN(N).with("add",()=>U+g).with("sub",()=>U-g).with("mul",()=>U*g/B).with("div",()=>{if(g===0n)throw RangeError("Division by zero");return U*B/g}).otherwise(()=>U)},this.bigIntValue*B/this.decimalMultiplier),G=d({bigIntDecimal:I,decimal:I,value:u});return new this.constructor({decimal:this.decimal,decimalMultiplier:C(I),identifier:this.toString(),value:G})}#N(N,...A){let H=this.#H(this,...A),T=this.getBigIntValue(A[0]||"0",H),P=this.getBigIntValue(this,H);return DN(N).with("gt",()=>P>T).with("gte",()=>P>=T).with("lt",()=>P<T).with("lte",()=>P<=T).with("eqValue",()=>P===T).otherwise(()=>!1)}#P(N){let A=UN(N)||"0";this.bigIntValue=this.#T(A)}#H(...N){let A=N.map((H)=>{return typeof H==="object"?H.decimal||BN(H.decimalMultiplier):uA(UN(H))}).filter(Boolean);return Math.max(...A,i)}#T(N,A){let H=A?C(A):this.decimalMultiplier,T=BN(H),[P="",I=""]=N.split(".");return BigInt(`${P}${I.padEnd(T,"0")}`)}}var kH=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function UN(N){let H=`${typeof N==="number"?kH.format(N):VN(N)}`.replaceAll(",",".").split(".");return H.length>1?`${H.slice(0,-1).join("")}.${H.at(-1)}`:H[0]||"0"}function uA(N){let A=N.split(".")[1]?.length||0;return Math.max(A,i)}function VN(N){return typeof N==="object"?"getValue"in N?N.getValue("string"):N.value:N}function KH(N,A){if(A===0n)throw Error("Cannot divide by zero");let H=A/2n;return N>=0n&&A>=0n||N<0n&&A<0n?(N+H)/A:(N-H)/A}function C(N){return 10n**BigInt(N)}function BN(N){return Math.log10(Number.parseFloat(N.toString()))}var p=[b.Hype,b.Near,b.Ripple,b.Solana,b.Sui,b.Ton,b.Tron],kN=[b.THORChain,b.Maya],s=new Map,XN=new Map,e=new Map,pH=3600000;function fH(N){let A=e.get(N);if(A?.timestamp&&Date.now()-A.timestamp>pH){e.delete(N);return}return A}function oH(N,A){if(e.size>1000){let H=e.keys().next().value;if(H)e.delete(H)}e.set(N,{...A,timestamp:Date.now()})}class W extends y{address;chain;isGasAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:N,decimal:A,tax:H,chain:T,symbol:P,identifier:I}){super(typeof N==="object"?N:{decimal:A,value:N});let B=GA(I||`${T}.${P}`);this.type=jN(B),this.tax=H,this.chain=B.chain,this.ticker=B.ticker,this.symbol=B.symbol,this.address=B.address,this.isSynthetic=B.isSynthetic,this.isTradeAsset=B.isTradeAsset,this.isGasAsset=B.isGasAsset,this.chainId=$N(B.chain).chainId}toString({includeSynthProtocol:N}={}){return(this.isSynthetic||this.isTradeAsset)&&!N?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){if(this.isSynthetic)return`${this.chain}.${this.symbol.replace(/\//g,".")}`;if(this.isTradeAsset)return`${this.chain}.${this.symbol.replace(/~/g,"..")}`;let N=this.symbol.replace(/\./g,"__");return`${this.chain}.${N}`}getIconUrl(){return s.get(this.toString())?.logoURI}eqAsset({chain:N,symbol:A}){return this.chain===N&&this.symbol===A}eq(N){return this.eqAsset(N)&&this.eqValue(N)}static fromUrl(N,A=0){let H=N.indexOf(".");if(H===-1)throw new Y({errorKey:"helpers_invalid_asset_url",info:{urlAsset:N}});let T=N.slice(0,H),P=N.slice(H+1),I=qN({chain:T,rest:P}).when(({rest:B})=>B.includes(".."),({chain:B,rest:u})=>`${B}.${u.replace(/\.\./g,"~")}`).when(({chain:B,rest:u})=>kN.includes(B)&&u.includes("."),({chain:B,rest:u})=>`${B}.${u.replace(/\./g,"/")}`).otherwise(({chain:B,rest:u})=>`${B}.${u.replace(/__/g,".")}`);return W.from({asset:I,value:A})}static from({value:N=0,fromBaseDecimal:A,asyncTokenLookup:H,...T}){let P=N instanceof y?N.getValue("string"):N,I="address"in T&&"chain"in T,B=cH(T);if(B===null&&H&&I){let{chain:PN,address:c}=T;return dH({address:c,chain:PN,fromBaseDecimal:A,parsedValue:P})}let u=I&&!B?`${T.chain}.UNKNOWN-${T.address}`:B,{identifier:G,decimal:U}=gN(u),{chain:x,isSynthetic:g,isTradeAsset:v,address:X}=GA(G),{baseDecimal:k}=$N(x),w=s.get(p.includes(x)?G:G.toUpperCase());if(!w&&H&&!g&&!v)return(async()=>{let{ticker:PN}=o(G),c=await MA({address:X,chain:x,ticker:PN});return vN({decimal:c.decimals,identifier:c.identifier,value:A?a(BigInt(P),A):P})})();let z=w?.decimal||U;l({condition:!z&&!H,id:`assetValue_static_decimal_not_found_${x}`,warning:`Couldn't find static decimal for one or more tokens on ${x} (Using default ${k} decimal as fallback).
2
+ This can result in incorrect calculations and mess with amount sent on transactions.
3
+ You can load static assets by installing @swapkit/tokens package and calling AssetValue.loadStaticAssets()
4
+ or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`});let{decimal:TN,identifier:h,tax:t}=w||{decimal:z||k,identifier:G},MN=A?a(BigInt(P),A):a(P,TN);return g||v?CH(h,MN):vN({decimal:TN,identifier:h,tax:t,value:MN})}static async loadStaticAssets(N){let{loadTokenLists:A}=await import("@swapkit/tokens"),H=await A(N);for(let{tokens:T}of Object.values(H))for(let P of T){let{identifier:I}=P,{chain:B,symbol:u}=o(I),{address:G}=IN(u,B),{baseDecimal:U}=$N(B),x=p.includes(B)?I:I.toUpperCase(),g="decimals"in P&&P.decimals!==void 0?P.decimals:U,v="logoURI"in P&&P.logoURI?P.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${I.toLowerCase()}.png`,X={decimal:g,identifier:I,logoURI:v,tax:"tax"in P?P.tax:void 0};if(s.set(x,X),G){let k=p.includes(B)?`${B}:${G}`:`${B}:${G.toUpperCase()}`;XN.set(k,I)}}return!0}static setStaticAssets(N){s.clear(),XN.clear();for(let[A,H]of N.entries()){let{identifier:T}=H,{chain:P,symbol:I}=o(T),{address:B}=IN(I,P),{baseDecimal:u}=$N(P),G=H.chain??P,U=H.address??B,x=p.includes(G)?T:T.toUpperCase(),g=H.decimals??H.decimal??u,v=H.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${T.toLowerCase()}.png`,X={decimal:g,identifier:x,logoURI:v,tax:H.tax};if(s.set(x,X),U){let k=p.includes(G)?`${G}:${U}`:`${G}:${U.toUpperCase()}`;XN.set(k,T)}}return!0}static get staticAssets(){return s}}function jL(N){let A=W.from({chain:N});return qN(N).with(b.Bitcoin,b.Litecoin,b.BitcoinCash,b.Dash,()=>A.set(0.00010001)).with(b.Dogecoin,()=>A.set(1.00000001)).with(b.Avalanche,b.Ethereum,b.Arbitrum,b.BinanceSmartChain,()=>A.set(0.00000001)).with(b.THORChain,b.Maya,()=>A.set(0)).with(b.Cosmos,b.Kujira,()=>A.set(0.000001)).otherwise(()=>A.set(0.00000001))}async function MA({chain:N,address:A,ticker:H}){let P=p.includes(N)?`${N}:${A||H}`:`${N}:${A||H}`.toUpperCase(),I=fH(P);if(I)return I;if(!A){let{baseDecimal:G}=$N(N);return{decimals:G,identifier:`${N}.${H||"UNKNOWN"}`}}let B=await RA({address:A,chain:N}),u=`${N}.${B.ticker||H||"UNKNOWN"}-${A}`;return l({condition:!!(!B.ticker&&H),id:`async_token_lookup_failed_${N}_${A}`,warning:`Could not fetch token metadata for ${N}:${A} from chain. Using user-provided ticker (${H}) with baseDecimal (${B.decimals}).`}),B.ticker&&oH(P,{decimals:B.decimals,identifier:u}),{decimals:B.decimals,identifier:u}}function vN({identifier:N,decimal:A,value:H,tax:T}){return $A(N),new W({decimal:A,identifier:N,tax:T,value:a(H,A)})}function CH(N,A=0){let H=N.includes(".")?N.split(".")?.[0]?.toUpperCase():void 0,T=H?kN.includes(H):!1,P=N.slice(0,14).includes("~")?"~":"/",[I,B]=T?N.split(".").slice(1).join().split(P):N.split(P);if(!(I&&B))throw new Y({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});return new W({decimal:8,identifier:`${H||b.THORChain}.${I}${P}${B}`,value:a(A,8)})}async function dH({address:N,chain:A,fromBaseDecimal:H,parsedValue:T}){let{decimals:P,identifier:I}=await MA({address:N,chain:A}),B=H?a(BigInt(T),H):T;return vN({decimal:P,identifier:I,value:B})}function a(N,A){return typeof N==="bigint"?d({bigIntDecimal:A,decimal:A,value:N}):N}function hH(N){let A=qN(N).when((H)=>("chain"in H)&&H.chain!==void 0,({chain:H})=>H).otherwise((H)=>{let T=o(H.asset);return T.synth?b.THORChain:T.chain});if(!mH.includes(A.toUpperCase())){let H="asset"in N?N.asset:A;throw new Y({errorKey:"helpers_invalid_asset_identifier",info:{identifier:H,message:`Unsupported chain "${A}" - use the AssetValue constructor directly`}})}}function cH(N){if(hH(N),"chain"in N){let{chain:P,address:I}=N;if(I){let B=p.includes(P)?`${P}:${I}`:`${P}:${I.toUpperCase()}`,u=XN.get(B);if(u)return u;return null}return P}let{chain:A,symbol:H}=o(N.asset);return jN({chain:A,symbol:H})==="Native"?A:N.asset}function lH(N,A,H){let T=N.split("."),P=T[0]?.toUpperCase(),I=kN.includes(P),B=H?"~":"/",[u,G=""]=I?T.slice(1).join(".").split(B):N.split(B);if(!(u&&G))throw new Y({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});let{ticker:U,address:x}=nA({chain:u,symbol:G}),g=`${u}${B}${G}`;return{address:x,chain:P,isGasAsset:!1,isSynthetic:A,isTradeAsset:H,symbol:g,ticker:U}}function rH(N){let A=N.indexOf("."),H=(A===-1?N:N.slice(0,A)).toUpperCase(),T=A===-1?N:N.slice(A+1),{address:P,ticker:I}=nA({chain:H,symbol:T}),B;try{B=P&&yH.includes(H)&&OA(P)?OA(P):P}catch{B=P}let u=B?`${I}-${B}`:T;return{address:B,chain:H,isGasAsset:IA({chain:H,symbol:T}),isSynthetic:!1,isTradeAsset:!1,symbol:u,ticker:I}}function GA(N){let A=N.slice(0,14),H=A.includes("/"),T=A.includes("~");if(H||T)return lH(N,H,T);return rH(N)}function nA({symbol:N,chain:A}){let{ticker:H,address:T}=IN(N,A);return{address:T&&!p.includes(A)?T.toLowerCase():T,ticker:H}}class SN extends y{eq(N){return this.eqValue(N)}static fromBigInt(N,A){return new SN({decimal:A,value:d({bigIntDecimal:A,decimal:A,value:N})})}}function _A(N=!0){return N?"https://midgard.thorchain.network":"https://midgard.mayachain.info"}function sH(N=!0){let A=_A(N);return N?`${A}/v2/thorname`:`${A}/v2/mayaname`}function eH(N){return function(H){let T=H?`?status=${H}`:"";return n.get(`${N}/v2/pools${T}`)}}function aH(N){return function(H){return n.get(`${N}/v2/pool/${H}`)}}function NT(N){return function(H,T){let P=T?`?period=${T}`:"";return n.get(`${N}/v2/pool/${H}/stats${P}`)}}function AT(N){return function(H,T){let P=new URLSearchParams;if(T?.interval)P.append("interval",T.interval);if(T?.count)P.append("count",T.count.toString());if(T?.from)P.append("from",T.from.toString());if(T?.to)P.append("to",T.to.toString());let I=P.toString()?`?${P.toString()}`:"";return n.get(`${N}/v2/history/depths/${H}${I}`)}}function HT(N){return function(){return n.get(`${N}/v2/network`)}}function TT(N){return function(){return n.get(`${N}/v2/health`)}}function PT(N){return function(){return n.get(`${N}/v2/nodes`)}}function LT(N){return function(H){return n.get(`${N}/v2/node/${H}`)}}function FT(N){return function(){return n.get(`${N}/v2/mimir/votes`)}}function RT(N){return function(){return n.get(`${N}/v2/mimir`)}}function IT(N){return function(){return n.get(`${N}/v2/constants`)}}function BT(N){return function(){return n.get(`${N}/v2/stats`)}}function $T(N){return function(H){let T=new URLSearchParams;if(H?.interval)T.append("interval",H.interval);if(H?.count)T.append("count",H.count.toString());if(H?.from)T.append("from",H.from.toString());if(H?.to)T.append("to",H.to.toString());let P=T.toString()?`?${T.toString()}`:"";return n.get(`${N}/v2/history/earnings${P}`)}}function uT(N){return function(H,T){let P=new URLSearchParams;if(T?.interval)P.append("interval",T.interval);if(T?.count)P.append("count",T.count.toString());if(T?.from)P.append("from",T.from.toString());if(T?.to)P.append("to",T.to.toString());let I=P.toString()?`?${P.toString()}`:"",B=H?`/swaps/${H}`:"/swaps";return n.get(`${N}/v2/history${B}${I}`)}}function OT(N){return function(H){let T=new URLSearchParams;if(H?.interval)T.append("interval",H.interval);if(H?.count)T.append("count",H.count.toString());if(H?.from)T.append("from",H.from.toString());if(H?.to)T.append("to",H.to.toString());let P=T.toString()?`?${T.toString()}`:"";return n.get(`${N}/v2/history/tvl${P}`)}}function GT(N){if(!N)return"";let A=new URLSearchParams,H=(T,P)=>{if(P!==void 0)A.append(T,typeof P==="number"?P.toString():P)};return H("address",N.address),H("txid",N.txid),H("asset",N.asset),H("type",N.type),H("affiliate",N.affiliate),H("limit",N.limit),H("offset",N.offset),A.toString()?`?${A.toString()}`:""}function MT(N){return function(H){let T=GT(H);return n.get(`${N}/v2/actions${T}`)}}function nT(N){return function(H){return n.get(`${N}/v2/member/${H}`)}}function _T(N){return function(H){let T=H?`/${H}`:"";return n.get(`${N}/v2/members${T}`)}}function YT(N){return function(H,T){let P=T?`&asset=${T}`:"";return n.get(`${N}/v2/saver/${H}${P?`?${P.substring(1)}`:""}`)}}function gT(N){return function(H){return n.get(`${N}/v2/savers/${H}`)}}function DT(N){return function(H,T){let P=new URLSearchParams;if(T?.interval)P.append("interval",T.interval);if(T?.count)P.append("count",T.count.toString());if(T?.from)P.append("from",T.from.toString());if(T?.to)P.append("to",T.to.toString());let I=P.toString()?`?${P.toString()}`:"",B=H?`/savers/${H}`:"/savers";return n.get(`${N}/v2/history${B}${I}`)}}function UT(N){return function(H){return n.get(`${N}/v2/balance/${H}`)}}function XT(N){return async function(H){let T=(P)=>{if(P?.cause?.status===404)return;throw P};return await n.get(`${N}/lookup/${H}`,{onError:T,retry:{maxRetries:1}})}}function ST(N){return async function(H){let T=(P)=>{if(P?.cause?.status===404)return[];throw P};return await n.get(`${N}/rlookup/${H}`,{onError:T,retry:{maxRetries:1}})}}function ET(N){return async function(H){let T=(P)=>{if(P?.cause?.status===404)return[];throw P};return await n.get(`${N}/owner/${H}`,{onError:T,retry:{maxRetries:1}})}}function NN({asset:N,value:A}){return W.from({asset:N,fromBaseDecimal:iH(EN.THORChain).baseDecimal,value:A})}function tT({liquidityPositionGetter:N,isThorchain:A}){return async function(T){let P=await N(T),I=A?"rune":"cacao";return P.pools.map((B)=>({[`${I}Pending`]:NN({asset:"THOR.RUNE",value:B.runePending}),[`${I}RegisteredAddress`]:B.runeAddress,[`${I}Withdrawn`]:NN({asset:"THOR.RUNE",value:B.runeWithdrawn}),[I]:NN({asset:"THOR.RUNE",value:B.runeAdded}),asset:NN({asset:B.pool,value:B.assetAdded}),assetPending:NN({asset:B.pool,value:B.assetPending}),assetRegisteredAddress:B.assetAddress,assetWithdrawn:NN({asset:B.pool,value:B.assetWithdrawn}),dateFirstAdded:B.dateFirstAdded,dateLastAdded:B.dateLastAdded,poolShare:new SN(B.liquidityUnits).div(B.pool)}))}}function YA(N){let A=N===EN.THORChain,H=_A(A),T=sH(A),P=nT(H);return{getActions:MT(H),getBalance:UT(H),getConstants:IT(H),getEarningsHistory:$T(H),getHealth:TT(H),getLiquidityPosition:tT({isThorchain:A,liquidityPositionGetter:P}),getLiquidityPositionRaw:P,getMembers:_T(H),getMimir:RT(H),getMimirVotes:FT(H),getNameDetails:XT(T),getNamesByAddress:ST(T),getNamesByOwner:ET(T),getNetworkInfo:HT(H),getNode:LT(H),getNodes:PT(H),getPool:aH(H),getPoolDepthHistory:AT(H),getPoolStats:NT(H),getPools:eH(H),getSaverDetails:YT(H),getSavers:gT(H),getSaversHistory:DT(H),getStats:BT(H),getSwapHistory:uT(H),getTVLHistory:OT(H)}}var gA=YA(EN.THORChain),DA=YA(EN.Maya);var fN={};cN(fN,{getTrackerDetails:()=>NP,getTokenListProviders:()=>LP,getTokenList:()=>FP,getTokenApproval:()=>PP,getSwapTo:()=>nP,getSwapQuote:()=>AP,getRouteWithTx:()=>HP,getPrice:()=>RP,getNearDepositChannel:()=>$P,getGasRate:()=>IP,getChainflipDepositChannel:()=>BP,getChainBalance:()=>TP,SKRequestClient:()=>V});import{EVMChains as pN}from"@swapkit/types";import{match as aT,P as GN}from"ts-pattern";async function UA(N,A,H,T){let P=`${A}:${H}:${T}`,I=new TextEncoder,B=await crypto.subtle.importKey("raw",I.encode(N),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),u=await crypto.subtle.sign("HMAC",B,I.encode(P));return Array.from(new Uint8Array(u)).map((G)=>G.toString(16).padStart(2,"0")).join("")}import{Chain as tN,ChainId as uN}from"@swapkit/types";import{array as E,boolean as K,coerce as tA,number as _,object as M,optional as O,string as F,union as KN,unknown as bA,z as L}from"zod";var xA;((T)=>{T.CHEAPEST="CHEAPEST";T.FASTEST="FASTEST";T.RECOMMENDED="RECOMMENDED"})(xA||={});var bN;((u)=>{u.PSBT="PSBT";u.EVM="EVM";u.COSMOS="COSMOS";u.RADIX="RADIX";u.NEAR="NEAR";u.TON="TON";u.TRON="TRON"})(bN||={});var wA;((z)=>{z.approve="approve";z.claim="claim";z.deposit="deposit";z.donate="donate";z.lending="lending";z.lp_action="lp_action";z.native_contract_call="native_contract_call";z.native_send="native_send";z.stake="stake";z.streaming_swap="streaming_swap";z.swap="swap";z.thorname_action="thorname_action";z.token_contract_call="token_contract_call";z.token_transfer="token_transfer";z.unknown="unknown";z.unstake="unstake"})(wA||={});var zA;((X)=>{X.swap="swap";X.aggregation="aggregation";X.addLiquidity="addLiquidity";X.withdrawLiquidity="withdrawLiquidity";X.addSavers="addSavers";X.withdrawSavers="withdrawSavers";X.borrow="borrow";X.repay="repay";X.name="name";X.donate="donate";X.claim="claim";X.stake="stake";X.unstake="unstake"})(zA||={});var QA;((u)=>{u.unknown="unknown";u.not_started="not_started";u.pending="pending";u.swapping="swapping";u.completed="completed";u.refunded="refunded";u.failed="failed"})(QA||={});var JA;((w)=>{w.not_started="not_started";w.starting="starting";w.broadcasted="broadcasted";w.mempool="mempool";w.inbound="inbound";w.outbound="outbound";w.swapping="swapping";w.completed="completed";w.refunded="refunded";w.partially_refunded="partially_refunded";w.dropped="dropped";w.reverted="reverted";w.replaced="replaced";w.retries_exceeded="retries_exceeded";w.parsing_error="parsing_error"})(JA||={});var hL=M({address:O(F()),chain:L.enum(tN).optional(),chainId:L.enum(uN),coingeckoId:O(F()),decimals:tA.number(),extensions:O(L.looseObject({})),identifier:F(),logoURI:O(F()),name:O(F()),shortCode:O(F()),symbol:O(F()),ticker:F()}),cL=L.object({block:L.optional(L.number().describe("Block number. Required for Polkadot chain. e.g. `123456`")),chainId:L.optional(L.string().describe("ChainId for the hash. e.g. `thorchain-1`")),depositChannelId:L.optional(L.string().describe("Deposit channel ID, required for Chainflip if tx was broadcasted without wallet connection")),hash:L.optional(L.string().describe("Hash for the first transaction broadcasted by the end user. e.g. `88D1819378ECD09E5284C54937CDC1E99B52F253C007617A02DD1200710CE677`"))}).refine((N)=>N.hash&&N.chainId||N.depositChannelId,{message:"Either `hash` and `chainId` or `depositChannelId` must be provided"}),lL=L.object({forceUpdate:L.string().toLowerCase().transform((N)=>N==="true").pipe(L.boolean()).optional()}),rL=M({error:F(),message:F()}),AN=M({address:O(F()),chain:L.enum(tN),decimal:O(_()),isGasAsset:K(),isSynthetic:K(),symbol:F(),tax:O(M({buy:_(),sell:_()})),ticker:F()}),ZA=M({id:F(),market_cap:_(),name:F(),price_change_24h_usd:_(),price_change_percentage_24h_usd:_(),sparkline_in_7d:E(_()),timestamp:F(),total_volume:_()}).partial(),iL=M({cg:O(ZA),identifier:F(),price_usd:_(),provider:F(),timestamp:_()}),WA=E(M({cg:O(ZA),identifier:F(),price_usd:_(),provider:F(),timestamp:_()}).partial()),sL=M({affiliate:O(F().describe("Affiliate thorname")),affiliateFee:O(_().describe("Affiliate fee in basis points").refine((N)=>N===Math.floor(N)&&N>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:O(K().describe("Allow smart contract as recipient")),allowSmartContractSender:O(K().describe("Allow smart contract as sender")),buyAsset:F().describe("Asset to buy"),cfBoost:O(K().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:O(F().describe("Address to send asset to")),disableSecurityChecks:O(K().describe("Disable security checks")),includeTx:O(K().describe("Set to true to include an transaction object (EVM only)")),providers:O(E(F().describe("List of providers to use").refine((N)=>J[N]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:O(F().describe("Referrer address (referral program)")),sellAmount:F().describe("Amount of asset to sell").refine((N)=>+N>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:F().describe("Asset to sell"),slippage:O(_().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:O(F().describe("Address to send asset from"))}).refine((N)=>N.sellAsset!==N.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),eL=M({metadata:K(),tokens:E(M({identifier:F()}))}),jA=M({destinationAddress:F()}),bT=jA.extend({affiliateFees:E(M({brokerAddress:F(),feeBps:_()})).optional(),brokerCommissionBps:_().optional(),buyAsset:M({asset:F(),chain:F()}),channelMetadata:M({cfParameters:F().optional(),gasBudget:F().optional(),message:F().optional()}).optional(),dcaParameters:M({chunkInterval:_().optional(),numberOfChunks:_().optional()}).optional(),maxBoostFeeBps:_().optional(),refundParameters:M({minPrice:F().optional(),refundAddress:F().optional(),retryDuration:_().optional()}).optional(),sellAsset:M({asset:F(),chain:F()})}),VA=M({channelId:F(),depositAddress:F()}),XA=jA.extend({affiliateFees:M({feeBps:_(),nearId:F()}).optional(),buyAsset:F(),sellAmount:F(),sellAsset:F(),slippage:tA.number(),sourceAddress:F()}),SA=M({amountIn:F(),amountInFormatted:F(),amountInUsd:F(),amountOut:F(),amountOutFormatted:F(),amountOutUsd:F(),deadline:F().optional(),minAmountIn:F(),minAmountOut:F(),timeEstimate:_().optional(),timeWhenInactive:F().optional()}),aL=SA.extend({depositAddress:F(),quote:SA,signature:F(),timestamp:F(),tx:bA()}),vA=M({buyAsset:F(),buyAssetAmount:F(),buyAssetAmountMaxSlippage:F(),deadline:F().optional(),depositAddress:F(),depositAmount:F(),depositAsset:F(),tx:bA()}),xT=M({evmCalldata:L.optional(L.string()),intentHash:L.optional(L.string()),logs:L.optional(L.unknown()),manifest:L.optional(L.unknown()),memo:L.optional(L.string()),spender:L.optional(L.string()),thorname:L.optional(L.string())}),wT=M({currentStage:F(),inboundConfirmation:_(),inboundObservation:_(),outboundDelay:_(),outboundObservation:_(),streamingSwap:_()}),zT=M({count:O(_()),interval:O(_()),quantity:O(_()),subSwapsMap:O(E(_()))}),QT=L.object({currentLegIndex:L.optional(L.number()),estimatedTimeToComplete:L.number(),estimates:L.optional(wT),providerDetails:L.optional(L.object({streamingDetails:L.optional(zT)}))}),JT=M({affiliate:O(AN),liquidity:O(AN),network:O(AN),protocol:O(AN),tax:O(AN)}),ZT=M({affiliate:F(),bps:F(),isReferrer:K()}),WT=M({affiliate:O(F()),affiliateFees:O(E(ZT)),broadcastedAt:O(_()),explorerUrl:O(F()),fees:O(JT),images:O(M({chain:O(F()),from:O(F()),provider:O(F()),to:O(F())})),provider:O(L.enum(J)),providerAction:L.optional(L.enum(zA)),quoteId:O(F()),wallet:O(F())}),HN=L.object({block:L.number(),chainId:L.enum(uN),finalAddress:L.optional(L.string()),finalAsset:L.optional(AN),finalisedAt:L.number(),fromAddress:L.string(),fromAmount:L.string(),fromAsset:L.string(),hash:L.string(),meta:L.optional(WT),payload:L.optional(xT),status:L.enum(QA),toAddress:L.string(),toAmount:L.string(),toAsset:L.string(),trackingStatus:L.optional(L.enum(JA)),transient:L.optional(QT),type:L.enum(wA)}),qA=HN.extend({legs:L.array(HN)}),NF=HN.extend({legs:E(HN)}),AF=HN.extend({legs:E(HN)}),mN=E(M({amount:F(),asset:F(),chain:F(),protocol:L.enum(J),type:L.enum(zN)})),yN=L.object({inbound:L.optional(L.number().describe("Time to receive inbound asset in seconds")),outbound:L.optional(L.number().describe("Time to receive outbound asset in seconds")),swap:L.optional(L.number().describe("Time to swap assets in seconds")),total:L.number().describe("Total time in seconds")}),jT=/^(?:0x[0-9a-fA-F]+|[0-9]+)$/;function VT(N){return N===""||jT.test(N)}function HF(N){return N?BigInt(N):0n}function TF(N){let A=typeof N==="bigint"?N:BigInt(N);return A>0n?`0x${A.toString(16)}`:"0x0"}var ON=F().refine(VT,{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"),kA=M({data:F().describe("Data to send"),from:F().describe("Address of the sender"),to:F().describe("Address of the recipient"),value:ON}),KA=L.object({data:L.string().optional(),raw_data:L.object({contract:L.any(),data:L.string().optional(),expiration:L.number(),fee_limit:L.number().optional(),ref_block_bytes:L.string(),ref_block_hash:L.string(),timestamp:L.number()}).passthrough(),raw_data_hex:L.string(),txID:L.string(),value:ON.optional(),visible:L.boolean()}),vT=E(KN([F(),_(),E(F()),M({from:F(),value:ON}).describe("Parameters to pass to the contract method")])),PF=M({approvalSpender:O(F().describe("Address of the spender to approve")),approvalToken:O(F().describe("Address of the token to approve spending of")),contractAddress:F().describe("Address of the contract to interact with"),contractMethod:F().describe("Name of the method to call"),contractParamNames:E(F().describe("Names of the parameters to pass to the contract method")),contractParams:vT}),qT=M({typeUrl:F("/types.MsgDeposit"),value:M({coins:E(M({amount:F(),asset:M({chain:F(),symbol:F(),synth:K(),ticker:F()})})),memo:F(),signer:F()})}),kT=M({typeUrl:F("/types.MsgSend"),value:M({amount:E(M({amount:F(),denom:F()})),fromAddress:F(),toAddress:F()})}),KT=M({typeUrl:F(),value:kT.shape.value.or(qT.shape.value)}),mT=M({amount:E(M({amount:F(),denom:F()})),gas:F()}),mA=M({accountNumber:_(),chainId:L.enum(uN),fee:mT,memo:F(),msgs:E(KT),sequence:_()}),yT=L.array(L.object({calldata:L.array(L.string()),contractAddress:L.string(),entrypoint:L.string()})),pT=L.object({address:L.string().describe("Destination address in friendly format"),amount:L.string().describe("Amount in nanotons"),payload:L.string().optional().describe("Base64 BOC of body cell"),stateInit:L.string().optional().describe("Base64 BOC of state init")}),yA=L.object({messages:L.array(pT),sendMode:L.number().describe("TON wallet send mode for the whole transfer")}),fT=M({affiliate:F().describe("Affiliate address").optional(),affiliateFee:_().describe("Affiliate fee").optional(),buyAsset:F().describe("Asset to buy"),destinationAddress:F().describe("Destination address"),estimatedTime:yN.optional(),provider:L.enum(J),sellAsset:F().describe("Asset to sell"),slipPercentage:_().describe("Slippage as a percentage"),sourceAddress:F().describe("Source address")}),LF=fT.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),oT=M({asset:F().describe("Asset name"),image:F().describe("Asset image"),price:_().describe("Price in USD")}),CT=bT,pA=M({assets:O(E(oT)),maxStreamingQuantity:_().optional(),referrer:F().optional(),streamingInterval:_().optional(),tags:E(L.enum(xA))}),fA=pA.extend({affiliate:O(F()),affiliateFee:O(F()),approvalAddress:O(F().describe("Approval address for swap")),chainflip:CT.optional(),garden:XA.optional(),near:XA.optional(),priceImpact:O(_().describe("Price impact")),referrer:O(F()),txType:O(L.enum(bN))}),oA=E(M({code:L.enum(wN),display:F(),tooltip:F().optional()})),dT=M({buyAmount:F().describe("Buy amount"),buyAmountMaxSlippage:F().describe("Buy amount max slippage"),buyAsset:F().describe("Asset to buy"),fees:O(mN),provider:L.enum(J),sellAmount:F().describe("Sell amount"),sellAsset:F().describe("Asset to sell")}),hT=M({buyAsset:F().describe("Asset to buy"),destinationAddress:O(F().describe("Destination address")),estimatedTime:O(yN),expectedBuyAmount:F().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:F().describe("Expected Buy amount max slippage"),expiration:O(F().describe("Expiration")),fees:mN,inboundAddress:O(F().describe("Inbound address")),legs:E(dT),memo:O(F().describe("Memo")),meta:fA,providers:E(L.enum(J)),routeId:F().describe("Route ID"),sellAmount:F().describe("Sell amount"),sellAsset:F().describe("Asset to sell"),sourceAddress:O(F().describe("Source address")),targetAddress:O(F().describe("Target address")),totalSlippageBps:_().describe("Total slippage in bps"),tx:O(KN([kA,mA,KA,yT,yA,F()])),txType:O(L.enum(bN)),warnings:oA}),CA=M({error:O(F().describe("Error message")),providerErrors:O(E(M({errorCode:O(L.enum(FN)),message:O(F()),provider:L.enum(J).optional()}))),quoteId:F().describe("Quote ID"),routes:E(hT)}),dA=L.object({chainId:L.enum(uN),createdAt:L.date(),id:L.number(),unit:L.string(),value:L.string()}),cT=L.array(dA),hA=L.union([dA,cT]),FF=E(M({chain:L.enum(tN),decimal:_(),identifier:F(),symbol:F(),ticker:F(),value:F()})),RF=L.union([L.object({amount:L.string(),spender:L.string(),tokenIdentifier:L.string(),userWalletAddress:L.string()}),L.object({amount:L.string(),chainId:L.enum(uN),spender:L.string(),tokenContractAddress:L.string(),userWalletAddress:L.string()}),L.object({routeId:L.string()})]),IF=L.object({approvalTransaction:L.optional(L.object({data:L.string(),from:L.string(),gasLimit:L.optional(L.string()),gasPrice:L.optional(L.string()),to:L.string(),value:ON})),approvedAmount:L.string(),isApproved:L.boolean()}),lT=L.object({data:L.string().describe("Encoded approval call data"),from:L.string().describe("User wallet address"),gasLimit:L.string().optional().describe("Estimated gas limit"),gasPrice:L.string().optional().describe("Current gas price"),to:L.string().describe("Token contract address"),value:ON.describe("ETH value (always '0' for approvals)")}),EA=L.object({buyAmount:L.string().describe("Buy amount").optional(),buyAmountMaxSlippage:L.string().describe("Buy amount max slippage").optional(),buyAsset:L.string().describe("Asset to buy"),expectedBuyAmount:L.string().describe("Expected Buy amount").optional(),expectedBuyAmountMaxSlippage:L.string().describe("Expected Buy amount max slippage").optional(),fees:mN,provider:L.enum(J),sellAmount:L.string().describe("Sell amount"),sellAsset:L.string().describe("Asset to sell")}),cA=EA.extend({estimatedTime:L.optional(yN),expiration:L.optional(L.string().describe("Expiration")),legs:L.array(EA),providers:L.array(L.enum(J)),routeId:L.string().describe("Route ID"),totalSlippageBps:L.number().describe("Total slippage in bps"),warnings:oA}).omit({provider:!0}),rT=L.object({method:L.string(),payload:L.optional(L.unknown()),url:L.string()}),iT=cA.extend({meta:pA,nextActions:L.optional(L.array(rT))}),BF=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(L.object({errorCode:L.optional(L.enum(FN)),message:L.optional(L.string()),provider:L.enum(J).optional()}))),quoteId:L.string().describe("Quote ID"),routes:L.array(iT)}),$F=L.object({providers:L.array(L.enum(J)).optional().describe("Optional list of providers to query for trading pairs"),sellAsset:L.string().describe("Asset identifier to sell (e.g., 'BTC.BTC' or 'ETH.ETH')")}),sT=L.object({chain:L.enum(tN).describe("Chain the asset is on"),identifier:L.string().describe("Asset identifier (e.g., 'ETH.USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')"),providers:L.array(L.enum(J)).describe("Providers that support this trading pair"),symbol:L.string().describe("Asset symbol"),ticker:L.string().describe("Asset ticker")}),uF=L.object({buyAssets:L.array(sT).describe("List of assets that can be swapped to"),sellAsset:L.string().describe("The input sell asset identifier")}),lA=cA.extend({destinationAddress:L.string().describe("Destination address"),inboundAddress:L.optional(L.string().describe("Inbound address")),memo:L.optional(L.string().describe("Memo to include in the transaction")),meta:fA,sourceAddress:L.string().describe("Source address"),targetAddress:L.optional(L.string().describe("Target address")),tx:O(KN([kA,mA,KA,yA,F()])),txType:L.optional(L.enum(bN))}),eT=L.object({data:L.optional(L.record(L.string(),L.string().optional())),errorCode:L.enum(FN),message:L.string().optional(),provider:L.enum(J).optional()}),OF=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(eT)),quoteId:L.string().describe("Quote ID"),routes:L.array(lA)}),rA=lA.extend({approvalTx:lT.optional().describe("Optional approval transaction if ERC-20 approval is required before swap"),swapId:L.string().describe("The unique swap ID for tracking")});var V=n.extend({dynamicHeader:async()=>{let N=S.get("widgetId"),A=S.get("widgetKey");if(N&&A&&typeof window<"u"){let T=Math.floor(Date.now()/1000),P=window.location.origin,I=await UA(A,N,P,T);return{Origin:P,"X-Signature":I,"X-Timestamp":T.toString(),"x-widget-id":N}}let{swapKit:H}=S.get("apiKeys");return H?{"x-api-key":H}:{}}});async function NP(N){let A=await V.post(j("/track"),{json:N});try{let H=qA.safeParse(A);if(!H.success)throw new Y("api_v2_invalid_response",H.error);return H.data}catch(H){return A}}async function AP(N){let{getQuote:A}=S.get("endpoints");if(A)return A(N);let T=S.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",P=await V.post(j(T),{json:N});if(P.error)throw new Y("api_v2_server_error",{message:P.error});try{let I=CA.safeParse(P);if(!I.success)throw new Y("api_v2_invalid_response",I.error);return I.data}catch{return P}}async function HP(N){let{getRouteWithTx:A}=S.get("endpoints");if(A)return A(N);let T=S.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",P=await V.post(j(T),{json:N});try{let I=rA.safeParse(P);if(!I.success)throw new Y("api_v2_invalid_response",I.error);return I.data}catch(I){return console.error(new Y("api_v2_invalid_response",I)),P}}async function TP({chain:N,address:A,scamFilter:H=!0}){let{getBalance:T}=S.get("endpoints");if(T)return T({address:A,chain:N});let P=j(`/balance?chain=${N}&address=${A}`),I=await V.get(P),B=Array.isArray(I)?I:[];return H?MP(B):B}function PP(N){let A=aT(N).with({routeId:GN.string,spender:GN.string},({routeId:H,spender:T})=>j(`/approve?routeId=${H}&sourceAddress=${T}`)).with({assetValue:GN.instanceOf(W),spender:GN.string,userWallet:GN.string},({spender:H,userWallet:T,assetValue:P})=>j(`/approve?tokenIdentifier=${P.toString()}&userWalletAddress=${T}&spender=${H}&amount=${P.getValue("string")}`)).exhaustive();return V.get(A)}function LP(){let N=j("/providers");return V.get(N)}function FP(N){let A=j(`/tokens?provider=${N}`);return V.get(A)}async function RP(N){let A=j("/price"),H=await V.post(A,{json:N});try{let T=WA.safeParse(H);if(!T.success)throw new Y("api_v2_invalid_response",T.error);return T.data}catch(T){throw new Y("api_v2_invalid_response",T)}}async function IP(){let N=j("/gas"),A=await V.get(N);try{let H=hA.safeParse(A);if(!H.success)throw new Y("api_v2_invalid_response",H.error);return Array.isArray(H)?H:[H]}catch(H){throw new Y("api_v2_invalid_response",H)}}async function BP(N){let{destinationAddress:A}=N;if(!A)throw new Y("chainflip_broker_invalid_params");let H=S.get("integrations").chainflip?.brokerUrl||j("/chainflip/broker/channel"),T=await V.post(H,{json:N});try{let P=VA.safeParse(T);if(!P.success)throw new Y("api_v2_invalid_response",P.error);return P.data}catch(P){throw new Y("api_v2_invalid_response",P)}}async function $P(N){let{destinationAddress:A}=N;if(!A)throw new Y("chainflip_broker_invalid_params");let H=j("/near/channel"),T=await V.post(H,{json:N});try{let P=vA.safeParse(T);if(!P.success)throw new Y("api_v2_invalid_response",P.error);return P.data}catch(P){throw new Y("api_v2_invalid_response",P)}}function j(N){let{isDev:A,apiUrl:H,devApiUrl:T}=S.get("envs"),{enabled:P,quoteUrl:I,swapUrl:B}=S.get("localMode");if(P&&N){let[G]=N.split("?");if(G==="/quote"||G==="/v3/quote")return`${I}${N}`;if(G==="/swap"||G==="/v3/swap")return`${B}${N}`}return`${A?T:H}${N}`}function uP(N){try{return W.from({asset:N.identifier})}catch{return}}var OP=new Set(["OP.OP"]),GP=/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/im;function MP(N){return N.filter((A)=>{let H=uP(A);if(!H)return!1;if(OP.has(H.toString().toUpperCase()))return!0;return(!pN.includes(H.chain)||H.isGasAsset||!!H.address)&&!GP.test(H.ticker)})}async function nP(N){let{getSwapTo:A}=S.get("endpoints");if(A)return A(N);let H=new URLSearchParams({sellAsset:N.sellAsset});if(N.providers?.length)for(let B of N.providers)H.append("providers",B);let T=j(`/swapTo?${H.toString()}`),P=await V.get(T);if(!Array.isArray(P))return{buyAssets:[],sellAsset:N.sellAsset};let I=[];for(let B of P)try{let u=W.from({asset:B});I.push({chain:u.chain,identifier:u.toString(),providers:[],symbol:u.symbol,ticker:u.ticker})}catch{}return{buyAssets:I,sellAsset:N.sellAsset}}var oN={};cN(oN,{getThorchainQueue:()=>DP,getTcyStakers:()=>wP,getTcyStaker:()=>xP,getTcyClaimers:()=>QP,getTcyClaimer:()=>zP,getTNSPreferredAsset:()=>EP,getTHORNodeTNSDetails:()=>iA,getRunePoolProviderInfo:()=>bP,getRunePoolInfo:()=>tP,getNodes:()=>UP,getMimirInfo:()=>XP,getLastBlock:()=>gP,getInboundAddresses:()=>SP});import{match as _P}from"ts-pattern";function q(N){let{isStagenet:A}=S.get("envs"),H=S.get("thornodeUrls");return`${_P({isStagenet:A,type:N}).with({type:"mayachain"},({isStagenet:P})=>P?H.MAYA_STAGENET:H.MAYA).otherwise(({isStagenet:P})=>P?H.THOR_STAGENET:H.THOR)}/${N??"thorchain"}`}function YP(N){let A=N==="mayachain"?"mayaname":"thorname";return`${q(N)}/${A}`}function gP(N="thorchain"){return n.get(`${q(N)}/lastblock`)}function DP(N){return n.get(`${q(N)}/queue`)}function UP(N){return n.get(`${q(N)}/nodes`)}function XP(N){return n.get(`${q(N)}/mimir`)}function SP(N){return n.get(`${q(N)}/inbound_addresses`)}async function iA({type:N,name:A}){try{return await n.get(`${YP(N)}/${A}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:A,owner:"",preferred_asset:""}}}async function EP({type:N,tns:A}){let H=await iA({name:A,type:N});if(!H.preferred_asset||H.preferred_asset===".")return;return W.from({asset:H.preferred_asset,asyncTokenLookup:!0})}function tP(N){return n.get(`${q(N)}/runepool`)}function bP({type:N,thorAddress:A}){return n.get(`${q(N)}/rune_provider/${A}`)}function xP({type:N,address:A}){return n.get(`${q(N)}/tcy_staker/${A}`)}function wP(N){return n.get(`${q(N)}/tcy_stakers`)}function zP({type:N,address:A}){return n.get(`${q(N)}/tcy_claimer/${A}`)}function QP(N){return n.get(`${q(N)}/tcy_claimers`)}var wF={...fN,mayachainMidgard:DA,thorchainMidgard:gA,thornode:oN};
5
+ export{WP as a,FN as b,wN as c,J as d,zN as e,TH as f,PH as g,LH as h,QN as i,FH as j,Z as k,S as l,Y as m,n,aP as o,NL as p,AL as q,HL as r,l as s,WN as t,xH as u,r as v,BL as w,nL as x,RA as y,IA as z,gN as A,jN as B,o as C,IN as D,_L as E,YL as F,$A as G,XL as H,d as I,y as J,W as K,jL as L,SN as M,UA as N,xA as O,bN as P,wA as Q,zA as R,QA as S,JA as T,hL as U,cL as V,lL as W,rL as X,AN as Y,ZA as Z,iL as _,WA as $,sL as aa,eL as ba,jA as ca,bT as da,VA as ea,XA as fa,aL as ga,vA as ha,qA as ia,NF as ja,AF as ka,mN as la,yN as ma,VT as na,HF as oa,TF as pa,kA as qa,KA as ra,vT as sa,PF as ta,mA as ua,yT as va,pT as wa,yA as xa,fT as ya,LF as za,oT as Aa,CT as Ba,pA as Ca,fA as Da,oA as Ea,hT as Fa,CA as Ga,dA as Ha,hA as Ia,RF as Ja,IF as Ka,lT as La,BF as Ma,$F as Na,sT as Oa,uF as Pa,lA as Qa,eT as Ra,OF as Sa,rA as Ta,wF as Ua};