@swapkit/helpers 4.13.3 → 4.13.5

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.
@@ -1,5 +0,0 @@
1
- var rA=Object.defineProperty;var iA=(N)=>N;function sA(N,A){this[N]=iA.bind(null,A)}var dN=(N,A)=>{for(var T in A)rA(N,T,{get:A[T],enumerable:!0,configurable:!0,set:sA.bind(A,T)})};var PN=((N)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(N,{get:(A,T)=>(typeof require<"u"?require:A)[T]}):N)(function(N){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+N+'" is not supported')});import{Chain as XN,getChainConfig as lT}from"@swapkit/types";import{AllChains as kT,Chain as E,EVMChains as KT,getChainConfig as IN}from"@swapkit/types";import{getAddress as IA}from"ethers";import{match as qN}from"ts-pattern";import{Chain as n,EVMChains as wT,getChainConfig as o,UTXOChains as QT}from"@swapkit/types";import{match as RN}from"ts-pattern";import{AllChains as lN,Chain as cN,getChainConfig as PT,MAYAConfig as LT,StagenetChain as gN,StagenetMAYAConfig as rN,StagenetTHORConfig as iN,THORConfig as RT}from"@swapkit/types";import{createStore as uT}from"zustand/vanilla";import{AllChains as eA,getChainConfig as aA}from"@swapkit/types";var xP=eA.reduce((N,A)=>{return N[A]=aA(A).networkDerivationPath,N},{});var LN;((u)=>{u.unknownError="unknownError";u.test_error="test_error";u.providerDetailsError="providerDetailsError";u.blockHeaderNotFound="blockHeaderNotFound";u.blockHashNotFoundAtHeight="blockHashNotFoundAtHeight";u.blockHashNotFoundAtHash="blockHashNotFoundAtHash";u.txHashMissing="txHashMissing";u.assetValueMissingInfo="assetValueMissingInfo";u.invalidAsset="invalidAsset";u.blockIsRequired="blockIsRequired";u.currentBlockHeaderNotFound="currentBlockHeaderNotFound";u.failedToRetrieveBalance="failedToRetrieveBalance";u.failedToRetrieveBlock="failedToRetrieveBlock";u.failedToRetrieveFees="failedToRetrieveFees";u.notImplementedBCH="notImplementedBCH";u.notImplementedDoge="notImplementedDoge";u.noPoolsFound="noPoolsFound";u.noVaultsFound="noVaultsFound";u.noTxFound="noTxFound";u.noInputCoinFound="noInputCoinFound";u.noBlockDataFound="noBlockDataFound";u.multipleCosmosMessages="multipleCosmosMessages";u.heightOrHashNotProvided="heightOrHashNotProvided";u.unknownDenom="unknownDenom";u.invalidBlockHeight="invalidBlockHeight";u.timestampExtrinsicNoArgumentsForBlock="timestampExtrinsicNoArgumentsForBlock";u.timestampExtrinsicNoTimestampForBlock="timestampExtrinsicNoTimestampForBlock";u.noTimestampExtrinsicForHash="noTimestampExtrinsicForHash";u.timestampExtrinsicNoArgumentsForHash="timestampExtrinsicNoArgumentsForHash";u.txMemoUndefined="txMemoUndefined";u.txMemoIncorrect="txMemoIncorrect";u.txTypeNotFound="txTypeNotFound";u.txNoMessage="txNoMessage";u.txNotFound="txNotFound";u.txReceiptNotFound="txReceiptNotFound";u.txParsingError="txParsingError";u.txLogsParsingError="txLogsParsingError";u.blockNotFound="blockNotFound";u.balanceNotFound="balanceNotFound";u.configError="configError";u.synthSwapDisallowed="synthSwapDisallowed";u.providerQuoteTimeout="providerQuoteTimeout";u.noQuoteResponse="noQuoteResponse";u.noPoolAssetsFound="noPoolAssetsFound";u.noThorchainPools="noThorchainPools";u.noMayachainPools="noMayachainPools";u.noThorchainNetworkInfo="noThorchainNetworkInfo";u.invalidAffiliateFee="invalidAffiliateFee";u.invalidBuyAssetAddress="invalidBuyAssetAddress";u.invalidSellAssetAddress="invalidSellAssetAddress";u.invalidSourceAddress="invalidSourceAddress";u.invalidDestinationAddress="invalidDestinationAddress";u.sourceAddressIsSmartContract="sourceAddressIsSmartContract";u.destinationAddressIsSmartContract="destinationAddressIsSmartContract";u.invalidChainId="invalidChainId";u.unsupportedChainId="unsupportedChainId";u.unsupportedEVMChainId="unsupportedEVMChainId";u.unsupportedMethod="unsupportedMethod";u.unsupportedProvider="unsupportedProvider";u.invalidParamsForMethod="invalidParamsForMethod";u.unsupportedAdapter="unsupportedAdapter";u.noWhitelistTokens="noWhitelistTokens";u.failedFetchGasPrice="failedFetchGasPrice";u.failedToCreateDepositChannel="failedToCreateDepositChannel";u.noProviderDetailsFound="noProviderDetailsFound";u.noTokenListsFound="noTokenListsFound";u.tokenNotFound="tokenNotFound";u.tokenPriceNotFound="tokenPriceNotFound";u.tokenPriceFailedToUpdate="tokenPriceFailedToUpdate";u.swapAmountTooSmall="swapAmountTooSmall";u.legsArrayIsEmpty="legsArrayIsEmpty";u.failedToFetchQuoteForLeg="failedToFetchQuoteForLeg";u.noBlockHeaderFound="noBlockHeaderFound";u.failedToSimulateSwap="failedToSimulateSwap";u.addressScreeningFailed="addressScreeningFailed";u.noLiquidtyProvidersFound="noLiquidtyProvidersFound";u.insufficientLiquidity="insufficientLiquidity";u.noInboundDataFound="noInbounDataFound";u.noInboundAddressesFound="noInboundAddressesFound";u.noInboundAddressFoundForChain="noInboundAddressFoundForChain";u.noLastBlocksFound="noLastBlocksFound";u.noVersionFound="noVersionFound";u.noConstantsFound="noConstantsFound";u.noMimirsFound="noMimirsFound";u.noRoutesFound="noRoutesFound";u.quoteNotFound="quoteNotFound";u.ledgerSignFailed="ledgerSignFailed";u.ledgerWrongPayload="ledgerWrongPayload";u.ledgerFetchSwapFailed="ledgerFetchSwapFailed";u.failedToFetchTx="failedToFetchTx";u.failedBuildTransactionDetails="failedBuildTransactionDetails";u.noLegsForRoute="noLegsForRoute";u.noRouterAddressFound="noRouterAddressFound";u.noAggregatorAddressFound="noAggregatorAddressFound";u.noContractInstanceFound="noContractInstanceFound";u.noContractAddressFound="noContractAddressFound";u.invalidAffiliate="invalidAffiliate";u.thornameAffiliate="thornameAffiliate";u.providerNotfound="No provider found";u.noRecordFound="No Record found";u.slippageTooLow="Slippage too low";u.tradingHalted="tradingHalted";u.noWrappedGasAsset="noWrappedGasAsset";u.aggregatorAddressNotFound="aggregatorAddressNotFound";u.routerAddressNotFound="routerAddressNotFound";u.dummyAddressNotFound="dummyAddressNotFound";u.trackerError="trackerError";u.thorchainPoolUnavailable="thorchainPoolUnavailable";u.noOhlcvDataFound="noOhlcvDataFound";u.noTradingPairs="noTradingPairs";u.noLendingAvailability="noLendingAvailability";u.lendingRepayTooSmall="lendingRepayTooSmall";u.missingState="missingState";u.ledgerSwapNotFound="ledgerSwapNotFound";u.ledgerSwapNotReadyForTracking="ledgerSwapNotReadyForTracking";u.errorEstimatingGas="errorEstimatingGas";u.apiKeyInvalid="apiKeyInvalid";u.apiKeyFailedToUpdate="apiKeyFailedToUpdate";u.apiKeyExpired="apiKeyExpired";u.unauthorized="unauthorized";u.failedToCreateMemo="failedToCreateMemo";u.radixIncorrectInstructions="radixIncorrectInstructions";u.radixTxMissedParam="radixTxMissedParam";u.radixTxMissedAccount="radixTxMissedAccount";u.radixManifestParseError="radixManifestParseError";u.radixManifestBuildError="radixManifestBuildError";u.invalidAddressForChain="invalidAddressForChain";u.riskyAddress="riskyAddress";u.noRoutesToProcess="noRoutesToProcess";u.sellAssetAmountTooSmall="sellAssetAmountTooSmall";u.missingPrivateKey="missingPrivateKey";u.noMemoPriceProtection="noMemoPriceProtection"})(LN||={});var xN;((T)=>{T.highSlippage="highSlippage";T.highPriceImpact="highPriceImpact"})(xN||={});var J;((S)=>{S.CHAINFLIP="CHAINFLIP";S.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";S.JUPITER="JUPITER";S.MAYACHAIN="MAYACHAIN";S.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";S.ONEINCH="ONEINCH";S.PANCAKESWAP="PANCAKESWAP";S.SUSHISWAP_V2="SUSHISWAP_V2";S.THORCHAIN="THORCHAIN";S.THORCHAIN_STREAMING="THORCHAIN_STREAMING";S.TRADERJOE_V2="TRADERJOE_V2";S.UNISWAP_V2="UNISWAP_V2";S.UNISWAP_V3="UNISWAP_V3";S.NEAR="NEAR";S.GARDEN="GARDEN";S.OKX="OKX";S.HARBOR="HARBOR";S.FLASHNET="FLASHNET"})(J||={});var bN;((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"})(bN||={});var NT;((H)=>{H.Average="average";H.Fast="fast";H.Fastest="fastest"})(NT||={});var AT;((T)=>{T.Approve="approve";T.CheckOnly="checkOnly"})(AT||={});var TT;((_)=>{_.NAME_REGISTER="~";_.BOND="BOND";_.DEPOSIT="+";_.LEAVE="LEAVE";_.UNBOND="UNBOND";_.WITHDRAW="-";_.RUNEPOOL_DEPOSIT="POOL+";_.RUNEPOOL_WITHDRAW="POOL-";_.CLAIM_TCY="tcy";_.STAKE_TCY="tcy+";_.UNSTAKE_TCY="tcy-"})(TT||={});var zN;((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.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"})(zN||={});var HT;((H)=>{H[H.NoError=36864]="NoError";H[H.LockedDevice=21781]="LockedDevice";H[H.TC_NotFound=65535]="TC_NotFound"})(HT||={});var FT=lN.reduce((N,A)=>{if(!N.THOR_STAGENET)N[gN.Maya]=rN.rpcUrls,N[gN.THORChain]=iN.rpcUrls;return N[A]=PT(A).rpcUrls,N},{}),IT={[cN.THORChain]:RT.nodeUrl,[cN.Maya]:LT.nodeUrl,[gN.THORChain]:iN.nodeUrl,[gN.Maya]:rN.nodeUrl},sN={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:lN,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"}}},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:FT,thornodeUrls:IT,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(zN),widgetKey:""},Z=uT((N)=>({...sN,setApiKey:(A,T)=>N((H)=>({apiKeys:{...H.apiKeys,[A]:T}})),setConfig:(A)=>N((T)=>({apiKeys:{...T.apiKeys,...A?.apiKeys},chains:T.chains.concat(A?.chains||[]),endpoints:{...T.endpoints,...A?.endpoints},envs:{...T.envs,...A?.envs},feeMultipliers:A?.feeMultipliers||T.feeMultipliers,integrations:{...T.integrations,...A?.integrations},rpcUrls:{...T.rpcUrls,...A?.rpcUrls},thornodeUrls:{...T.thornodeUrls,...A?.thornodeUrls},v3SwapFlow:{...T.v3SwapFlow,...A?.v3SwapFlow},wallets:T.wallets.concat(A?.wallets||[]),widgetKey:A?.widgetKey||T.widgetKey})),setEndpoint:(A,T)=>N((H)=>({endpoints:{...H.endpoints,[A]:T}})),setEnv:(A,T)=>N((H)=>({envs:{...H.envs,[A]:T}})),setFeeMultipliers:(A)=>N(()=>({feeMultipliers:A})),setIntegrationConfig:(A,T)=>N((H)=>({integrations:{...H.integrations,[A]:T}})),setRequestOptions:(A)=>N((T)=>({requestOptions:{retry:{...T.requestOptions.retry,...A.retry},timeoutMs:A.timeoutMs||T.requestOptions.timeoutMs}})),setRpcUrl:(A,T)=>N((H)=>({rpcUrls:{...H.rpcUrls,[A]:T}})),setThornodeUrl:(A,T)=>N((H)=>({thornodeUrls:{...H.thornodeUrls,[A]:T}})),setWidgetKey:(A)=>N({widgetKey:A})})),w={get:(N)=>Z.getState()[N],getState:Z.getState,reinitialize:()=>Z.setState(sN),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),setWidgetKey:(N)=>Z.getState().setWidgetKey(N)};var nT={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_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_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,T)=>typeof T==="bigint"?T.toString():T)}class t extends Error{static ErrorCode=nT;errorKey;info;constructor(N,A){let T=typeof N==="string",H=T?N:N.errorKey,P=T?void 0:N.info,I=`${H}${P?`: ${JN(P)}`:""}`;super(I);if(Object.setPrototypeOf(this,t.prototype),this.name="SwapKitError",this.errorKey=H,this.info=P,this.cause=A,A){let F=A instanceof Error?`${A.message}${A.cause?` (${A.cause})`:""}`:JN(A);console.error(`SwapKitError [${H}]: ${F}`)}else if(P)console.error(`SwapKitError [${H}]: ${JN(P)}`)}}var BT=(N)=>new Promise((A)=>setTimeout(A,N)),OT=(N,{baseDelay:A,backoffMultiplier:T,maxDelay:H})=>Math.min(A*T**N,H);function $T(N,A){if(N instanceof Error&&N.name==="AbortError")return!0;if(N instanceof TypeError)return!0;if(A===429)return!0;if(A&&A>=500&&A<600)return!0;return!1}var GT=async(N,A)=>{let T=await fetch(N,A),H;try{H=await T.json()}catch{if(!T.ok)throw new t({errorKey:"helpers_invalid_response",info:{status:T.status,statusText:T.statusText}},{status:T.status,statusText:T.statusText});return{}}if(!T.ok){let I={data:H?.data,error:H?.error,message:H?.message,status:T.status};throw new t({errorKey:H?.error||"helpers_invalid_response",info:I},I)}let P=H?.routes?.length||H?.result||H?.data&&!H?.error;if(H?.error&&!P){let I={data:H.data,error:H.error,message:H.message,status:T.status};throw new t({errorKey:H.error,info:I},I)}if(H?.providerErrors?.length||H?.error&&P)console.warn("[SwapKit] Partial errors in response:",H.providerErrors||H.error);return H};function MN(N,A={}){return async function(H,P={}){let{searchParams:I,json:F,body:O,headers:g,dynamicHeader:Y,retry:Q,timeoutMs:_,abortController:j,onError:U,onSuccess:k,responseHandler:x,...b}={...A,...P},TN=w.get("requestOptions"),S={...TN.retry,...Q},ON=!!F||H.endsWith(".json"),$N=MT(H,I),fN=Y?await Y():{},HN=gT(ON,{...g,...fN}),d=ON?JSON.stringify(F):O,QN;for(let GN=0;GN<=S.maxRetries;GN++){let CN=j||new AbortController,hN=setTimeout(()=>CN.abort(),_||TN.timeoutMs);try{let m=await GT($N,{...b,body:d,headers:HN,method:N,signal:CN.signal});return clearTimeout(hN),k?.(m)||x?.(m)||m}catch(m){clearTimeout(hN),QN=m;let lA=m?.cause?.status;if(GN>=S.maxRetries||!$T(m,lA))return U?U(m):Promise.reject(m);await BT(OT(GN,S))}}return U?U(QN):Promise.reject(QN)}}function gT(N,A){return{...A,...N&&{"Content-Type":"application/json"}}}function MT(N,A){let T=new URL(N);if(A)T.search=new URLSearchParams(A).toString();return T.toString()}var G={extend:(N)=>({extend:(A)=>G.extend({...N,...A}),get:MN("GET",N),post:MN("POST",N)}),get:MN("GET"),post:MN("POST")};import{Chain as z,CosmosChains as tT,EVMChains as _T,StagenetChains as DT,UTXOChains as YT}from"@swapkit/types";import{match as NA}from"ts-pattern";import{Chain as ZN}from"@swapkit/types";function lP(N){if(N<0)throw new t({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:N}});return 10+N}function rP(N){if(N<0)throw new t({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:N}});return Math.round((10+N*1.0512)*10000000000)/10000000000}function iP(N,A){try{return N()}catch(T){if(A)throw new t(A,T);return}}function sP(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 eN=new Set;function c({condition:N,id:A,warning:T}){if(N){if(eN.has(A))return;console.warn(T),eN.add(A)}}function UT(N){return NA(N).with(..._T,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...YT,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...tT,...DT,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(z.Polkadot,z.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(z.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(z.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(z.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(z.Aptos,z.Tron,z.Radix,z.Stellar,()=>"").with(z.HyperCore,()=>({type:"meta"})).with(z.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(z.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(z.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new t("helpers_chain_not_supported",{chain:N})})}function ST(N){return NA(N).with(z.Aptos,()=>"/-/healthy").with(z.HyperCore,()=>"/info").with(z.Radix,()=>"/status/network-configuration").with(z.Stellar,()=>"").with(z.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function aN(N,A){try{let T=A.startsWith("wss")?A.replace("wss","https"):A;return(await fetch(`${T}${ST(N)}`,{body:JSON.stringify(UT(N)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var VN=new Map,XT=120000;function ET(N){let[A=""]=w.get("rpcUrls")[N];if(!A)throw c({condition:!0,id:"helpers_chain_no_public_or_set_rpc_url",warning:`No public or set RPC URL found for chain. Please ensure you configured rpcUrls for ${N}.`}),new t("helpers_chain_no_public_or_set_rpc_url",{chain:N});let T=VN.get(N);if(T&&Date.now()-T.timestamp<XT)return T.url;return VN.set(N,{timestamp:Date.now(),url:A}),A}async function l(N){let A=ET(N),[,...T]=w.get("rpcUrls")[N];if(await aN(N,A))return A;for(let P of T)if(await aN(N,P))return VN.set(N,{timestamp:Date.now(),url:P}),P;throw new t("helpers_chain_rpc_connection_failed",{chain:N,fallbackUrls:T,primaryRpcUrl:A})}function PL(N){c({condition:!0,id:"initializeRPCUrlsWithFallback",warning:"initializeRPCUrlsWithFallback is deprecated. Use static { rpcUrls, fallbackRpcUrls } SwapKit init config or dynamic SKConfig.setRpcUrl/setFallbackRpcUrl to configure RPC endpoints."})}var nL=[`${n.Maya}.MAYA`,`${n.Maya}.CACAO`,`${n.Ethereum}.THOR`,`${n.Ethereum}.vTHOR`,`${n.Kujira}.USK`,`${n.Ethereum}.FLIP`,`${n.Radix}.XRD`],HA=[n.Arbitrum,n.Aurora,n.Base,n.Ethereum,n.Optimism];async function xT(N){let{baseDecimal:A}=o(n.Radix);try{let T=await l(n.Radix),{manager:H}=await G.post(`${T}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:N}),headers:{Accept:"*/*","Content-Type":"application/json"}});return H?.divisibility?.value?.divisibility}catch(T){let H=T instanceof Error?T.message:String(T);return console.warn(`Failed to fetch Radix asset decimals for ${N}: ${H}`),A}}async function bT(N){try{let A=await l(n.Radix);return(await G.post(`${A}/state/entity/details`,{body:JSON.stringify({addresses:[N],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((P)=>P.key==="symbol")?.value.typed.value||void 0}catch(A){let T=A instanceof Error?A.message:String(A);return console.warn(`Failed to fetch Radix asset symbol for ${N}: ${T}`),""}}async function PA({chain:N,address:A,methodHex:T,id:H}){let P=await l(N);return G.post(P,{body:JSON.stringify({id:H,jsonrpc:"2.0",method:"eth_call",params:[{data:T,to:A.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}async function zT(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 JT(N,A){if(!N||N==="0x")return A;try{return Number(N)}catch(T){return console.warn(`Failed to decode ABI uint8 from ${N}: ${T}`),A}}async function ZT({chain:N,address:A}){let{baseDecimal:T}=o(N),H=A.toLowerCase();if(A===""||!H.startsWith("0x"))return T;let P=await PA({address:A,chain:N,id:2,methodHex:"0x313ce567"}).catch((F)=>{return console.warn(`Could not fetch decimals for ${A} on ${N}: ${F.message}`),{result:""}});return JT(P.result,T)}async function VT({chain:N,address:A}){let T=A.toLowerCase();if(T===""||!T.startsWith("0x"))return;let H=await PA({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 zT(H.result)}async function AA({rpcUrl:N,contractAddress:A,functionSelector:T}){return(await G.post(`${N}/wallet/triggerconstantcontract`,{body:JSON.stringify({contract_address:A,function_selector:T,owner_address:A,parameter:"",visible:!0}),headers:{accept:"application/json","content-type":"application/json"}}).catch(()=>{return}))?.constant_result?.[0]}function TA(N){let A=N.match(/.{2}/g)?.map((T)=>Number.parseInt(T,16))??[];return new TextDecoder().decode(new Uint8Array(A))}function WT(N){return RN(N).with(void 0,()=>{return}).when((A)=>A.length>=128,(A)=>{let T=Number.parseInt(A.slice(64,128),16);return TA(A.slice(128,128+T*2))}).when((A)=>A.length===64,(A)=>{let T=A.replace(/0+$/,"");if(T.length>0&&T.length%2===0)return TA(T);return}).otherwise(()=>{return})}function LA({chain:N,address:A}){let{baseDecimal:T}=o(N),H={decimals:T,ticker:void 0};return RN(N).with(...wT,async()=>{try{let{isAddress:P,getAddress:I}=await import("ethers");if(!P(I(A.replace(/^0X/,"0x"))))return H;let[F,O]=await Promise.all([VT({address:A,chain:N}),ZT({address:A,chain:N})]);return{decimals:O,ticker:F}}catch(P){return console.warn(`Failed to fetch token info for ${A} on ${N}: ${P?.code} ${P?.message}`),H}}).with(n.Solana,async()=>{if(!A)return H;try{let P=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${A}`);if(P.ok){let I=await P.json(),F=Array.isArray(I)?I[0]:I;if(F)return{decimals:F.decimals??T,ticker:F.symbol||void 0}}}catch(P){console.warn(`Failed to fetch Solana token info for ${A}: ${P?.code} ${P?.message}`)}return H}).with(n.Tron,async()=>{if(!A)return H;try{let P=await l(n.Tron),[I,F]=await Promise.all([AA({contractAddress:A,functionSelector:"symbol()",rpcUrl:P}),AA({contractAddress:A,functionSelector:"decimals()",rpcUrl:P})]),O=WT(I);return{decimals:I!==void 0&&F?Number(BigInt(`0x${F}`)):T,ticker:O}}catch(P){let I=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Tron token info for ${A}: ${I}`),H}}).with(n.Near,async()=>{if(!A)return H;try{let{JsonRpcProvider:P}=await import("@near-js/providers"),I=await l(n.Near),O=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(O.result).toString());return{decimals:g?.decimals||T,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}`),H}}).with(n.Radix,async()=>{if(!A)return H;try{let[P,I]=await Promise.all([bT(A),xT(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}`),H}}).otherwise(async()=>H)}function tN({chain:N,symbol:A}){return RN(N).with(...HA,()=>A==="ETH").with(n.Avalanche,()=>A==="AVAX").with(n.Berachain,()=>A==="BERA").with(n.Hyperevm,()=>A==="HYPE").with(n.HyperCore,()=>A==="HYPE").with(n.BinanceSmartChain,()=>A==="BNB").with(n.Gnosis,()=>A==="xDAI"||A==="XDAI").with(n.Monad,()=>A==="MON").with(n.XLayer,()=>A==="OKB").with(n.Maya,()=>A==="CACAO").with(n.Cosmos,()=>A==="ATOM").with(n.THORChain,()=>A==="RUNE").with(n.Tron,()=>A==="TRX").with(n.Ripple,()=>A==="XRP").with(n.Radix,()=>`${N}.${A}`===_N(N).identifier).otherwise(()=>A===N)}var _N=(N)=>{let{baseDecimal:A}=o(N);return RN(N.toUpperCase()).with(...HA,(H)=>({decimal:A,identifier:`${H}.ETH`})).with(n.THORChain,(H)=>({decimal:A,identifier:`${H}.RUNE`})).with(n.Cosmos,(H)=>({decimal:A,identifier:`${H}.ATOM`})).with(n.Maya,(H)=>({decimal:10,identifier:`${H}.CACAO`})).with(n.BinanceSmartChain,(H)=>({decimal:A,identifier:`${H}.BNB`})).with(n.Monad,(H)=>({decimal:A,identifier:`${H}.MON`})).with(n.Avalanche,(H)=>({decimal:A,identifier:`${H}.AVAX`})).with(n.Gnosis,(H)=>({decimal:A,identifier:`${H}.xDAI`})).with(n.XLayer,(H)=>({decimal:A,identifier:`${H}.OKB`})).with(n.Berachain,(H)=>({decimal:A,identifier:`${H}.BERA`})).with(n.Hyperevm,(H)=>({decimal:A,identifier:`${H}.HYPE`})).with(n.HyperCore,(H)=>({decimal:A,identifier:`${H}.HYPE`})).with(n.Tron,(H)=>({decimal:A,identifier:`${H}.TRX`})).with(n.Solana,n.Chainflip,n.Kujira,n.Ripple,n.Polkadot,n.Near,...QT,(H)=>({decimal:A,identifier:`${H}.${H}`})).with(n.Radix,"XRD.XRD",()=>({decimal:A,identifier:"XRD.XRD"})).with(n.Polygon,"POL.POL",()=>({decimal:A,identifier:"POL.POL"})).with("KUJI.USK",(H)=>({decimal:6,identifier:H})).with("ETH.FLIP",()=>({decimal:o(n.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:o(n.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:o(n.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(H)=>({decimal:10,identifier:H})).with("MAYA.MAYA",(H)=>({decimal:4,identifier:H})).otherwise(()=>({decimal:A,identifier:N}))};function WN({chain:N,symbol:A}){if(A.includes("/"))return"Synth";if(A.includes("~"))return"Trade";return RN(N).with(n.Radix,()=>A===n.Radix||`${N}.${A}`===_N(N).identifier).with(n.Arbitrum,n.Optimism,n.Base,n.Aurora,()=>A===n.Ethereum).with(n.Cosmos,()=>A==="ATOM").with(n.BinanceSmartChain,()=>A==="BNB").with(n.Maya,()=>A==="CACAO").with(n.Monad,()=>A==="MON").with(n.THORChain,()=>A==="RUNE").with(n.Tron,()=>A==="TRX").with(n.Hyperevm,()=>A==="HYPE").with(n.HyperCore,()=>A==="HYPE").with(n.XLayer,()=>A==="OKB").otherwise(()=>A===N)?"Native":N}var f=(N)=>{let[A,...T]=N.split("."),H=N.includes("/"),P=T.join("."),I=P?.split("-"),F=I?.length?I.length===1?I[0]:I.slice(0,-1).join("-"):void 0;return{chain:A,symbol:P,synth:H,ticker:F}};function uN(N,A){let H=A===n.Near?N.indexOf("-"):N.lastIndexOf("-");if(H===-1)return{address:void 0,ticker:N};return{address:N.slice(H+1),ticker:N.slice(0,H)}}function BL(N){return`https://storage.googleapis.com/token-list-swapkit-dev/images/${N.toLowerCase()}.png`}async function OL(N){let{loadTokenLists:A}=await import("./tokens.js"),T=await A(),H=Object.values(T).flatMap((I)=>I.tokens);if("identifier"in N)return H.find((I)=>I.identifier===N.identifier)?.identifier;let P=N.contract.toLowerCase();for(let I of H){let{chain:F,symbol:O}=f(I.identifier);if(F!==N.chain)continue;let{address:g}=uN(O,F);if(g?.toLowerCase()===P)return I.identifier}return}var RA=["TERRA",...w.get("chains")];function uA(N=""){let A=N.toUpperCase(),[T]=A.split(".");if(RA.includes(T))return!0;let[H]=A.split("/");if(RA.includes(H))return!0;throw new t({errorKey:"helpers_invalid_identifier",info:{identifier:N,message:`Invalid identifier: ${N}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}function ML(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 r=8,jT=10;function h({value:N,bigIntDecimal:A=r,decimal:T=r}){if(T===0)return N.toString();let H=N<0n,P=N.toString().substring(H?1:0),I=T-(P.length-1);if(I>0)P="0".repeat(I)+P;let F=P.length-T,O=P.slice(-T);if(Number.parseInt(O[A]||"0",10)>=5){let Y=Number.parseInt(O[A-1]||"0",10);O=`${O.substring(0,A-1)}${Y+1}`}else O=O.substring(0,A);return`${H?"-":""}${P.slice(0,F)}.${O}`.replace(/\.?0*$/,"")}class p{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(N,A){return new p({decimal:A,value:h({bigIntDecimal:A,decimal:A,value:N})})}static shiftDecimals({value:N,from:A,to:T}){return p.fromBigInt(N.getBaseValue("bigint")*C(T)/C(A),T)}constructor(N){let A=jN(N),T=typeof N==="object";this.decimal=T?N.decimal:void 0,this.decimalMultiplier=T&&"decimalMultiplier"in N?N.decimalMultiplier:C(Math.max(FA(YN(A)),this.decimal||0)),this.#P(A)}set(N){return new this.constructor({decimal:this.decimal,identifier:this.toString?.({includeSynthProtocol:!0}),value:N})}add(...N){return this.#A("add",...N)}sub(...N){return this.#A("sub",...N)}mul(...N){return this.#A("mul",...N)}div(...N){return this.#A("div",...N)}gt(N){return this.#N("gt",N)}gte(N){return this.#N("gte",N)}lt(N){return this.#N("lt",N)}lte(N){return this.#N("lte",N)}eqValue(N){return this.#N("eqValue",N)}getValue(N,A){let T=FN(this.decimalMultiplier),H=A!==void 0?A:this.decimal,P=H!==void 0?H:T;if(H!==void 0&&H<T){if(this.formatBigIntToSafeValue(this.bigIntValue,H)==="0"&&this.bigIntValue!==0n)P=T}let 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 T=this.decimalMultiplier/C(A||this.decimal||r),H=qT(this.bigIntValue,T);return DN(N).with("number",()=>Number(H)).with("string",()=>H.toString()).otherwise(()=>H)}getBigIntValue(N,A){if(!A&&typeof N==="object")return N.bigIntValue;let T=jN(N),H=YN(T);if(H==="0"||H==="undefined")return 0n;return this.#H(H,A)}toSignificant(N=6){let A=this.getValue("string"),[T="",H=""]=A.split("."),P=Number.parseInt(T,10)>0;if((P?T.length+H.length:H.length)<=N)return A;if(T.length>=N)return T.slice(0,N).padEnd(T.length,"0");if(P)return`${T}.${H.slice(0,N-T.length)}`;let F=Number.parseInt(H,10).toString(),O=F.slice(0,N),g=H.length-F.length;return`0.${O.padStart(g+O.length,"0")}`}toFixed(N=6){let A=this.getValue("string"),T=A.startsWith("-"),[H="0",P=""]=(T?A.slice(1):A).split("."),I=H==="0"&&Number.parseInt(P.slice(0,N),10)===0,F=T&&!I?"-":"";if(N===0){if(H==="0"&&!P)return"0";return P&&Number.parseInt(P[0]||"0",10)>=5?`${F}${BigInt(H)+1n}.0`:`${F}${H}.0`}if(!P)return`${F}${H}.${"0".repeat(N)}`;let O=P[N];if(!(O&&Number.parseInt(O,10)>=5))return`${F}${H}.${P.slice(0,N).padEnd(N,"0")}`;let Y=BigInt(P.slice(0,N).padEnd(N,"0"))+1n,Q=10n**BigInt(N);if(Y>=Q)return`${F}${BigInt(H)+1n}.${"0".repeat(N)}`;return`${F}${H}.${Y.toString().padStart(N,"0")}`}toAbbreviation(N=2){let A=this.getValue("string"),T=Number(A),H=["","K","M","B","T","Q","Qi","S"],P=Math.floor(Math.log10(Math.abs(T))/3);if(P===0||!H[P])return A;return`${(T/10**(P*3)).toFixed(N)}${H[P]}`}toCurrency(N="$",{currencyPosition:A="start",decimal:T=2,decimalSeparator:H=".",thousandSeparator:P=",",trimTrailingZeros:I=!0}={}){let F=this.toFixed(T),O=A==="end",[g="0",Y=""]=F.split("."),Q=g.replace(/\B(?=(\d{3})+(?!\d))/g,P),_=Y&&Number.parseInt(Y,10)>0,j=_?`${Q}${H}${Y}`:Q,k=j.length<100&&I&&_?j.replace(/\.?0*$/,""):j;return O?`${k}${N}`:`${N}${k}`}formatBigIntToSafeValue(N,A){let T=A||this.decimal||r,H=Math.max(T,FN(this.decimalMultiplier));return h({bigIntDecimal:T,decimal:H,value:N})}#A(N,...A){let T=this.#T(this,...A),H=FN(this.decimalMultiplier),I=Math.max(T,H)+jT,F=C(I),O=A.reduce((Y,Q)=>{let _=this.getBigIntValue(Q,I);return DN(N).with("add",()=>Y+_).with("sub",()=>Y-_).with("mul",()=>Y*_/F).with("div",()=>{if(_===0n)throw RangeError("Division by zero");return Y*F/_}).otherwise(()=>Y)},this.bigIntValue*F/this.decimalMultiplier),g=h({bigIntDecimal:I,decimal:I,value:O});return new this.constructor({decimal:this.decimal,decimalMultiplier:C(I),identifier:this.toString(),value:g})}#N(N,...A){let T=this.#T(this,...A),H=this.getBigIntValue(A[0]||"0",T),P=this.getBigIntValue(this,T);return DN(N).with("gt",()=>P>H).with("gte",()=>P>=H).with("lt",()=>P<H).with("lte",()=>P<=H).with("eqValue",()=>P===H).otherwise(()=>!1)}#P(N){let A=YN(N)||"0";this.bigIntValue=this.#H(A)}#T(...N){let A=N.map((T)=>{return typeof T==="object"?T.decimal||FN(T.decimalMultiplier):FA(YN(T))}).filter(Boolean);return Math.max(...A,r)}#H(N,A){let T=A?C(A):this.decimalMultiplier,H=FN(T),[P="",I=""]=N.split(".");return BigInt(`${P}${I.padEnd(H,"0")}`)}}var vT=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function YN(N){let T=`${typeof N==="number"?vT.format(N):jN(N)}`.replaceAll(",",".").split(".");return T.length>1?`${T.slice(0,-1).join("")}.${T.at(-1)}`:T[0]||"0"}function FA(N){let A=N.split(".")[1]?.length||0;return Math.max(A,r)}function jN(N){return typeof N==="object"?"getValue"in N?N.getValue("string"):N.value:N}function qT(N,A){if(A===0n)throw Error("Cannot divide by zero");let T=A/2n;return N>=0n&&A>=0n||N<0n&&A<0n?(N+T)/A:(N-T)/A}function C(N){return 10n**BigInt(N)}function FN(N){return Math.log10(Number.parseFloat(N.toString()))}var y=[E.HyperCore,E.Near,E.Ripple,E.Solana,E.Sui,E.Ton,E.Tron],kN=[E.THORChain,E.Maya],i=new Map,UN=new Map,s=new Map,mT=3600000;function pT(N){let A=s.get(N);if(A?.timestamp&&Date.now()-A.timestamp>mT){s.delete(N);return}return A}function yT(N,A){if(s.size>1000){let T=s.keys().next().value;if(T)s.delete(T)}s.set(N,{...A,timestamp:Date.now()})}class v extends p{address;chain;isGasAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:N,decimal:A,tax:T,chain:H,symbol:P,identifier:I}){super(typeof N==="object"?N:{decimal:A,value:N});let F=nA(I||`${H}.${P}`);this.type=WN(F),this.tax=T,this.chain=F.chain,this.ticker=F.ticker,this.symbol=F.symbol,this.address=F.address,this.isSynthetic=F.isSynthetic,this.isTradeAsset=F.isTradeAsset,this.isGasAsset=F.isGasAsset,this.chainId=IN(F.chain).chainId}toString({includeSynthProtocol:N}={}){return(this.isSynthetic||this.isTradeAsset)&&!N?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){if(this.isSynthetic)return`${this.chain}.${this.symbol.replace(/\//g,".")}`;if(this.isTradeAsset)return`${this.chain}.${this.symbol.replace(/~/g,"..")}`;let N=this.symbol.replace(/\./g,"__");return`${this.chain}.${N}`}getIconUrl(){return i.get(this.toString())?.logoURI}eqAsset({chain:N,symbol:A}){return this.chain===N&&this.symbol===A}eq(N){return this.eqAsset(N)&&this.eqValue(N)}static fromUrl(N,A=0){let T=N.indexOf(".");if(T===-1)throw new t({errorKey:"helpers_invalid_asset_url",info:{urlAsset:N}});let H=N.slice(0,T),P=N.slice(T+1),I=qN({chain:H,rest:P}).when(({rest:F})=>F.includes(".."),({chain:F,rest:O})=>`${F}.${O.replace(/\.\./g,"~")}`).when(({chain:F,rest:O})=>kN.includes(F)&&O.includes("."),({chain:F,rest:O})=>`${F}.${O.replace(/\./g,"/")}`).otherwise(({chain:F,rest:O})=>`${F}.${O.replace(/__/g,".")}`);return v.from({asset:I,value:A})}static from({value:N=0,fromBaseDecimal:A,asyncTokenLookup:T,...H}){let P=N instanceof p?N.getValue("string"):N,I="address"in H&&"chain"in H,F=hT(H);if(F===null&&T&&I){let{chain:HN,address:d}=H;return fT({address:d,chain:HN,fromBaseDecimal:A,parsedValue:P})}let O=I&&!F?`${H.chain}.UNKNOWN-${H.address}`:F,{identifier:g,decimal:Y}=_N(O),{chain:Q,isSynthetic:_,isTradeAsset:j,address:U}=nA(g),{baseDecimal:k}=IN(Q),x=i.get(y.includes(Q)?g:g.toUpperCase());if(!x&&T&&!_&&!j)return(async()=>{let{ticker:HN}=f(g),d=await BA({address:U,chain:Q,ticker:HN});return vN({decimal:d.decimals,identifier:d.identifier,value:A?e(BigInt(P),A):P})})();let b=x?.decimal||Y;c({condition:!b&&!T,id:`assetValue_static_decimal_not_found_${Q}`,warning:`Couldn't find static decimal for one or more tokens on ${Q} (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:S,tax:ON}=x||{decimal:b||k,identifier:g},$N=A?e(BigInt(P),A):e(P,TN);return _||j?oT(S,$N):vN({decimal:TN,identifier:S,tax:ON,value:$N})}static async loadStaticAssets(N){let{loadTokenLists:A}=await import("@swapkit/tokens"),T=await A(N);for(let{tokens:H}of Object.values(T))for(let P of H){let{identifier:I}=P,{chain:F,symbol:O}=f(I),{address:g}=uN(O,F),{baseDecimal:Y}=IN(F),Q=y.includes(F)?I:I.toUpperCase(),_="decimals"in P&&P.decimals!==void 0?P.decimals:Y,j="logoURI"in P&&P.logoURI?P.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${I.toLowerCase()}.png`,U={decimal:_,identifier:I,logoURI:j,tax:"tax"in P?P.tax:void 0};if(i.set(Q,U),g){let k=y.includes(F)?`${F}:${g}`:`${F}:${g.toUpperCase()}`;UN.set(k,I)}}return!0}static setStaticAssets(N){i.clear(),UN.clear();for(let[A,T]of N.entries()){let{identifier:H}=T,{chain:P,symbol:I}=f(H),{address:F}=uN(I,P),{baseDecimal:O}=IN(P),g=T.chain??P,Y=T.address??F,Q=y.includes(g)?H:H.toUpperCase(),_=T.decimals??T.decimal??O,j=T.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${H.toLowerCase()}.png`,U={decimal:_,identifier:Q,logoURI:j,tax:T.tax};if(i.set(Q,U),Y){let k=y.includes(g)?`${g}:${Y}`:`${g}:${Y.toUpperCase()}`;UN.set(k,H)}}return!0}static get staticAssets(){return i}}function bL(N){let A=v.from({chain:N});return qN(N).with(E.Bitcoin,E.Litecoin,E.BitcoinCash,E.Dash,()=>A.set(0.00010001)).with(E.Dogecoin,()=>A.set(1.00000001)).with(E.Avalanche,E.Ethereum,E.Arbitrum,E.BinanceSmartChain,()=>A.set(0.00000001)).with(E.THORChain,E.Maya,()=>A.set(0)).with(E.Cosmos,E.Kujira,()=>A.set(0.000001)).otherwise(()=>A.set(0.00000001))}async function BA({chain:N,address:A,ticker:T}){let P=y.includes(N)?`${N}:${A||T}`:`${N}:${A||T}`.toUpperCase(),I=pT(P);if(I)return I;if(!A){let{baseDecimal:g}=IN(N);return{decimals:g,identifier:`${N}.${T||"UNKNOWN"}`}}let F=await LA({address:A,chain:N}),O=`${N}.${F.ticker||T||"UNKNOWN"}-${A}`;return c({condition:!!(!F.ticker&&T),id:`async_token_lookup_failed_${N}_${A}`,warning:`Could not fetch token metadata for ${N}:${A} from chain. Using user-provided ticker (${T}) with baseDecimal (${F.decimals}).`}),F.ticker&&yT(P,{decimals:F.decimals,identifier:O}),{decimals:F.decimals,identifier:O}}function vN({identifier:N,decimal:A,value:T,tax:H}){return uA(N),new v({decimal:A,identifier:N,tax:H,value:e(T,A)})}function oT(N,A=0){let T=N.includes(".")?N.split(".")?.[0]?.toUpperCase():void 0,H=T?kN.includes(T):!1,P=N.slice(0,14).includes("~")?"~":"/",[I,F]=H?N.split(".").slice(1).join().split(P):N.split(P);if(!(I&&F))throw new t({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});return new v({decimal:8,identifier:`${T||E.THORChain}.${I}${P}${F}`,value:e(A,8)})}async function fT({address:N,chain:A,fromBaseDecimal:T,parsedValue:H}){let{decimals:P,identifier:I}=await BA({address:N,chain:A}),F=T?e(BigInt(H),T):H;return vN({decimal:P,identifier:I,value:F})}function e(N,A){return typeof N==="bigint"?h({bigIntDecimal:A,decimal:A,value:N}):N}function CT(N){let A=qN(N).when((T)=>("chain"in T)&&T.chain!==void 0,({chain:T})=>T).otherwise((T)=>{let H=f(T.asset);return H.synth?E.THORChain:H.chain});if(!kT.includes(A.toUpperCase())){let T="asset"in N?N.asset:A;throw new t({errorKey:"helpers_invalid_asset_identifier",info:{identifier:T,message:`Unsupported chain "${A}" - use the AssetValue constructor directly`}})}}function hT(N){if(CT(N),"chain"in N){let{chain:P,address:I}=N;if(I){let F=y.includes(P)?`${P}:${I}`:`${P}:${I.toUpperCase()}`,O=UN.get(F);if(O)return O;return null}return P}let{chain:A,symbol:T}=f(N.asset);return WN({chain:A,symbol:T})==="Native"?A:N.asset}function dT(N,A,T){let H=N.split("."),P=H[0]?.toUpperCase(),I=kN.includes(P),F=T?"~":"/",[O,g=""]=I?H.slice(1).join(".").split(F):N.split(F);if(!(O&&g))throw new t({errorKey:"helpers_invalid_asset_identifier",info:{identifier:N}});let{ticker:Y,address:Q}=OA({chain:O,symbol:g}),_=`${O}${F}${g}`;return{address:Q,chain:P,isGasAsset:!1,isSynthetic:A,isTradeAsset:T,symbol:_,ticker:Y}}function cT(N){let A=N.indexOf("."),T=(A===-1?N:N.slice(0,A)).toUpperCase(),H=A===-1?N:N.slice(A+1),{address:P,ticker:I}=OA({chain:T,symbol:H}),F;try{F=P&&KT.includes(T)&&IA(P)?IA(P):P}catch{F=P}let O=F?`${I}-${F}`:H;return{address:F,chain:T,isGasAsset:tN({chain:T,symbol:H}),isSynthetic:!1,isTradeAsset:!1,symbol:O,ticker:I}}function nA(N){let A=N.slice(0,14),T=A.includes("/"),H=A.includes("~");if(T||H)return dT(N,T,H);return cT(N)}function OA({symbol:N,chain:A}){let{ticker:T,address:H}=uN(N,A);return{address:H&&!y.includes(A)?H.toLowerCase():H,ticker:T}}class SN extends p{eq(N){return this.eqValue(N)}static fromBigInt(N,A){return new SN({decimal:A,value:h({bigIntDecimal:A,decimal:A,value:N})})}}function $A(N=!0){return N?"https://midgard.thorchain.network":"https://midgard.mayachain.info"}function rT(N=!0){let A=$A(N);return N?`${A}/v2/thorname`:`${A}/v2/mayaname`}function iT(N){return function(T){let H=T?`?status=${T}`:"";return G.get(`${N}/v2/pools${H}`)}}function sT(N){return function(T){return G.get(`${N}/v2/pool/${T}`)}}function eT(N){return function(T,H){let P=H?`?period=${H}`:"";return G.get(`${N}/v2/pool/${T}/stats${P}`)}}function aT(N){return function(T,H){let P=new URLSearchParams;if(H?.interval)P.append("interval",H.interval);if(H?.count)P.append("count",H.count.toString());if(H?.from)P.append("from",H.from.toString());if(H?.to)P.append("to",H.to.toString());let I=P.toString()?`?${P.toString()}`:"";return G.get(`${N}/v2/history/depths/${T}${I}`)}}function NH(N){return function(){return G.get(`${N}/v2/network`)}}function AH(N){return function(){return G.get(`${N}/v2/health`)}}function TH(N){return function(){return G.get(`${N}/v2/nodes`)}}function HH(N){return function(T){return G.get(`${N}/v2/node/${T}`)}}function PH(N){return function(){return G.get(`${N}/v2/mimir/votes`)}}function LH(N){return function(){return G.get(`${N}/v2/mimir`)}}function RH(N){return function(){return G.get(`${N}/v2/constants`)}}function uH(N){return function(){return G.get(`${N}/v2/stats`)}}function FH(N){return function(T){let H=new URLSearchParams;if(T?.interval)H.append("interval",T.interval);if(T?.count)H.append("count",T.count.toString());if(T?.from)H.append("from",T.from.toString());if(T?.to)H.append("to",T.to.toString());let P=H.toString()?`?${H.toString()}`:"";return G.get(`${N}/v2/history/earnings${P}`)}}function IH(N){return function(T,H){let P=new URLSearchParams;if(H?.interval)P.append("interval",H.interval);if(H?.count)P.append("count",H.count.toString());if(H?.from)P.append("from",H.from.toString());if(H?.to)P.append("to",H.to.toString());let I=P.toString()?`?${P.toString()}`:"",F=T?`/swaps/${T}`:"/swaps";return G.get(`${N}/v2/history${F}${I}`)}}function nH(N){return function(T){let H=new URLSearchParams;if(T?.interval)H.append("interval",T.interval);if(T?.count)H.append("count",T.count.toString());if(T?.from)H.append("from",T.from.toString());if(T?.to)H.append("to",T.to.toString());let P=H.toString()?`?${H.toString()}`:"";return G.get(`${N}/v2/history/tvl${P}`)}}function BH(N){if(!N)return"";let A=new URLSearchParams,T=(H,P)=>{if(P!==void 0)A.append(H,typeof P==="number"?P.toString():P)};return T("address",N.address),T("txid",N.txid),T("asset",N.asset),T("type",N.type),T("affiliate",N.affiliate),T("limit",N.limit),T("offset",N.offset),A.toString()?`?${A.toString()}`:""}function OH(N){return function(T){let H=BH(T);return G.get(`${N}/v2/actions${H}`)}}function $H(N){return function(T){return G.get(`${N}/v2/member/${T}`)}}function GH(N){return function(T){let H=T?`/${T}`:"";return G.get(`${N}/v2/members${H}`)}}function gH(N){return function(T,H){let P=H?`&asset=${H}`:"";return G.get(`${N}/v2/saver/${T}${P?`?${P.substring(1)}`:""}`)}}function MH(N){return function(T){return G.get(`${N}/v2/savers/${T}`)}}function tH(N){return function(T,H){let P=new URLSearchParams;if(H?.interval)P.append("interval",H.interval);if(H?.count)P.append("count",H.count.toString());if(H?.from)P.append("from",H.from.toString());if(H?.to)P.append("to",H.to.toString());let I=P.toString()?`?${P.toString()}`:"",F=T?`/savers/${T}`:"/savers";return G.get(`${N}/v2/history${F}${I}`)}}function _H(N){return function(T){return G.get(`${N}/v2/balance/${T}`)}}function DH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return;throw P};return await G.get(`${N}/lookup/${T}`,{onError:H,retry:{maxRetries:1}})}}function YH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return[];throw P};return await G.get(`${N}/rlookup/${T}`,{onError:H,retry:{maxRetries:1}})}}function UH(N){return async function(T){let H=(P)=>{if(P?.cause?.status===404)return[];throw P};return await G.get(`${N}/owner/${T}`,{onError:H,retry:{maxRetries:1}})}}function a({asset:N,value:A}){return v.from({asset:N,fromBaseDecimal:lT(XN.THORChain).baseDecimal,value:A})}function SH({liquidityPositionGetter:N,isThorchain:A}){return async function(H){let P=await N(H),I=A?"rune":"cacao";return P.pools.map((F)=>({[`${I}Pending`]:a({asset:"THOR.RUNE",value:F.runePending}),[`${I}RegisteredAddress`]:F.runeAddress,[`${I}Withdrawn`]:a({asset:"THOR.RUNE",value:F.runeWithdrawn}),[I]:a({asset:"THOR.RUNE",value:F.runeAdded}),asset:a({asset:F.pool,value:F.assetAdded}),assetPending:a({asset:F.pool,value:F.assetPending}),assetRegisteredAddress:F.assetAddress,assetWithdrawn:a({asset:F.pool,value:F.assetWithdrawn}),dateFirstAdded:F.dateFirstAdded,dateLastAdded:F.dateLastAdded,poolShare:new SN(F.liquidityUnits).div(F.pool)}))}}function GA(N){let A=N===XN.THORChain,T=$A(A),H=rT(A),P=$H(T);return{getActions:OH(T),getBalance:_H(T),getConstants:RH(T),getEarningsHistory:FH(T),getHealth:AH(T),getLiquidityPosition:SH({isThorchain:A,liquidityPositionGetter:P}),getLiquidityPositionRaw:P,getMembers:GH(T),getMimir:LH(T),getMimirVotes:PH(T),getNameDetails:DH(H),getNamesByAddress:YH(H),getNamesByOwner:UH(H),getNetworkInfo:NH(T),getNode:HH(T),getNodes:TH(T),getPool:sT(T),getPoolDepthHistory:aT(T),getPoolStats:eT(T),getPools:iT(T),getSaverDetails:gH(T),getSavers:MH(T),getSaversHistory:tH(T),getStats:uH(T),getSwapHistory:IH(T),getTVLHistory:nH(T)}}var gA=GA(XN.THORChain),MA=GA(XN.Maya);var yN={};dN(yN,{getTrackerDetails:()=>iH,getTokenListProviders:()=>AP,getTokenList:()=>TP,getTokenApproval:()=>NP,getSwapTo:()=>nP,getSwapQuote:()=>sH,getRouteWithTx:()=>eH,getPrice:()=>HP,getNearDepositChannel:()=>RP,getGasRate:()=>PP,getChainflipDepositChannel:()=>LP,getChainBalance:()=>aH,SKRequestClient:()=>W});import{EVMChains as lH}from"@swapkit/types";import{match as rH,P as BN}from"ts-pattern";async function tA(N,A,T){let H=`${A}:${T}`,P=new TextEncoder,I=await crypto.subtle.importKey("raw",P.encode(N),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),F=await crypto.subtle.sign("HMAC",I,P.encode(H));return Array.from(new Uint8Array(F)).map((O)=>O.toString(16).padStart(2,"0")).join("")}import{Chain as EN,ChainId as nN}from"@swapkit/types";import{array as X,boolean as K,coerce as UA,number as M,object as $,optional as B,string as R,union as KN,unknown as SA,z as L}from"zod/v4";var XA;((H)=>{H.CHEAPEST="CHEAPEST";H.FASTEST="FASTEST";H.RECOMMENDED="RECOMMENDED"})(XA||={});var wN;((P)=>{P.PSBT="PSBT";P.EVM="EVM";P.COSMOS="COSMOS";P.RADIX="RADIX"})(wN||={});var EA;((b)=>{b.approve="approve";b.claim="claim";b.deposit="deposit";b.donate="donate";b.lending="lending";b.lp_action="lp_action";b.native_contract_call="native_contract_call";b.native_send="native_send";b.stake="stake";b.streaming_swap="streaming_swap";b.swap="swap";b.thorname_action="thorname_action";b.token_contract_call="token_contract_call";b.token_transfer="token_transfer";b.unknown="unknown";b.unstake="unstake"})(EA||={});var wA;((U)=>{U.swap="swap";U.aggregation="aggregation";U.addLiquidity="addLiquidity";U.withdrawLiquidity="withdrawLiquidity";U.addSavers="addSavers";U.withdrawSavers="withdrawSavers";U.borrow="borrow";U.repay="repay";U.name="name";U.donate="donate";U.claim="claim";U.stake="stake";U.unstake="unstake"})(wA||={});var QA;((O)=>{O.unknown="unknown";O.not_started="not_started";O.pending="pending";O.swapping="swapping";O.completed="completed";O.refunded="refunded";O.failed="failed"})(QA||={});var xA;((x)=>{x.not_started="not_started";x.starting="starting";x.broadcasted="broadcasted";x.mempool="mempool";x.inbound="inbound";x.outbound="outbound";x.swapping="swapping";x.completed="completed";x.refunded="refunded";x.partially_refunded="partially_refunded";x.dropped="dropped";x.reverted="reverted";x.replaced="replaced";x.retries_exceeded="retries_exceeded";x.parsing_error="parsing_error"})(xA||={});var yL=$({address:B(R()),chain:L.enum(EN).optional(),chainId:L.enum(nN),coingeckoId:B(R()),decimals:UA.number(),extensions:B(L.looseObject({})),identifier:R(),logoURI:B(R()),name:B(R()),shortCode:B(R()),symbol:B(R()),ticker:R()}),oL=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"}),fL=L.object({forceUpdate:L.string().toLowerCase().transform((N)=>N==="true").pipe(L.boolean()).optional()}),CL=$({error:R(),message:R()}),NN=$({address:B(R()),chain:L.enum(EN),decimal:B(M()),isGasAsset:K(),isSynthetic:K(),symbol:R(),tax:B($({buy:M(),sell:M()})),ticker:R()}),bA=$({id:R(),market_cap:M(),name:R(),price_change_24h_usd:M(),price_change_percentage_24h_usd:M(),sparkline_in_7d:X(M()),timestamp:R(),total_volume:M()}).partial(),hL=$({cg:B(bA),identifier:R(),price_usd:M(),provider:R(),timestamp:M()}),zA=X($({cg:B(bA),identifier:R(),price_usd:M(),provider:R(),timestamp:M()}).partial()),dL=$({affiliate:B(R().describe("Affiliate thorname")),affiliateFee:B(M().describe("Affiliate fee in basis points").refine((N)=>N===Math.floor(N)&&N>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:B(K().describe("Allow smart contract as recipient")),allowSmartContractSender:B(K().describe("Allow smart contract as sender")),buyAsset:R().describe("Asset to buy"),cfBoost:B(K().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:B(R().describe("Address to send asset to")),disableSecurityChecks:B(K().describe("Disable security checks")),includeTx:B(K().describe("Set to true to include an transaction object (EVM only)")),providers:B(X(R().describe("List of providers to use").refine((N)=>J[N]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:B(R().describe("Referrer address (referral program)")),sellAmount:R().describe("Amount of asset to sell").refine((N)=>+N>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:R().describe("Asset to sell"),slippage:B(M().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:B(R().describe("Address to send asset from"))}).refine((N)=>N.sellAsset!==N.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),cL=$({metadata:K(),tokens:X($({identifier:R()}))}),JA=$({destinationAddress:R()}),XH=JA.extend({affiliateFees:X($({brokerAddress:R(),feeBps:M()})).optional(),brokerCommissionBps:M().optional(),buyAsset:$({asset:R(),chain:R()}),channelMetadata:$({cfParameters:R().optional(),gasBudget:R().optional(),message:R().optional()}).optional(),dcaParameters:$({chunkInterval:M().optional(),numberOfChunks:M().optional()}).optional(),maxBoostFeeBps:M().optional(),refundParameters:$({minPrice:R().optional(),refundAddress:R().optional(),retryDuration:M().optional()}).optional(),sellAsset:$({asset:R(),chain:R()})}),ZA=$({channelId:R(),depositAddress:R()}),_A=JA.extend({affiliateFees:$({feeBps:M(),nearId:R()}).optional(),buyAsset:R(),sellAmount:R(),sellAsset:R(),slippage:UA.number(),sourceAddress:R()}),DA=$({amountIn:R(),amountInFormatted:R(),amountInUsd:R(),amountOut:R(),amountOutFormatted:R(),amountOutUsd:R(),deadline:R().optional(),minAmountIn:R(),minAmountOut:R(),timeEstimate:M().optional(),timeWhenInactive:R().optional()}),lL=DA.extend({depositAddress:R(),quote:DA,signature:R(),timestamp:R(),tx:SA()}),VA=$({buyAsset:R(),buyAssetAmount:R(),buyAssetAmountMaxSlippage:R(),deadline:R().optional(),depositAddress:R(),depositAmount:R(),depositAsset:R(),tx:SA()}),EH=$({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())}),wH=$({currentStage:R(),inboundConfirmation:M(),inboundObservation:M(),outboundDelay:M(),outboundObservation:M(),streamingSwap:M()}),QH=$({count:B(M()),interval:B(M()),quantity:B(M()),subSwapsMap:B(X(M()))}),xH=L.object({currentLegIndex:L.optional(L.number()),estimatedTimeToComplete:L.number(),estimates:L.optional(wH),providerDetails:L.optional(L.object({streamingDetails:L.optional(QH)}))}),bH=$({affiliate:B(NN),liquidity:B(NN),network:B(NN),protocol:B(NN),tax:B(NN)}),zH=$({affiliate:R(),bps:R(),isReferrer:K()}),JH=$({affiliate:B(R()),affiliateFees:B(X(zH)),broadcastedAt:B(M()),explorerUrl:B(R()),fees:B(bH),images:B($({chain:B(R()),from:B(R()),provider:B(R()),to:B(R())})),provider:B(L.enum(J)),providerAction:L.optional(L.enum(wA)),quoteId:B(R()),wallet:B(R())}),AN=L.object({block:L.number(),chainId:L.enum(nN),finalAddress:L.optional(L.string()),finalAsset:L.optional(NN),finalisedAt:L.number(),fromAddress:L.string(),fromAmount:L.string(),fromAsset:L.string(),hash:L.string(),meta:L.optional(JH),payload:L.optional(EH),status:L.enum(QA),toAddress:L.string(),toAmount:L.string(),toAsset:L.string(),trackingStatus:L.optional(L.enum(xA)),transient:L.optional(xH),type:L.enum(EA)}),WA=AN.extend({legs:L.array(AN)}),rL=AN.extend({legs:X(AN)}),iL=AN.extend({legs:X(AN)}),mN=X($({amount:R(),asset:R(),chain:R(),protocol:L.enum(J),type:L.enum(bN)})),pN=L.object({inbound:L.optional(L.number().describe("Time to receive inbound asset in seconds")),outbound:L.optional(L.number().describe("Time to receive outbound asset in seconds")),swap:L.optional(L.number().describe("Time to swap assets in seconds")),total:L.number().describe("Total time in seconds")}),jA=$({data:R().describe("Data to send"),from:R().describe("Address of the sender"),to:R().describe("Address of the recipient"),value:R().describe("Value to send")}),vA=L.object({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(),visible:L.boolean()}),ZH=X(KN([R(),M(),X(R()),$({from:R(),value:R()}).describe("Parameters to pass to the contract method")])),sL=$({approvalSpender:B(R().describe("Address of the spender to approve")),approvalToken:B(R().describe("Address of the token to approve spending of")),contractAddress:R().describe("Address of the contract to interact with"),contractMethod:R().describe("Name of the method to call"),contractParamNames:X(R().describe("Names of the parameters to pass to the contract method")),contractParams:ZH}),VH=$({typeUrl:R("/types.MsgDeposit"),value:$({coins:X($({amount:R(),asset:$({chain:R(),symbol:R(),synth:K(),ticker:R()})})),memo:R(),signer:R()})}),WH=$({typeUrl:R("/types.MsgSend"),value:$({amount:X($({amount:R(),denom:R()})),fromAddress:R(),toAddress:R()})}),jH=$({typeUrl:R(),value:WH.or(VH)}),vH=$({amount:X($({amount:R(),denom:R()})),gas:R()}),qA=$({accountNumber:M(),chainId:L.enum(nN),fee:vH,memo:R(),msgs:X(jH),sequence:M()}),qH=L.array(L.object({calldata:L.array(L.string()),contractAddress:L.string(),entrypoint:L.string()})),kA=L.array(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")})),kH=$({affiliate:R().describe("Affiliate address").optional(),affiliateFee:M().describe("Affiliate fee").optional(),buyAsset:R().describe("Asset to buy"),destinationAddress:R().describe("Destination address"),estimatedTime:pN.optional(),provider:L.enum(J),sellAsset:R().describe("Asset to sell"),slipPercentage:M().describe("Slippage as a percentage"),sourceAddress:R().describe("Source address")}),eL=kH.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),KH=$({asset:R().describe("Asset name"),image:R().describe("Asset image"),price:M().describe("Price in USD")}),mH=XH,KA=$({assets:B(X(KH)),maxStreamingQuantity:M().optional(),referrer:R().optional(),streamingInterval:M().optional(),tags:X(L.enum(XA))}),mA=KA.extend({affiliate:B(R()),affiliateFee:B(R()),approvalAddress:B(R().describe("Approval address for swap")),chainflip:mH.optional(),garden:_A.optional(),near:_A.optional(),priceImpact:B(M().describe("Price impact")),referrer:B(R()),txType:B(L.enum(wN))}),pA=X($({code:L.enum(xN),display:R(),tooltip:R().optional()})),pH=$({buyAmount:R().describe("Buy amount"),buyAmountMaxSlippage:R().describe("Buy amount max slippage"),buyAsset:R().describe("Asset to buy"),fees:B(mN),provider:L.enum(J),sellAmount:R().describe("Sell amount"),sellAsset:R().describe("Asset to sell")}),yH=$({buyAsset:R().describe("Asset to buy"),destinationAddress:B(R().describe("Destination address")),estimatedTime:B(pN),expectedBuyAmount:R().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:R().describe("Expected Buy amount max slippage"),expiration:B(R().describe("Expiration")),fees:mN,inboundAddress:B(R().describe("Inbound address")),legs:X(pH),memo:B(R().describe("Memo")),meta:mA,providers:X(L.enum(J)),routeId:R().describe("Route ID"),sellAmount:R().describe("Sell amount"),sellAsset:R().describe("Asset to sell"),sourceAddress:B(R().describe("Source address")),targetAddress:B(R().describe("Target address")),totalSlippageBps:M().describe("Total slippage in bps"),tx:B(KN([jA,qA,vA,qH,kA,R()])),txType:B(L.enum(wN)),warnings:pA}),yA=$({error:B(R().describe("Error message")),providerErrors:B(X($({errorCode:B(L.enum(LN)),message:B(R()),provider:L.enum(J).optional()}))),quoteId:R().describe("Quote ID"),routes:X(yH)}),oA=L.object({chainId:L.enum(nN),createdAt:L.date(),id:L.number(),unit:L.string(),value:L.string()}),oH=L.array(oA),fA=L.union([oA,oH]),aL=X($({chain:L.enum(EN),decimal:M(),identifier:R(),symbol:R(),ticker:R(),value:R()})),NR=L.union([L.object({amount:L.string(),spender:L.string(),tokenIdentifier:L.string(),userWalletAddress:L.string()}),L.object({amount:L.string(),chainId:L.enum(nN),spender:L.string(),tokenContractAddress:L.string(),userWalletAddress:L.string()}),L.object({routeId:L.string()})]),AR=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:L.string()})),approvedAmount:L.string(),isApproved:L.boolean()}),fH=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:L.string().describe("ETH value (always '0' for approvals)")}),YA=L.object({buyAmount:L.string().describe("Buy amount"),buyAmountMaxSlippage:L.string().describe("Buy amount max slippage"),buyAsset:L.string().describe("Asset to buy"),expectedBuyAmount:L.string().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:L.string().describe("Expected Buy amount max slippage"),fees:mN,provider:L.enum(J),sellAmount:L.string().describe("Sell amount"),sellAsset:L.string().describe("Asset to sell")}),CA=YA.extend({estimatedTime:L.optional(pN),expiration:L.optional(L.string().describe("Expiration")),legs:L.array(YA),providers:L.array(L.enum(J)),routeId:L.string().describe("Route ID"),totalSlippageBps:L.number().describe("Total slippage in bps"),warnings:pA}).omit({provider:!0}),CH=L.object({method:L.string(),payload:L.optional(L.unknown()),url:L.string()}),hH=CA.extend({meta:KA,nextActions:L.optional(L.array(CH))}),TR=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(L.object({errorCode:L.optional(L.enum(LN)),message:L.optional(L.string()),provider:L.enum(J).optional()}))),quoteId:L.string().describe("Quote ID"),routes:L.array(hH)}),HR=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')")}),dH=L.object({chain:L.enum(EN).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")}),PR=L.object({buyAssets:L.array(dH).describe("List of assets that can be swapped to"),sellAsset:L.string().describe("The input sell asset identifier")}),hA=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:mA,sourceAddress:L.string().describe("Source address"),targetAddress:L.optional(L.string().describe("Target address")),tx:B(KN([jA,qA,vA,kA,R()])),txType:L.optional(L.enum(wN))}),cH=L.object({data:L.optional(L.record(L.string(),L.string().optional())),errorCode:L.enum(LN),message:L.string().optional(),provider:L.enum(J).optional()}),LR=L.object({error:L.optional(L.string().describe("Error message")),providerErrors:L.optional(L.array(cH)),quoteId:L.string().describe("Quote ID"),routes:L.array(hA)}),dA=hA.extend({approvalTx:fH.optional().describe("Optional approval transaction if ERC-20 approval is required before swap"),swapId:L.string().describe("The unique swap ID for tracking")});var W=G.extend({dynamicHeader:async()=>{let N=w.get("widgetKey");if(N&&typeof window<"u"){let T=Math.floor(Date.now()/1000),H=window.location.origin;return{"X-Signature":await tA(N,H,T),"X-Timestamp":T.toString()}}let{swapKit:A}=w.get("apiKeys");return A?{"x-api-key":A}:{}}});async function iH(N){let A=await W.post(V("/track"),{json:N});try{let T=WA.safeParse(A);if(!T.success)throw new t("api_v2_invalid_response",T.error);return T.data}catch(T){return A}}async function sH(N){let{getQuote:A}=w.get("endpoints");if(A)return A(N);let H=w.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",P=await W.post(V(H),{json:N});if(P.error)throw new t("api_v2_server_error",{message:P.error});try{let I=yA.safeParse(P);if(!I.success)throw new t("api_v2_invalid_response",I.error);return I.data}catch{return P}}async function eH(N){let{getRouteWithTx:A}=w.get("endpoints");if(A)return A(N);let H=w.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",P=await W.post(V(H),{json:N});try{let I=dA.safeParse(P);if(!I.success)throw new t("api_v2_invalid_response",I.error);return I.data}catch(I){return console.error(new t("api_v2_invalid_response",I)),P}}async function aH({chain:N,address:A,scamFilter:T=!0}){let{getBalance:H}=w.get("endpoints");if(H)return H({address:A,chain:N});let P=V(`/balance?chain=${N}&address=${A}`),I=await W.get(P),F=Array.isArray(I)?I:[];return T?IP(F):F}function NP(N){let A=rH(N).with({routeId:BN.string,spender:BN.string},({routeId:T,spender:H})=>V(`/approve?routeId=${T}&sourceAddress=${H}`)).with({assetValue:BN.instanceOf(v),spender:BN.string,userWallet:BN.string},({spender:T,userWallet:H,assetValue:P})=>V(`/approve?tokenIdentifier=${P.toString()}&userWalletAddress=${H}&spender=${T}&amount=${P.getValue("string")}`)).exhaustive();return W.get(A)}function AP(){let N=V("/providers");return W.get(N)}function TP(N){let A=V(`/tokens?provider=${N}`);return W.get(A)}async function HP(N){let A=V("/price"),T=await W.post(A,{json:N});try{let H=zA.safeParse(T);if(!H.success)throw new t("api_v2_invalid_response",H.error);return H.data}catch(H){throw new t("api_v2_invalid_response",H)}}async function PP(){let N=V("/gas"),A=await W.get(N);try{let T=fA.safeParse(A);if(!T.success)throw new t("api_v2_invalid_response",T.error);return Array.isArray(T)?T:[T]}catch(T){throw new t("api_v2_invalid_response",T)}}async function LP(N){let{destinationAddress:A}=N;if(!A)throw new t("chainflip_broker_invalid_params");let T=w.get("integrations").chainflip?.brokerUrl||V("/chainflip/broker/channel"),H=await W.post(T,{json:N});try{let P=ZA.safeParse(H);if(!P.success)throw new t("api_v2_invalid_response",P.error);return P.data}catch(P){throw new t("api_v2_invalid_response",P)}}async function RP(N){let{destinationAddress:A}=N;if(!A)throw new t("chainflip_broker_invalid_params");let T=V("/near/channel"),H=await W.post(T,{json:N});try{let P=VA.safeParse(H);if(!P.success)throw new t("api_v2_invalid_response",P.error);return P.data}catch(P){throw new t("api_v2_invalid_response",P)}}function V(N){let{isDev:A,apiUrl:T,devApiUrl:H}=w.get("envs");return`${A?H:T}${N}`}function uP(N){let[A,T]=N.split(".");if(!lH.includes(A))return!0;let H=T.split("-"),P=H.length===1?void 0:H[H.length-1];return tN({chain:A,symbol:T})||!!P}var FP=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi");function IP(N){return N.filter((A)=>{return!FP.test(A.identifier)&&uP(A.identifier)})}async function nP(N){let{getSwapTo:A}=w.get("endpoints");if(A)return A(N);let T=new URLSearchParams({sellAsset:N.sellAsset});if(N.providers?.length)for(let F of N.providers)T.append("providers",F);let H=V(`/swapTo?${T.toString()}`),P=await W.get(H);if(!Array.isArray(P))return{buyAssets:[],sellAsset:N.sellAsset};let I=[];for(let F of P)try{let O=v.from({asset:F});I.push({chain:O.chain,identifier:O.toString(),providers:[],symbol:O.symbol,ticker:O.ticker})}catch{}return{buyAssets:I,sellAsset:N.sellAsset}}var oN={};dN(oN,{getThorchainQueue:()=>GP,getTcyStakers:()=>SP,getTcyStaker:()=>UP,getTcyClaimers:()=>EP,getTcyClaimer:()=>XP,getTNSPreferredAsset:()=>_P,getTHORNodeTNSDetails:()=>cA,getRunePoolProviderInfo:()=>YP,getRunePoolInfo:()=>DP,getNodes:()=>gP,getMimirInfo:()=>MP,getLastBlock:()=>$P,getInboundAddresses:()=>tP});import{match as BP}from"ts-pattern";function q(N){let{isStagenet:A}=w.get("envs"),T=w.get("thornodeUrls");return`${BP({isStagenet:A,type:N}).with({type:"mayachain"},({isStagenet:P})=>P?T.MAYA_STAGENET:T.MAYA).with({type:"thorchain"},({isStagenet:P})=>P?T.THOR_STAGENET:T.THOR)}/${N}`}function OP(N){let A=N==="mayachain"?"mayaname":"thorname";return`${q(N)}/${A}`}function $P(N="thorchain"){return G.get(`${q(N)}/lastblock`)}function GP(N){return G.get(`${q(N)}/queue`)}function gP(N){return G.get(`${q(N)}/nodes`)}function MP(N){return G.get(`${q(N)}/mimir`)}function tP(N){return G.get(`${q(N)}/inbound_addresses`)}async function cA({type:N,name:A}){try{return await G.get(`${OP(N)}/${A}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:A,owner:"",preferred_asset:""}}}async function _P({type:N,tns:A}){let T=await cA({name:A,type:N});if(!T.preferred_asset||T.preferred_asset===".")return;return v.from({asset:T.preferred_asset,asyncTokenLookup:!0})}function DP(N){return G.get(`${q(N)}/runepool`)}function YP({type:N,thorAddress:A}){return G.get(`${q(N)}/rune_provider/${A}`)}function UP({type:N,address:A}){return G.get(`${q(N)}/tcy_staker/${A}`)}function SP(N){return G.get(`${q(N)}/tcy_stakers`)}function XP({type:N,address:A}){return G.get(`${q(N)}/tcy_claimer/${A}`)}function EP(N){return G.get(`${q(N)}/tcy_claimers`)}var UR={...yN,mayachainMidgard:MA,thorchainMidgard:gA,thornode:oN};
5
- export{xP as a,LN as b,xN as c,J as d,bN as e,NT as f,AT as g,TT as h,zN as i,HT as j,Z as k,w as l,t as m,G as n,lP as o,rP as p,iP as q,sP as r,c as s,VN as t,ET as u,l as v,PL as w,nL as x,LA as y,tN as z,_N as A,WN as B,f as C,uN as D,BL as E,OL as F,uA as G,ML as H,h as I,p as J,v as K,bL as L,SN as M,tA as N,XA as O,wN as P,EA as Q,wA as R,QA as S,xA as T,yL as U,oL as V,fL as W,CL as X,NN as Y,bA as Z,hL as _,zA as $,dL as aa,cL as ba,JA as ca,XH as da,ZA as ea,_A as fa,lL as ga,VA as ha,WA as ia,rL as ja,iL as ka,mN as la,pN as ma,jA as na,vA as oa,ZH as pa,sL as qa,qA as ra,qH as sa,kA as ta,kH as ua,eL as va,KH as wa,mH as xa,KA as ya,mA as za,pA as Aa,yH as Ba,yA as Ca,oA as Da,fA as Ea,NR as Fa,AR as Ga,fH as Ha,TR as Ia,HR as Ja,dH as Ka,PR as La,hA as Ma,cH as Na,LR as Oa,dA as Pa,UR as Qa};
@@ -1,4 +0,0 @@
1
- var jP={};x(jP,{TxnType:()=>mN,TxnStatus:()=>yN,TronTransactionSchema:()=>iN,TransactionSchema:()=>pH,TransactionDTOSchema:()=>yH,TrackingStatus:()=>oN,TrackingRequestSchema:()=>QH,TrackingRequestQuerySchema:()=>xH,TrackerResponseSchema:()=>lN,TokenSchema:()=>wH,TokenDetailsMetadataSchema:()=>zH,TONTransactionSchema:()=>eN,SwapToResponseSchema:()=>TP,SwapToRequestSchema:()=>AP,SwapToAssetSchema:()=>hA,SwapRouteV2ResponseSchema:()=>RA,SwapKitApi:()=>WP,StarknetTransactionSchema:()=>KA,RouteQuoteWarningSchema:()=>AA,RouteQuoteTxType:()=>nN,RouteQuoteProviderErrorSchema:()=>dA,RouteQuoteMetadataV2Schema:()=>NA,RouteQuoteMetadataSchema:()=>aN,RouteQuoteMetadataAssetSchema:()=>pA,RouteLegWithoutAddressesSchema:()=>cH,RouteLegSchema:()=>mA,QuoteV3ResponseSchema:()=>NP,QuoteV2ResponseSchema:()=>HP,QuoteRouteV2Response:()=>LA,QuoteResponseSchema:()=>TA,QuoteResponseRouteItem:()=>oA,QuoteRequestSchema:()=>JH,ProviderAction:()=>pN,PriorityLabel:()=>KN,PriceResponseSchema:()=>CN,PriceRequestSchema:()=>ZH,NearSwapResponseSchema:()=>cN,NearDepositChannelResultSchema:()=>VH,NearDepositChannelParamsSchema:()=>kN,GasSchema:()=>HA,GasResponseSchema:()=>PA,FeesSchema:()=>wN,EstimatedTimeSchema:()=>QN,EVMTransactionSchema:()=>rN,EVMTransactionDetailsSchema:()=>oH,EVMTransactionDetailsParamsSchema:()=>kA,DepositChannelResponseSchema:()=>dN,DepositChannelParamsSchema:()=>hN,CosmosTransactionSchema:()=>sN,CoinGeckoMetadataSchema:()=>fN,ChainflipMetadataSchema:()=>yA,BrokerDepositChannelParamsSchema:()=>qA,AssetValueSchema:()=>d,ApproveResponseSchema:()=>sH,ApproveRequestParams:()=>iH,ApprovalTransactionSchema:()=>fA,ApiV2ErrorSchema:()=>bH});module.exports=VP(jP);var h=require("@swapkit/types");var lT={};x(lT,{getMinAmountByChain:()=>yT,AssetValue:()=>z});var G=require("@swapkit/types"),WN=require("ethers"),EN=require("ts-pattern");var ZT={};x(ZT,{parseSymbolForAddress:()=>i,isGasAsset:()=>LN,getTokenLogoURI:()=>zT,getCommonAssetInfo:()=>RN,getAssetType:()=>UN,findAssetBy:()=>JT,fetchTokenInfo:()=>JN,assetFromString:()=>K,CommonAssetStrings:()=>UT});var I=require("@swapkit/types"),r=require("ts-pattern");var nT={};x(nT,{RequestClient:()=>B});var AT={};x(AT,{swapKitConfigStore:()=>b,SKConfig:()=>U});var S=require("@swapkit/types"),MA=require("zustand/vanilla");var eA={};x(eA,{WarningCodeEnum:()=>gN,WalletOption:()=>tN,ProviderName:()=>Q,NetworkDerivationPath:()=>sA,MemoType:()=>GA,LedgerErrorCode:()=>gA,FeeTypeEnum:()=>MN,FeeOption:()=>OA,ErrorCode:()=>l,ApproveMode:()=>$A});var GN=require("@swapkit/types"),sA=GN.AllChains.reduce((A,T)=>{return A[T]=GN.getChainConfig(T).networkDerivationPath,A},{});var l;((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"})(l||={});var gN;((H)=>{H.highSlippage="highSlippage";H.highPriceImpact="highPriceImpact"})(gN||={});var Q;((Y)=>{Y.CHAINFLIP="CHAINFLIP";Y.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";Y.JUPITER="JUPITER";Y.MAYACHAIN="MAYACHAIN";Y.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";Y.ONEINCH="ONEINCH";Y.PANCAKESWAP="PANCAKESWAP";Y.SUSHISWAP_V2="SUSHISWAP_V2";Y.THORCHAIN="THORCHAIN";Y.THORCHAIN_STREAMING="THORCHAIN_STREAMING";Y.TRADERJOE_V2="TRADERJOE_V2";Y.UNISWAP_V2="UNISWAP_V2";Y.UNISWAP_V3="UNISWAP_V3";Y.NEAR="NEAR";Y.GARDEN="GARDEN";Y.OKX="OKX";Y.HARBOR="HARBOR";Y.FLASHNET="FLASHNET"})(Q||={});var MN;((O)=>{O.LIQUIDITY="liquidity";O.NETWORK="network";O.INBOUND="inbound";O.OUTBOUND="outbound";O.AFFILIATE="affiliate";O.TAX="tax";O.PRIORITY="priority";O.SERVICE="service"})(MN||={});var OA;((P)=>{P.Average="average";P.Fast="fast";P.Fastest="fastest"})(OA||={});var $A;((H)=>{H.Approve="approve";H.CheckOnly="checkOnly"})($A||={});var GA;((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-"})(GA||={});var tN;((M)=>{M.BITGET="BITGET";M.BRAVE="BRAVE";M.COINBASE_MOBILE="COINBASE_MOBILE";M.COINBASE_WEB="COINBASE_WEB";M.COSMOSTATION="COSMOSTATION";M.CTRL="CTRL";M.EIP6963="EIP6963";M.EXODUS="EXODUS";M.KEEPKEY="KEEPKEY";M.KEEPKEY_BEX="KEEPKEY_BEX";M.KEPLR="KEPLR";M.KEYSTORE="KEYSTORE";M.LEAP="LEAP";M.LEDGER="LEDGER";M.METAMASK="METAMASK";M.OKX="OKX";M.OKX_MOBILE="OKX_MOBILE";M.ONEKEY="ONEKEY";M.PASSKEYS="PASSKEYS";M.PETRA="PETRA";M.PHANTOM="PHANTOM";M.POLKADOT_JS="POLKADOT_JS";M.RADIX_WALLET="RADIX_WALLET";M.TALISMAN="TALISMAN";M.TREZOR="TREZOR";M.TRONLINK="TRONLINK";M.TRUSTWALLET_WEB="TRUSTWALLET_WEB";M.VULTISIG="VULTISIG";M.WALLETCONNECT="WALLETCONNECT";M.WALLET_SELECTOR="WALLET_SELECTOR";M.XAMAN="XAMAN"})(tN||={});var gA;((P)=>{P[P.NoError=36864]="NoError";P[P.LockedDevice=21781]="LockedDevice";P[P.TC_NotFound=65535]="TC_NotFound"})(gA||={});var aA=S.AllChains.reduce((A,T)=>{if(!A.THOR_STAGENET)A[S.StagenetChain.Maya]=S.StagenetMAYAConfig.rpcUrls,A[S.StagenetChain.THORChain]=S.StagenetTHORConfig.rpcUrls;return A[T]=S.getChainConfig(T).rpcUrls,A},{}),NT={[S.Chain.THORChain]:S.THORConfig.nodeUrl,[S.Chain.Maya]:S.MAYAConfig.nodeUrl,[S.StagenetChain.THORChain]:S.StagenetTHORConfig.nodeUrl,[S.StagenetChain.Maya]:S.StagenetMAYAConfig.nodeUrl},tA={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:S.AllChains,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"}}},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:aA,thornodeUrls:NT,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(tN),widgetKey:""},b=MA.createStore((A)=>({...tA,setApiKey:(T,H)=>A((P)=>({apiKeys:{...P.apiKeys,[T]:H}})),setConfig:(T)=>A((H)=>({apiKeys:{...H.apiKeys,...T?.apiKeys},chains:H.chains.concat(T?.chains||[]),endpoints:{...H.endpoints,...T?.endpoints},envs:{...H.envs,...T?.envs},feeMultipliers:T?.feeMultipliers||H.feeMultipliers,integrations:{...H.integrations,...T?.integrations},rpcUrls:{...H.rpcUrls,...T?.rpcUrls},thornodeUrls:{...H.thornodeUrls,...T?.thornodeUrls},v3SwapFlow:{...H.v3SwapFlow,...T?.v3SwapFlow},wallets:H.wallets.concat(T?.wallets||[]),widgetKey:T?.widgetKey||H.widgetKey})),setEndpoint:(T,H)=>A((P)=>({endpoints:{...P.endpoints,[T]:H}})),setEnv:(T,H)=>A((P)=>({envs:{...P.envs,[T]:H}})),setFeeMultipliers:(T)=>A(()=>({feeMultipliers:T})),setIntegrationConfig:(T,H)=>A((P)=>({integrations:{...P.integrations,[T]:H}})),setRequestOptions:(T)=>A((H)=>({requestOptions:{retry:{...H.requestOptions.retry,...T.retry},timeoutMs:T.timeoutMs||H.requestOptions.timeoutMs}})),setRpcUrl:(T,H)=>A((P)=>({rpcUrls:{...P.rpcUrls,[T]:H}})),setThornodeUrl:(T,H)=>A((P)=>({thornodeUrls:{...P.thornodeUrls,[T]:H}})),setWidgetKey:(T)=>A({widgetKey:T})})),U={get:(A)=>b.getState()[A],getState:b.getState,reinitialize:()=>b.setState(tA),set:(A)=>b.getState().setConfig(A),setApiKey:(A,T)=>b.getState().setApiKey(A,T),setEndpoint:(A,T)=>b.getState().setEndpoint(A,T),setEnv:(A,T)=>b.getState().setEnv(A,T),setFeeMultipliers:(A)=>b.getState().setFeeMultipliers(A),setIntegrationConfig:(A,T)=>b.getState().setIntegrationConfig(A,T),setRequestOptions:(A)=>b.getState().setRequestOptions(A),setRpcUrl:(A,T)=>b.getState().setRpcUrl(A,T),setThornodeUrl:(A,T)=>b.getState().setThornodeUrl(A,T),setWidgetKey:(A)=>b.getState().setWidgetKey(A)};var HT={};x(HT,{SwapKitError:()=>$});var TT={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_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_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 bN(A){return JSON.stringify(A,(T,H)=>typeof H==="bigint"?H.toString():H)}class $ extends Error{static ErrorCode=TT;errorKey;info;constructor(A,T){let H=typeof A==="string",P=H?A:A.errorKey,L=H?void 0:A.info,F=`${P}${L?`: ${bN(L)}`:""}`;super(F);if(Object.setPrototypeOf(this,$.prototype),this.name="SwapKitError",this.errorKey=P,this.info=L,this.cause=T,T){let u=T instanceof Error?`${T.message}${T.cause?` (${T.cause})`:""}`:bN(T);console.error(`SwapKitError [${P}]: ${u}`)}else if(L)console.error(`SwapKitError [${P}]: ${bN(L)}`)}}var PT=(A)=>new Promise((T)=>setTimeout(T,A)),LT=(A,{baseDelay:T,backoffMultiplier:H,maxDelay:P})=>Math.min(T*H**A,P);function RT(A,T){if(A instanceof Error&&A.name==="AbortError")return!0;if(A instanceof TypeError)return!0;if(T===429)return!0;if(T&&T>=500&&T<600)return!0;return!1}var uT=async(A,T)=>{let H=await fetch(A,T),P;try{P=await H.json()}catch{if(!H.ok)throw new $({errorKey:"helpers_invalid_response",info:{status:H.status,statusText:H.statusText}},{status:H.status,statusText:H.statusText});return{}}if(!H.ok){let F={data:P?.data,error:P?.error,message:P?.message,status:H.status};throw new $({errorKey:P?.error||"helpers_invalid_response",info:F},F)}let L=P?.routes?.length||P?.result||P?.data&&!P?.error;if(P?.error&&!L){let F={data:P.data,error:P.error,message:P.message,status:H.status};throw new $({errorKey:P.error,info:F},F)}if(P?.providerErrors?.length||P?.error&&L)console.warn("[SwapKit] Partial errors in response:",P.providerErrors||P.error);return P};function _N(A,T={}){return async function(P,L={}){let{searchParams:F,json:u,body:n,headers:O,dynamicHeader:t,retry:X,timeoutMs:g,abortController:V,onError:D,onSuccess:j,responseHandler:E,...w}={...T,...L},HN=U.get("requestOptions"),Y={...HN.retry,...X},BN=!!u||P.endsWith(".json"),ON=IT(P,F),IA=t?await t():{},PN=FT(BN,{...O,...IA}),c=BN?JSON.stringify(u):n,xN;for(let $N=0;$N<=Y.maxRetries;$N++){let nA=V||new AbortController,BA=setTimeout(()=>nA.abort(),g||HN.timeoutMs);try{let q=await uT(ON,{...w,body:c,headers:PN,method:A,signal:nA.signal});return clearTimeout(BA),j?.(q)||E?.(q)||q}catch(q){clearTimeout(BA),xN=q;let iA=q?.cause?.status;if($N>=Y.maxRetries||!RT(q,iA))return D?D(q):Promise.reject(q);await PT(LT($N,Y))}}return D?D(xN):Promise.reject(xN)}}function FT(A,T){return{...T,...A&&{"Content-Type":"application/json"}}}function IT(A,T){let H=new URL(A);if(T)H.search=new URLSearchParams(T).toString();return H.toString()}var B={extend:(A)=>({extend:(T)=>B.extend({...A,...T}),get:_N("GET",A),post:_N("POST",A)}),get:_N("GET"),post:_N("POST")};var YT={};x(YT,{initializeRPCUrlsWithFallback:()=>DT,getRPCUrlSync:()=>YA,getRPCUrl:()=>f,_rpcCache:()=>YN});var _=require("@swapkit/types"),zN=require("ts-pattern");var gT={};x(gT,{wrapWithThrow:()=>$T,warnOnce:()=>o,getTHORNameCost:()=>BT,getMAYANameCost:()=>OT,getChainIdentifier:()=>GT});var DN=require("@swapkit/types");function BT(A){if(A<0)throw new $({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:A}});return 10+A}function OT(A){if(A<0)throw new $({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:A}});return Math.round((10+A*1.0512)*10000000000)/10000000000}function $T(A,T){try{return A()}catch(H){if(T)throw new $(T,H);return}}function GT(A){switch(A){case DN.Chain.THORChain:return`${A}.RUNE`;case DN.Chain.Cosmos:return`${A}.ATOM`;case DN.Chain.BinanceSmartChain:return`${A}`;default:return`${A}.${A}`}}var _A=new Set;function o({condition:A,id:T,warning:H}){if(A){if(_A.has(T))return;console.warn(H),_A.add(T)}}function MT(A){return zN.match(A).with(..._.EVMChains,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(..._.UTXOChains,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(..._.CosmosChains,..._.StagenetChains,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(_.Chain.Polkadot,_.Chain.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(_.Chain.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(_.Chain.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(_.Chain.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(_.Chain.Aptos,_.Chain.Tron,_.Chain.Radix,_.Chain.Stellar,()=>"").with(_.Chain.HyperCore,()=>({type:"meta"})).with(_.Chain.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(_.Chain.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(_.Chain.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new $("helpers_chain_not_supported",{chain:A})})}function tT(A){return zN.match(A).with(_.Chain.Aptos,()=>"/-/healthy").with(_.Chain.HyperCore,()=>"/info").with(_.Chain.Radix,()=>"/status/network-configuration").with(_.Chain.Stellar,()=>"").with(_.Chain.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function DA(A,T){try{let H=T.startsWith("wss")?T.replace("wss","https"):T;return(await fetch(`${H}${tT(A)}`,{body:JSON.stringify(MT(A)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var YN=new Map,_T=120000;function YA(A){let[T=""]=U.get("rpcUrls")[A];if(!T)throw o({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 ${A}.`}),new $("helpers_chain_no_public_or_set_rpc_url",{chain:A});let H=YN.get(A);if(H&&Date.now()-H.timestamp<_T)return H.url;return YN.set(A,{timestamp:Date.now(),url:T}),T}async function f(A){let T=YA(A),[,...H]=U.get("rpcUrls")[A];if(await DA(A,T))return T;for(let L of H)if(await DA(A,L))return YN.set(A,{timestamp:Date.now(),url:L}),L;throw new $("helpers_chain_rpc_connection_failed",{chain:A,fallbackUrls:H,primaryRpcUrl:T})}function DT(A){o({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 UT=[`${I.Chain.Maya}.MAYA`,`${I.Chain.Maya}.CACAO`,`${I.Chain.Ethereum}.THOR`,`${I.Chain.Ethereum}.vTHOR`,`${I.Chain.Kujira}.USK`,`${I.Chain.Ethereum}.FLIP`,`${I.Chain.Radix}.XRD`],XA=[I.Chain.Arbitrum,I.Chain.Aurora,I.Chain.Base,I.Chain.Ethereum,I.Chain.Optimism];async function ST(A){let{baseDecimal:T}=I.getChainConfig(I.Chain.Radix);try{let H=await f(I.Chain.Radix),{manager:P}=await B.post(`${H}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:A}),headers:{Accept:"*/*","Content-Type":"application/json"}});return P?.divisibility?.value?.divisibility}catch(H){let P=H instanceof Error?H.message:String(H);return console.warn(`Failed to fetch Radix asset decimals for ${A}: ${P}`),T}}async function XT(A){try{let T=await f(I.Chain.Radix);return(await B.post(`${T}/state/entity/details`,{body:JSON.stringify({addresses:[A],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((L)=>L.key==="symbol")?.value.typed.value||void 0}catch(T){let H=T instanceof Error?T.message:String(T);return console.warn(`Failed to fetch Radix asset symbol for ${A}: ${H}`),""}}async function EA({chain:A,address:T,methodHex:H,id:P}){let L=await f(A);return B.post(L,{body:JSON.stringify({id:P,jsonrpc:"2.0",method:"eth_call",params:[{data:H,to:T.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}async function ET(A){if(!A||A==="0x")return"UNKNOWN";try{let{AbiCoder:T}=await import("ethers");return T.defaultAbiCoder().decode(["string"],A)[0].trim()}catch(T){return console.warn(`Failed to decode ABI string from ${A}: ${T}`),"UNKNOWN"}}function wT(A,T){if(!A||A==="0x")return T;try{return Number(A)}catch(H){return console.warn(`Failed to decode ABI uint8 from ${A}: ${H}`),T}}async function QT({chain:A,address:T}){let{baseDecimal:H}=I.getChainConfig(A),P=T.toLowerCase();if(T===""||!P.startsWith("0x"))return H;let L=await EA({address:T,chain:A,id:2,methodHex:"0x313ce567"}).catch((u)=>{return console.warn(`Could not fetch decimals for ${T} on ${A}: ${u.message}`),{result:""}});return wT(L.result,H)}async function xT({chain:A,address:T}){let H=T.toLowerCase();if(H===""||!H.startsWith("0x"))return;let P=await EA({address:T,chain:A,id:1,methodHex:"0x95d89b41"}).catch((F)=>{return console.warn(`Could not fetch symbol for ${T} on ${A}: ${F.message}`),{result:""}});return await ET(P.result)}async function UA({rpcUrl:A,contractAddress:T,functionSelector:H}){return(await B.post(`${A}/wallet/triggerconstantcontract`,{body:JSON.stringify({contract_address:T,function_selector:H,owner_address:T,parameter:"",visible:!0}),headers:{accept:"application/json","content-type":"application/json"}}).catch(()=>{return}))?.constant_result?.[0]}function SA(A){let T=A.match(/.{2}/g)?.map((H)=>Number.parseInt(H,16))??[];return new TextDecoder().decode(new Uint8Array(T))}function bT(A){return r.match(A).with(void 0,()=>{return}).when((T)=>T.length>=128,(T)=>{let H=Number.parseInt(T.slice(64,128),16);return SA(T.slice(128,128+H*2))}).when((T)=>T.length===64,(T)=>{let H=T.replace(/0+$/,"");if(H.length>0&&H.length%2===0)return SA(H);return}).otherwise(()=>{return})}function JN({chain:A,address:T}){let{baseDecimal:H}=I.getChainConfig(A),P={decimals:H,ticker:void 0};return r.match(A).with(...I.EVMChains,async()=>{try{let{isAddress:L,getAddress:F}=await import("ethers");if(!L(F(T.replace(/^0X/,"0x"))))return P;let[u,n]=await Promise.all([xT({address:T,chain:A}),QT({address:T,chain:A})]);return{decimals:n,ticker:u}}catch(L){return console.warn(`Failed to fetch token info for ${T} on ${A}: ${L?.code} ${L?.message}`),P}}).with(I.Chain.Solana,async()=>{if(!T)return P;try{let L=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${T}`);if(L.ok){let F=await L.json(),u=Array.isArray(F)?F[0]:F;if(u)return{decimals:u.decimals??H,ticker:u.symbol||void 0}}}catch(L){console.warn(`Failed to fetch Solana token info for ${T}: ${L?.code} ${L?.message}`)}return P}).with(I.Chain.Tron,async()=>{if(!T)return P;try{let L=await f(I.Chain.Tron),[F,u]=await Promise.all([UA({contractAddress:T,functionSelector:"symbol()",rpcUrl:L}),UA({contractAddress:T,functionSelector:"decimals()",rpcUrl:L})]),n=bT(F);return{decimals:F!==void 0&&u?Number(BigInt(`0x${u}`)):H,ticker:n}}catch(L){let F=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Tron token info for ${T}: ${F}`),P}}).with(I.Chain.Near,async()=>{if(!T)return P;try{let{JsonRpcProvider:L}=await import("@near-js/providers"),F=await f(I.Chain.Near),n=await new L({url:F}).query({account_id:T,args_base64:Buffer.from("{}").toString("base64"),finality:"final",method_name:"ft_metadata",request_type:"call_function"}),O=JSON.parse(Buffer.from(n.result).toString());return{decimals:O?.decimals||H,ticker:O?.symbol}}catch(L){let F=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Near token info for ${T}: ${F}`),P}}).with(I.Chain.Radix,async()=>{if(!T)return P;try{let[L,F]=await Promise.all([XT(T),ST(T)]);return{decimals:F,ticker:L}}catch(L){let F=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Radix token info for ${T}: ${F}`),P}}).otherwise(async()=>P)}function LN({chain:A,symbol:T}){return r.match(A).with(...XA,()=>T==="ETH").with(I.Chain.Avalanche,()=>T==="AVAX").with(I.Chain.Berachain,()=>T==="BERA").with(I.Chain.Hyperevm,()=>T==="HYPE").with(I.Chain.HyperCore,()=>T==="HYPE").with(I.Chain.BinanceSmartChain,()=>T==="BNB").with(I.Chain.Gnosis,()=>T==="xDAI"||T==="XDAI").with(I.Chain.Monad,()=>T==="MON").with(I.Chain.XLayer,()=>T==="OKB").with(I.Chain.Maya,()=>T==="CACAO").with(I.Chain.Cosmos,()=>T==="ATOM").with(I.Chain.THORChain,()=>T==="RUNE").with(I.Chain.Tron,()=>T==="TRX").with(I.Chain.Ripple,()=>T==="XRP").with(I.Chain.Radix,()=>`${A}.${T}`===RN(A).identifier).otherwise(()=>T===A)}var RN=(A)=>{let{baseDecimal:T}=I.getChainConfig(A);return r.match(A.toUpperCase()).with(...XA,(P)=>({decimal:T,identifier:`${P}.ETH`})).with(I.Chain.THORChain,(P)=>({decimal:T,identifier:`${P}.RUNE`})).with(I.Chain.Cosmos,(P)=>({decimal:T,identifier:`${P}.ATOM`})).with(I.Chain.Maya,(P)=>({decimal:10,identifier:`${P}.CACAO`})).with(I.Chain.BinanceSmartChain,(P)=>({decimal:T,identifier:`${P}.BNB`})).with(I.Chain.Monad,(P)=>({decimal:T,identifier:`${P}.MON`})).with(I.Chain.Avalanche,(P)=>({decimal:T,identifier:`${P}.AVAX`})).with(I.Chain.Gnosis,(P)=>({decimal:T,identifier:`${P}.xDAI`})).with(I.Chain.XLayer,(P)=>({decimal:T,identifier:`${P}.OKB`})).with(I.Chain.Berachain,(P)=>({decimal:T,identifier:`${P}.BERA`})).with(I.Chain.Hyperevm,(P)=>({decimal:T,identifier:`${P}.HYPE`})).with(I.Chain.HyperCore,(P)=>({decimal:T,identifier:`${P}.HYPE`})).with(I.Chain.Tron,(P)=>({decimal:T,identifier:`${P}.TRX`})).with(I.Chain.Solana,I.Chain.Chainflip,I.Chain.Kujira,I.Chain.Ripple,I.Chain.Polkadot,I.Chain.Near,...I.UTXOChains,(P)=>({decimal:T,identifier:`${P}.${P}`})).with(I.Chain.Radix,"XRD.XRD",()=>({decimal:T,identifier:"XRD.XRD"})).with(I.Chain.Polygon,"POL.POL",()=>({decimal:T,identifier:"POL.POL"})).with("KUJI.USK",(P)=>({decimal:6,identifier:P})).with("ETH.FLIP",()=>({decimal:I.getChainConfig(I.Chain.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:I.getChainConfig(I.Chain.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:I.getChainConfig(I.Chain.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(P)=>({decimal:10,identifier:P})).with("MAYA.MAYA",(P)=>({decimal:4,identifier:P})).otherwise(()=>({decimal:T,identifier:A}))};function UN({chain:A,symbol:T}){if(T.includes("/"))return"Synth";if(T.includes("~"))return"Trade";return r.match(A).with(I.Chain.Radix,()=>T===I.Chain.Radix||`${A}.${T}`===RN(A).identifier).with(I.Chain.Arbitrum,I.Chain.Optimism,I.Chain.Base,I.Chain.Aurora,()=>T===I.Chain.Ethereum).with(I.Chain.Cosmos,()=>T==="ATOM").with(I.Chain.BinanceSmartChain,()=>T==="BNB").with(I.Chain.Maya,()=>T==="CACAO").with(I.Chain.Monad,()=>T==="MON").with(I.Chain.THORChain,()=>T==="RUNE").with(I.Chain.Tron,()=>T==="TRX").with(I.Chain.Hyperevm,()=>T==="HYPE").with(I.Chain.HyperCore,()=>T==="HYPE").with(I.Chain.XLayer,()=>T==="OKB").otherwise(()=>T===A)?"Native":A}var K=(A)=>{let[T,...H]=A.split("."),P=A.includes("/"),L=H.join("."),F=L?.split("-"),u=F?.length?F.length===1?F[0]:F.slice(0,-1).join("-"):void 0;return{chain:T,symbol:L,synth:P,ticker:u}};function i(A,T){let P=T===I.Chain.Near?A.indexOf("-"):A.lastIndexOf("-");if(P===-1)return{address:void 0,ticker:A};return{address:A.slice(P+1),ticker:A.slice(0,P)}}function zT(A){return`https://storage.googleapis.com/token-list-swapkit-dev/images/${A.toLowerCase()}.png`}async function JT(A){let{loadTokenLists:T}=await import("././tokens.cjs"),H=await T(),P=Object.values(H).flatMap((F)=>F.tokens);if("identifier"in A)return P.find((F)=>F.identifier===A.identifier)?.identifier;let L=A.contract.toLowerCase();for(let F of P){let{chain:u,symbol:n}=K(F.identifier);if(u!==A.chain)continue;let{address:O}=i(n,u);if(O?.toLowerCase()===L)return F.identifier}return}var WT={};x(WT,{validateTNS:()=>VT,validateIdentifier:()=>ZN});var wA=["TERRA",...U.get("chains")];function ZN(A=""){let T=A.toUpperCase(),[H]=T.split(".");if(wA.includes(H))return!0;let[P]=T.split("/");if(wA.includes(P))return!0;throw new $({errorKey:"helpers_invalid_identifier",info:{identifier:A,message:`Invalid identifier: ${A}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}function VT(A){if(A.length>30)return!1;let T=/^[a-zA-Z0-9+_-]+$/g;return!!A.match(T)}var kT={};x(kT,{formatBigIntToSafeValue:()=>m,BigIntArithmetics:()=>k});var FN=require("ts-pattern"),s=8,jT=10;function m({value:A,bigIntDecimal:T=s,decimal:H=s}){if(H===0)return A.toString();let P=A<0n,L=A.toString().substring(P?1:0),F=H-(L.length-1);if(F>0)L="0".repeat(F)+L;let u=L.length-H,n=L.slice(-H);if(Number.parseInt(n[T]||"0",10)>=5){let t=Number.parseInt(n[T-1]||"0",10);n=`${n.substring(0,T-1)}${t+1}`}else n=n.substring(0,T);return`${P?"-":""}${L.slice(0,u)}.${n}`.replace(/\.?0*$/,"")}class k{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(A,T){return new k({decimal:T,value:m({bigIntDecimal:T,decimal:T,value:A})})}static shiftDecimals({value:A,from:T,to:H}){return k.fromBigInt(A.getBaseValue("bigint")*C(H)/C(T),H)}constructor(A){let T=VN(A),H=typeof A==="object";this.decimal=H?A.decimal:void 0,this.decimalMultiplier=H&&"decimalMultiplier"in A?A.decimalMultiplier:C(Math.max(QA(SN(T)),this.decimal||0)),this.#P(T)}set(A){return new this.constructor({decimal:this.decimal,identifier:this.toString?.({includeSynthProtocol:!0}),value:A})}add(...A){return this.#A("add",...A)}sub(...A){return this.#A("sub",...A)}mul(...A){return this.#A("mul",...A)}div(...A){return this.#A("div",...A)}gt(A){return this.#N("gt",A)}gte(A){return this.#N("gte",A)}lt(A){return this.#N("lt",A)}lte(A){return this.#N("lte",A)}eqValue(A){return this.#N("eqValue",A)}getValue(A,T){let H=uN(this.decimalMultiplier),P=T!==void 0?T:this.decimal,L=P!==void 0?P:H;if(P!==void 0&&P<H){if(this.formatBigIntToSafeValue(this.bigIntValue,P)==="0"&&this.bigIntValue!==0n)L=H}let F=this.formatBigIntToSafeValue(this.bigIntValue,L);return FN.match(A).with("number",()=>Number(F)).with("string",()=>F).with("bigint",()=>{return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}).otherwise(()=>F)}getBaseValue(A,T){let H=this.decimalMultiplier/C(T||this.decimal||s),P=qT(this.bigIntValue,H);return FN.match(A).with("number",()=>Number(P)).with("string",()=>P.toString()).otherwise(()=>P)}getBigIntValue(A,T){if(!T&&typeof A==="object")return A.bigIntValue;let H=VN(A),P=SN(H);if(P==="0"||P==="undefined")return 0n;return this.#H(P,T)}toSignificant(A=6){let T=this.getValue("string"),[H="",P=""]=T.split("."),L=Number.parseInt(H,10)>0;if((L?H.length+P.length:P.length)<=A)return T;if(H.length>=A)return H.slice(0,A).padEnd(H.length,"0");if(L)return`${H}.${P.slice(0,A-H.length)}`;let u=Number.parseInt(P,10).toString(),n=u.slice(0,A),O=P.length-u.length;return`0.${n.padStart(O+n.length,"0")}`}toFixed(A=6){let T=this.getValue("string"),H=T.startsWith("-"),[P="0",L=""]=(H?T.slice(1):T).split("."),F=P==="0"&&Number.parseInt(L.slice(0,A),10)===0,u=H&&!F?"-":"";if(A===0){if(P==="0"&&!L)return"0";return L&&Number.parseInt(L[0]||"0",10)>=5?`${u}${BigInt(P)+1n}.0`:`${u}${P}.0`}if(!L)return`${u}${P}.${"0".repeat(A)}`;let n=L[A];if(!(n&&Number.parseInt(n,10)>=5))return`${u}${P}.${L.slice(0,A).padEnd(A,"0")}`;let t=BigInt(L.slice(0,A).padEnd(A,"0"))+1n,X=10n**BigInt(A);if(t>=X)return`${u}${BigInt(P)+1n}.${"0".repeat(A)}`;return`${u}${P}.${t.toString().padStart(A,"0")}`}toAbbreviation(A=2){let T=this.getValue("string"),H=Number(T),P=["","K","M","B","T","Q","Qi","S"],L=Math.floor(Math.log10(Math.abs(H))/3);if(L===0||!P[L])return T;return`${(H/10**(L*3)).toFixed(A)}${P[L]}`}toCurrency(A="$",{currencyPosition:T="start",decimal:H=2,decimalSeparator:P=".",thousandSeparator:L=",",trimTrailingZeros:F=!0}={}){let u=this.toFixed(H),n=T==="end",[O="0",t=""]=u.split("."),X=O.replace(/\B(?=(\d{3})+(?!\d))/g,L),g=t&&Number.parseInt(t,10)>0,V=g?`${X}${P}${t}`:X,j=V.length<100&&F&&g?V.replace(/\.?0*$/,""):V;return n?`${j}${A}`:`${A}${j}`}formatBigIntToSafeValue(A,T){let H=T||this.decimal||s,P=Math.max(H,uN(this.decimalMultiplier));return m({bigIntDecimal:H,decimal:P,value:A})}#A(A,...T){let H=this.#T(this,...T),P=uN(this.decimalMultiplier),F=Math.max(H,P)+jT,u=C(F),n=T.reduce((t,X)=>{let g=this.getBigIntValue(X,F);return FN.match(A).with("add",()=>t+g).with("sub",()=>t-g).with("mul",()=>t*g/u).with("div",()=>{if(g===0n)throw RangeError("Division by zero");return t*u/g}).otherwise(()=>t)},this.bigIntValue*u/this.decimalMultiplier),O=m({bigIntDecimal:F,decimal:F,value:n});return new this.constructor({decimal:this.decimal,decimalMultiplier:C(F),identifier:this.toString(),value:O})}#N(A,...T){let H=this.#T(this,...T),P=this.getBigIntValue(T[0]||"0",H),L=this.getBigIntValue(this,H);return FN.match(A).with("gt",()=>L>P).with("gte",()=>L>=P).with("lt",()=>L<P).with("lte",()=>L<=P).with("eqValue",()=>L===P).otherwise(()=>!1)}#P(A){let T=SN(A)||"0";this.bigIntValue=this.#H(T)}#T(...A){let T=A.map((H)=>{return typeof H==="object"?H.decimal||uN(H.decimalMultiplier):QA(SN(H))}).filter(Boolean);return Math.max(...T,s)}#H(A,T){let H=T?C(T):this.decimalMultiplier,P=uN(H),[L="",F=""]=A.split(".");return BigInt(`${L}${F.padEnd(P,"0")}`)}}var vT=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function SN(A){let H=`${typeof A==="number"?vT.format(A):VN(A)}`.replaceAll(",",".").split(".");return H.length>1?`${H.slice(0,-1).join("")}.${H.at(-1)}`:H[0]||"0"}function QA(A){let T=A.split(".")[1]?.length||0;return Math.max(T,s)}function VN(A){return typeof A==="object"?"getValue"in A?A.getValue("string"):A.value:A}function qT(A,T){if(T===0n)throw Error("Cannot divide by zero");let H=T/2n;return A>=0n&&T>=0n||A<0n&&T<0n?(A+H)/T:(A-H)/T}function C(A){return 10n**BigInt(A)}function uN(A){return Math.log10(Number.parseFloat(A.toString()))}var p=[G.Chain.HyperCore,G.Chain.Near,G.Chain.Ripple,G.Chain.Solana,G.Chain.Sui,G.Chain.Ton,G.Chain.Tron],vN=[G.Chain.THORChain,G.Chain.Maya],e=new Map,XN=new Map,a=new Map,KT=3600000;function mT(A){let T=a.get(A);if(T?.timestamp&&Date.now()-T.timestamp>KT){a.delete(A);return}return T}function pT(A,T){if(a.size>1000){let H=a.keys().next().value;if(H)a.delete(H)}a.set(A,{...T,timestamp:Date.now()})}class z extends k{address;chain;isGasAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:A,decimal:T,tax:H,chain:P,symbol:L,identifier:F}){super(typeof A==="object"?A:{decimal:T,value:A});let u=xA(F||`${P}.${L}`);this.type=UN(u),this.tax=H,this.chain=u.chain,this.ticker=u.ticker,this.symbol=u.symbol,this.address=u.address,this.isSynthetic=u.isSynthetic,this.isTradeAsset=u.isTradeAsset,this.isGasAsset=u.isGasAsset,this.chainId=G.getChainConfig(u.chain).chainId}toString({includeSynthProtocol:A}={}){return(this.isSynthetic||this.isTradeAsset)&&!A?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 A=this.symbol.replace(/\./g,"__");return`${this.chain}.${A}`}getIconUrl(){return e.get(this.toString())?.logoURI}eqAsset({chain:A,symbol:T}){return this.chain===A&&this.symbol===T}eq(A){return this.eqAsset(A)&&this.eqValue(A)}static fromUrl(A,T=0){let H=A.indexOf(".");if(H===-1)throw new $({errorKey:"helpers_invalid_asset_url",info:{urlAsset:A}});let P=A.slice(0,H),L=A.slice(H+1),F=EN.match({chain:P,rest:L}).when(({rest:u})=>u.includes(".."),({chain:u,rest:n})=>`${u}.${n.replace(/\.\./g,"~")}`).when(({chain:u,rest:n})=>vN.includes(u)&&n.includes("."),({chain:u,rest:n})=>`${u}.${n.replace(/\./g,"/")}`).otherwise(({chain:u,rest:n})=>`${u}.${n.replace(/__/g,".")}`);return z.from({asset:F,value:T})}static from({value:A=0,fromBaseDecimal:T,asyncTokenLookup:H,...P}){let L=A instanceof k?A.getValue("string"):A,F="address"in P&&"chain"in P,u=hT(P);if(u===null&&H&&F){let{chain:PN,address:c}=P;return fT({address:c,chain:PN,fromBaseDecimal:T,parsedValue:L})}let n=F&&!u?`${P.chain}.UNKNOWN-${P.address}`:u,{identifier:O,decimal:t}=RN(n),{chain:X,isSynthetic:g,isTradeAsset:V,address:D}=xA(O),{baseDecimal:j}=G.getChainConfig(X),E=e.get(p.includes(X)?O:O.toUpperCase());if(!E&&H&&!g&&!V)return(async()=>{let{ticker:PN}=K(O),c=await bA({address:D,chain:X,ticker:PN});return jN({decimal:c.decimals,identifier:c.identifier,value:T?NN(BigInt(L),T):L})})();let w=E?.decimal||t;o({condition:!w&&!H,id:`assetValue_static_decimal_not_found_${X}`,warning:`Couldn't find static decimal for one or more tokens on ${X} (Using default ${j} decimal as fallback).
2
- This can result in incorrect calculations and mess with amount sent on transactions.
3
- You can load static assets by installing @swapkit/tokens package and calling AssetValue.loadStaticAssets()
4
- or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`});let{decimal:HN,identifier:Y,tax:BN}=E||{decimal:w||j,identifier:O},ON=T?NN(BigInt(L),T):NN(L,HN);return g||V?oT(Y,ON):jN({decimal:HN,identifier:Y,tax:BN,value:ON})}static async loadStaticAssets(A){let{loadTokenLists:T}=await import("@swapkit/tokens"),H=await T(A);for(let{tokens:P}of Object.values(H))for(let L of P){let{identifier:F}=L,{chain:u,symbol:n}=K(F),{address:O}=i(n,u),{baseDecimal:t}=G.getChainConfig(u),X=p.includes(u)?F:F.toUpperCase(),g="decimals"in L&&L.decimals!==void 0?L.decimals:t,V="logoURI"in L&&L.logoURI?L.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${F.toLowerCase()}.png`,D={decimal:g,identifier:F,logoURI:V,tax:"tax"in L?L.tax:void 0};if(e.set(X,D),O){let j=p.includes(u)?`${u}:${O}`:`${u}:${O.toUpperCase()}`;XN.set(j,F)}}return!0}static setStaticAssets(A){e.clear(),XN.clear();for(let[T,H]of A.entries()){let{identifier:P}=H,{chain:L,symbol:F}=K(P),{address:u}=i(F,L),{baseDecimal:n}=G.getChainConfig(L),O=H.chain??L,t=H.address??u,X=p.includes(O)?P:P.toUpperCase(),g=H.decimals??H.decimal??n,V=H.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${P.toLowerCase()}.png`,D={decimal:g,identifier:X,logoURI:V,tax:H.tax};if(e.set(X,D),t){let j=p.includes(O)?`${O}:${t}`:`${O}:${t.toUpperCase()}`;XN.set(j,P)}}return!0}static get staticAssets(){return e}}function yT(A){let T=z.from({chain:A});return EN.match(A).with(G.Chain.Bitcoin,G.Chain.Litecoin,G.Chain.BitcoinCash,G.Chain.Dash,()=>T.set(0.00010001)).with(G.Chain.Dogecoin,()=>T.set(1.00000001)).with(G.Chain.Avalanche,G.Chain.Ethereum,G.Chain.Arbitrum,G.Chain.BinanceSmartChain,()=>T.set(0.00000001)).with(G.Chain.THORChain,G.Chain.Maya,()=>T.set(0)).with(G.Chain.Cosmos,G.Chain.Kujira,()=>T.set(0.000001)).otherwise(()=>T.set(0.00000001))}async function bA({chain:A,address:T,ticker:H}){let L=p.includes(A)?`${A}:${T||H}`:`${A}:${T||H}`.toUpperCase(),F=mT(L);if(F)return F;if(!T){let{baseDecimal:O}=G.getChainConfig(A);return{decimals:O,identifier:`${A}.${H||"UNKNOWN"}`}}let u=await JN({address:T,chain:A}),n=`${A}.${u.ticker||H||"UNKNOWN"}-${T}`;return o({condition:!!(!u.ticker&&H),id:`async_token_lookup_failed_${A}_${T}`,warning:`Could not fetch token metadata for ${A}:${T} from chain. Using user-provided ticker (${H}) with baseDecimal (${u.decimals}).`}),u.ticker&&pT(L,{decimals:u.decimals,identifier:n}),{decimals:u.decimals,identifier:n}}function jN({identifier:A,decimal:T,value:H,tax:P}){return ZN(A),new z({decimal:T,identifier:A,tax:P,value:NN(H,T)})}function oT(A,T=0){let H=A.includes(".")?A.split(".")?.[0]?.toUpperCase():void 0,P=H?vN.includes(H):!1,L=A.slice(0,14).includes("~")?"~":"/",[F,u]=P?A.split(".").slice(1).join().split(L):A.split(L);if(!(F&&u))throw new $({errorKey:"helpers_invalid_asset_identifier",info:{identifier:A}});return new z({decimal:8,identifier:`${H||G.Chain.THORChain}.${F}${L}${u}`,value:NN(T,8)})}async function fT({address:A,chain:T,fromBaseDecimal:H,parsedValue:P}){let{decimals:L,identifier:F}=await bA({address:A,chain:T}),u=H?NN(BigInt(P),H):P;return jN({decimal:L,identifier:F,value:u})}function NN(A,T){return typeof A==="bigint"?m({bigIntDecimal:T,decimal:T,value:A}):A}function CT(A){let T=EN.match(A).when((H)=>("chain"in H)&&H.chain!==void 0,({chain:H})=>H).otherwise((H)=>{let P=K(H.asset);return P.synth?G.Chain.THORChain:P.chain});if(!G.AllChains.includes(T.toUpperCase())){let H="asset"in A?A.asset:T;throw new $({errorKey:"helpers_invalid_asset_identifier",info:{identifier:H,message:`Unsupported chain "${T}" - use the AssetValue constructor directly`}})}}function hT(A){if(CT(A),"chain"in A){let{chain:L,address:F}=A;if(F){let u=p.includes(L)?`${L}:${F}`:`${L}:${F.toUpperCase()}`,n=XN.get(u);if(n)return n;return null}return L}let{chain:T,symbol:H}=K(A.asset);return UN({chain:T,symbol:H})==="Native"?T:A.asset}function dT(A,T,H){let P=A.split("."),L=P[0]?.toUpperCase(),F=vN.includes(L),u=H?"~":"/",[n,O=""]=F?P.slice(1).join(".").split(u):A.split(u);if(!(n&&O))throw new $({errorKey:"helpers_invalid_asset_identifier",info:{identifier:A}});let{ticker:t,address:X}=zA({chain:n,symbol:O}),g=`${n}${u}${O}`;return{address:X,chain:L,isGasAsset:!1,isSynthetic:T,isTradeAsset:H,symbol:g,ticker:t}}function cT(A){let T=A.indexOf("."),H=(T===-1?A:A.slice(0,T)).toUpperCase(),P=T===-1?A:A.slice(T+1),{address:L,ticker:F}=zA({chain:H,symbol:P}),u;try{u=L&&G.EVMChains.includes(H)&&WN.getAddress(L)?WN.getAddress(L):L}catch{u=L}let n=u?`${F}-${u}`:P;return{address:u,chain:H,isGasAsset:LN({chain:H,symbol:P}),isSynthetic:!1,isTradeAsset:!1,symbol:n,ticker:F}}function xA(A){let T=A.slice(0,14),H=T.includes("/"),P=T.includes("~");if(H||P)return dT(A,H,P);return cT(A)}function zA({symbol:A,chain:T}){let{ticker:H,address:P}=i(A,T);return{address:P&&!p.includes(T)?P.toLowerCase():P,ticker:H}}var rT={};x(rT,{SwapKitNumber:()=>IN});class IN extends k{eq(A){return this.eqValue(A)}static fromBigInt(A,T){return new IN({decimal:T,value:m({bigIntDecimal:T,decimal:T,value:A})})}}function JA(A=!0){return A?"https://midgard.thorchain.network":"https://midgard.mayachain.info"}function iT(A=!0){let T=JA(A);return A?`${T}/v2/thorname`:`${T}/v2/mayaname`}function sT(A){return function(H){let P=H?`?status=${H}`:"";return B.get(`${A}/v2/pools${P}`)}}function eT(A){return function(H){return B.get(`${A}/v2/pool/${H}`)}}function aT(A){return function(H,P){let L=P?`?period=${P}`:"";return B.get(`${A}/v2/pool/${H}/stats${L}`)}}function NH(A){return function(H,P){let L=new URLSearchParams;if(P?.interval)L.append("interval",P.interval);if(P?.count)L.append("count",P.count.toString());if(P?.from)L.append("from",P.from.toString());if(P?.to)L.append("to",P.to.toString());let F=L.toString()?`?${L.toString()}`:"";return B.get(`${A}/v2/history/depths/${H}${F}`)}}function AH(A){return function(){return B.get(`${A}/v2/network`)}}function TH(A){return function(){return B.get(`${A}/v2/health`)}}function HH(A){return function(){return B.get(`${A}/v2/nodes`)}}function PH(A){return function(H){return B.get(`${A}/v2/node/${H}`)}}function LH(A){return function(){return B.get(`${A}/v2/mimir/votes`)}}function RH(A){return function(){return B.get(`${A}/v2/mimir`)}}function uH(A){return function(){return B.get(`${A}/v2/constants`)}}function FH(A){return function(){return B.get(`${A}/v2/stats`)}}function IH(A){return function(H){let P=new URLSearchParams;if(H?.interval)P.append("interval",H.interval);if(H?.count)P.append("count",H.count.toString());if(H?.from)P.append("from",H.from.toString());if(H?.to)P.append("to",H.to.toString());let L=P.toString()?`?${P.toString()}`:"";return B.get(`${A}/v2/history/earnings${L}`)}}function nH(A){return function(H,P){let L=new URLSearchParams;if(P?.interval)L.append("interval",P.interval);if(P?.count)L.append("count",P.count.toString());if(P?.from)L.append("from",P.from.toString());if(P?.to)L.append("to",P.to.toString());let F=L.toString()?`?${L.toString()}`:"",u=H?`/swaps/${H}`:"/swaps";return B.get(`${A}/v2/history${u}${F}`)}}function BH(A){return function(H){let P=new URLSearchParams;if(H?.interval)P.append("interval",H.interval);if(H?.count)P.append("count",H.count.toString());if(H?.from)P.append("from",H.from.toString());if(H?.to)P.append("to",H.to.toString());let L=P.toString()?`?${P.toString()}`:"";return B.get(`${A}/v2/history/tvl${L}`)}}function OH(A){if(!A)return"";let T=new URLSearchParams,H=(P,L)=>{if(L!==void 0)T.append(P,typeof L==="number"?L.toString():L)};return H("address",A.address),H("txid",A.txid),H("asset",A.asset),H("type",A.type),H("affiliate",A.affiliate),H("limit",A.limit),H("offset",A.offset),T.toString()?`?${T.toString()}`:""}function $H(A){return function(H){let P=OH(H);return B.get(`${A}/v2/actions${P}`)}}function GH(A){return function(H){return B.get(`${A}/v2/member/${H}`)}}function gH(A){return function(H){let P=H?`/${H}`:"";return B.get(`${A}/v2/members${P}`)}}function MH(A){return function(H,P){let L=P?`&asset=${P}`:"";return B.get(`${A}/v2/saver/${H}${L?`?${L.substring(1)}`:""}`)}}function tH(A){return function(H){return B.get(`${A}/v2/savers/${H}`)}}function _H(A){return function(H,P){let L=new URLSearchParams;if(P?.interval)L.append("interval",P.interval);if(P?.count)L.append("count",P.count.toString());if(P?.from)L.append("from",P.from.toString());if(P?.to)L.append("to",P.to.toString());let F=L.toString()?`?${L.toString()}`:"",u=H?`/savers/${H}`:"/savers";return B.get(`${A}/v2/history${u}${F}`)}}function DH(A){return function(H){return B.get(`${A}/v2/balance/${H}`)}}function YH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return;throw L};return await B.get(`${A}/lookup/${H}`,{onError:P,retry:{maxRetries:1}})}}function UH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return[];throw L};return await B.get(`${A}/rlookup/${H}`,{onError:P,retry:{maxRetries:1}})}}function SH(A){return async function(H){let P=(L)=>{if(L?.cause?.status===404)return[];throw L};return await B.get(`${A}/owner/${H}`,{onError:P,retry:{maxRetries:1}})}}function AN({asset:A,value:T}){return z.from({asset:A,fromBaseDecimal:h.getChainConfig(h.Chain.THORChain).baseDecimal,value:T})}function XH({liquidityPositionGetter:A,isThorchain:T}){return async function(P){let L=await A(P),F=T?"rune":"cacao";return L.pools.map((u)=>({[`${F}Pending`]:AN({asset:"THOR.RUNE",value:u.runePending}),[`${F}RegisteredAddress`]:u.runeAddress,[`${F}Withdrawn`]:AN({asset:"THOR.RUNE",value:u.runeWithdrawn}),[F]:AN({asset:"THOR.RUNE",value:u.runeAdded}),asset:AN({asset:u.pool,value:u.assetAdded}),assetPending:AN({asset:u.pool,value:u.assetPending}),assetRegisteredAddress:u.assetAddress,assetWithdrawn:AN({asset:u.pool,value:u.assetWithdrawn}),dateFirstAdded:u.dateFirstAdded,dateLastAdded:u.dateLastAdded,poolShare:new IN(u.liquidityUnits).div(u.pool)}))}}function ZA(A){let T=A===h.Chain.THORChain,H=JA(T),P=iT(T),L=GH(H);return{getActions:$H(H),getBalance:DH(H),getConstants:uH(H),getEarningsHistory:IH(H),getHealth:TH(H),getLiquidityPosition:XH({isThorchain:T,liquidityPositionGetter:L}),getLiquidityPositionRaw:L,getMembers:gH(H),getMimir:RH(H),getMimirVotes:LH(H),getNameDetails:YH(P),getNamesByAddress:UH(P),getNamesByOwner:SH(P),getNetworkInfo:AH(H),getNode:PH(H),getNodes:HH(H),getPool:eT(H),getPoolDepthHistory:NH(H),getPoolStats:aT(H),getPools:sT(H),getSaverDetails:MH(H),getSavers:tH(H),getSaversHistory:_H(H),getStats:FH(H),getSwapHistory:nH(H),getTVLHistory:BH(H)}}var VA=ZA(h.Chain.THORChain),WA=ZA(h.Chain.Maya);var uA={};x(uA,{getTrackerDetails:()=>PP,getTokenListProviders:()=>IP,getTokenList:()=>nP,getTokenApproval:()=>FP,getSwapTo:()=>_P,getSwapQuote:()=>LP,getRouteWithTx:()=>RP,getPrice:()=>BP,getNearDepositChannel:()=>GP,getGasRate:()=>OP,getChainflipDepositChannel:()=>$P,getChainBalance:()=>uP,SKRequestClient:()=>Z});var cA=require("@swapkit/types"),y=require("ts-pattern");var EH={};x(EH,{signWidgetRequest:()=>qN});async function qN(A,T,H){let P=`${T}:${H}`,L=new TextEncoder,F=await crypto.subtle.importKey("raw",L.encode(A),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),u=await crypto.subtle.sign("HMAC",F,L.encode(P));return Array.from(new Uint8Array(u)).map((n)=>n.toString(16).padStart(2,"0")).join("")}var v=require("@swapkit/types"),N=require("zod/v4");var KN;((P)=>{P.CHEAPEST="CHEAPEST";P.FASTEST="FASTEST";P.RECOMMENDED="RECOMMENDED"})(KN||={});var nN;((L)=>{L.PSBT="PSBT";L.EVM="EVM";L.COSMOS="COSMOS";L.RADIX="RADIX"})(nN||={});var mN;((w)=>{w.approve="approve";w.claim="claim";w.deposit="deposit";w.donate="donate";w.lending="lending";w.lp_action="lp_action";w.native_contract_call="native_contract_call";w.native_send="native_send";w.stake="stake";w.streaming_swap="streaming_swap";w.swap="swap";w.thorname_action="thorname_action";w.token_contract_call="token_contract_call";w.token_transfer="token_transfer";w.unknown="unknown";w.unstake="unstake"})(mN||={});var pN;((D)=>{D.swap="swap";D.aggregation="aggregation";D.addLiquidity="addLiquidity";D.withdrawLiquidity="withdrawLiquidity";D.addSavers="addSavers";D.withdrawSavers="withdrawSavers";D.borrow="borrow";D.repay="repay";D.name="name";D.donate="donate";D.claim="claim";D.stake="stake";D.unstake="unstake"})(pN||={});var yN;((n)=>{n.unknown="unknown";n.not_started="not_started";n.pending="pending";n.swapping="swapping";n.completed="completed";n.refunded="refunded";n.failed="failed"})(yN||={});var oN;((E)=>{E.not_started="not_started";E.starting="starting";E.broadcasted="broadcasted";E.mempool="mempool";E.inbound="inbound";E.outbound="outbound";E.swapping="swapping";E.completed="completed";E.refunded="refunded";E.partially_refunded="partially_refunded";E.dropped="dropped";E.reverted="reverted";E.replaced="replaced";E.retries_exceeded="retries_exceeded";E.parsing_error="parsing_error"})(oN||={});var wH=N.object({address:N.optional(N.string()),chain:N.z.enum(v.Chain).optional(),chainId:N.z.enum(v.ChainId),coingeckoId:N.optional(N.string()),decimals:N.coerce.number(),extensions:N.optional(N.z.looseObject({})),identifier:N.string(),logoURI:N.optional(N.string()),name:N.optional(N.string()),shortCode:N.optional(N.string()),symbol:N.optional(N.string()),ticker:N.string()}),QH=N.z.object({block:N.z.optional(N.z.number().describe("Block number. Required for Polkadot chain. e.g. `123456`")),chainId:N.z.optional(N.z.string().describe("ChainId for the hash. e.g. `thorchain-1`")),depositChannelId:N.z.optional(N.z.string().describe("Deposit channel ID, required for Chainflip if tx was broadcasted without wallet connection")),hash:N.z.optional(N.z.string().describe("Hash for the first transaction broadcasted by the end user. e.g. `88D1819378ECD09E5284C54937CDC1E99B52F253C007617A02DD1200710CE677`"))}).refine((A)=>A.hash&&A.chainId||A.depositChannelId,{message:"Either `hash` and `chainId` or `depositChannelId` must be provided"}),xH=N.z.object({forceUpdate:N.z.string().toLowerCase().transform((A)=>A==="true").pipe(N.z.boolean()).optional()}),bH=N.object({error:N.string(),message:N.string()}),d=N.object({address:N.optional(N.string()),chain:N.z.enum(v.Chain),decimal:N.optional(N.number()),isGasAsset:N.boolean(),isSynthetic:N.boolean(),symbol:N.string(),tax:N.optional(N.object({buy:N.number(),sell:N.number()})),ticker:N.string()}),fN=N.object({id:N.string(),market_cap:N.number(),name:N.string(),price_change_24h_usd:N.number(),price_change_percentage_24h_usd:N.number(),sparkline_in_7d:N.array(N.number()),timestamp:N.string(),total_volume:N.number()}).partial(),zH=N.object({cg:N.optional(fN),identifier:N.string(),price_usd:N.number(),provider:N.string(),timestamp:N.number()}),CN=N.array(N.object({cg:N.optional(fN),identifier:N.string(),price_usd:N.number(),provider:N.string(),timestamp:N.number()}).partial()),JH=N.object({affiliate:N.optional(N.string().describe("Affiliate thorname")),affiliateFee:N.optional(N.number().describe("Affiliate fee in basis points").refine((A)=>A===Math.floor(A)&&A>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:N.optional(N.boolean().describe("Allow smart contract as recipient")),allowSmartContractSender:N.optional(N.boolean().describe("Allow smart contract as sender")),buyAsset:N.string().describe("Asset to buy"),cfBoost:N.optional(N.boolean().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:N.optional(N.string().describe("Address to send asset to")),disableSecurityChecks:N.optional(N.boolean().describe("Disable security checks")),includeTx:N.optional(N.boolean().describe("Set to true to include an transaction object (EVM only)")),providers:N.optional(N.array(N.string().describe("List of providers to use").refine((A)=>Q[A]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:N.optional(N.string().describe("Referrer address (referral program)")),sellAmount:N.string().describe("Amount of asset to sell").refine((A)=>+A>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:N.string().describe("Asset to sell"),slippage:N.optional(N.number().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:N.optional(N.string().describe("Address to send asset from"))}).refine((A)=>A.sellAsset!==A.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),ZH=N.object({metadata:N.boolean(),tokens:N.array(N.object({identifier:N.string()}))}),hN=N.object({destinationAddress:N.string()}),qA=hN.extend({affiliateFees:N.array(N.object({brokerAddress:N.string(),feeBps:N.number()})).optional(),brokerCommissionBps:N.number().optional(),buyAsset:N.object({asset:N.string(),chain:N.string()}),channelMetadata:N.object({cfParameters:N.string().optional(),gasBudget:N.string().optional(),message:N.string().optional()}).optional(),dcaParameters:N.object({chunkInterval:N.number().optional(),numberOfChunks:N.number().optional()}).optional(),maxBoostFeeBps:N.number().optional(),refundParameters:N.object({minPrice:N.string().optional(),refundAddress:N.string().optional(),retryDuration:N.number().optional()}).optional(),sellAsset:N.object({asset:N.string(),chain:N.string()})}),dN=N.object({channelId:N.string(),depositAddress:N.string()}),kN=hN.extend({affiliateFees:N.object({feeBps:N.number(),nearId:N.string()}).optional(),buyAsset:N.string(),sellAmount:N.string(),sellAsset:N.string(),slippage:N.coerce.number(),sourceAddress:N.string()}),jA=N.object({amountIn:N.string(),amountInFormatted:N.string(),amountInUsd:N.string(),amountOut:N.string(),amountOutFormatted:N.string(),amountOutUsd:N.string(),deadline:N.string().optional(),minAmountIn:N.string(),minAmountOut:N.string(),timeEstimate:N.number().optional(),timeWhenInactive:N.string().optional()}),VH=jA.extend({depositAddress:N.string(),quote:jA,signature:N.string(),timestamp:N.string(),tx:N.unknown()}),cN=N.object({buyAsset:N.string(),buyAssetAmount:N.string(),buyAssetAmountMaxSlippage:N.string(),deadline:N.string().optional(),depositAddress:N.string(),depositAmount:N.string(),depositAsset:N.string(),tx:N.unknown()}),WH=N.object({evmCalldata:N.z.optional(N.z.string()),intentHash:N.z.optional(N.z.string()),logs:N.z.optional(N.z.unknown()),manifest:N.z.optional(N.z.unknown()),memo:N.z.optional(N.z.string()),spender:N.z.optional(N.z.string()),thorname:N.z.optional(N.z.string())}),jH=N.object({currentStage:N.string(),inboundConfirmation:N.number(),inboundObservation:N.number(),outboundDelay:N.number(),outboundObservation:N.number(),streamingSwap:N.number()}),vH=N.object({count:N.optional(N.number()),interval:N.optional(N.number()),quantity:N.optional(N.number()),subSwapsMap:N.optional(N.array(N.number()))}),qH=N.z.object({currentLegIndex:N.z.optional(N.z.number()),estimatedTimeToComplete:N.z.number(),estimates:N.z.optional(jH),providerDetails:N.z.optional(N.z.object({streamingDetails:N.z.optional(vH)}))}),kH=N.object({affiliate:N.optional(d),liquidity:N.optional(d),network:N.optional(d),protocol:N.optional(d),tax:N.optional(d)}),KH=N.object({affiliate:N.string(),bps:N.string(),isReferrer:N.boolean()}),mH=N.object({affiliate:N.optional(N.string()),affiliateFees:N.optional(N.array(KH)),broadcastedAt:N.optional(N.number()),explorerUrl:N.optional(N.string()),fees:N.optional(kH),images:N.optional(N.object({chain:N.optional(N.string()),from:N.optional(N.string()),provider:N.optional(N.string()),to:N.optional(N.string())})),provider:N.optional(N.z.enum(Q)),providerAction:N.z.optional(N.z.enum(pN)),quoteId:N.optional(N.string()),wallet:N.optional(N.string())}),TN=N.z.object({block:N.z.number(),chainId:N.z.enum(v.ChainId),finalAddress:N.z.optional(N.z.string()),finalAsset:N.z.optional(d),finalisedAt:N.z.number(),fromAddress:N.z.string(),fromAmount:N.z.string(),fromAsset:N.z.string(),hash:N.z.string(),meta:N.z.optional(mH),payload:N.z.optional(WH),status:N.z.enum(yN),toAddress:N.z.string(),toAmount:N.z.string(),toAsset:N.z.string(),trackingStatus:N.z.optional(N.z.enum(oN)),transient:N.z.optional(qH),type:N.z.enum(mN)}),lN=TN.extend({legs:N.z.array(TN)}),pH=TN.extend({legs:N.array(TN)}),yH=TN.extend({legs:N.array(TN)}),wN=N.array(N.object({amount:N.string(),asset:N.string(),chain:N.string(),protocol:N.z.enum(Q),type:N.z.enum(MN)})),QN=N.z.object({inbound:N.z.optional(N.z.number().describe("Time to receive inbound asset in seconds")),outbound:N.z.optional(N.z.number().describe("Time to receive outbound asset in seconds")),swap:N.z.optional(N.z.number().describe("Time to swap assets in seconds")),total:N.z.number().describe("Total time in seconds")}),rN=N.object({data:N.string().describe("Data to send"),from:N.string().describe("Address of the sender"),to:N.string().describe("Address of the recipient"),value:N.string().describe("Value to send")}),iN=N.z.object({raw_data:N.z.object({contract:N.z.any(),data:N.z.string().optional(),expiration:N.z.number(),fee_limit:N.z.number().optional(),ref_block_bytes:N.z.string(),ref_block_hash:N.z.string(),timestamp:N.z.number()}).passthrough(),raw_data_hex:N.z.string(),txID:N.z.string(),visible:N.z.boolean()}),kA=N.array(N.union([N.string(),N.number(),N.array(N.string()),N.object({from:N.string(),value:N.string()}).describe("Parameters to pass to the contract method")])),oH=N.object({approvalSpender:N.optional(N.string().describe("Address of the spender to approve")),approvalToken:N.optional(N.string().describe("Address of the token to approve spending of")),contractAddress:N.string().describe("Address of the contract to interact with"),contractMethod:N.string().describe("Name of the method to call"),contractParamNames:N.array(N.string().describe("Names of the parameters to pass to the contract method")),contractParams:kA}),fH=N.object({typeUrl:N.string("/types.MsgDeposit"),value:N.object({coins:N.array(N.object({amount:N.string(),asset:N.object({chain:N.string(),symbol:N.string(),synth:N.boolean(),ticker:N.string()})})),memo:N.string(),signer:N.string()})}),CH=N.object({typeUrl:N.string("/types.MsgSend"),value:N.object({amount:N.array(N.object({amount:N.string(),denom:N.string()})),fromAddress:N.string(),toAddress:N.string()})}),hH=N.object({typeUrl:N.string(),value:CH.or(fH)}),dH=N.object({amount:N.array(N.object({amount:N.string(),denom:N.string()})),gas:N.string()}),sN=N.object({accountNumber:N.number(),chainId:N.z.enum(v.ChainId),fee:dH,memo:N.string(),msgs:N.array(hH),sequence:N.number()}),KA=N.z.array(N.z.object({calldata:N.z.array(N.z.string()),contractAddress:N.z.string(),entrypoint:N.z.string()})),eN=N.z.array(N.z.object({address:N.z.string().describe("Destination address in friendly format"),amount:N.z.string().describe("Amount in nanotons"),payload:N.z.string().optional().describe("Base64 BOC of body cell"),stateInit:N.z.string().optional().describe("Base64 BOC of state init")})),mA=N.object({affiliate:N.string().describe("Affiliate address").optional(),affiliateFee:N.number().describe("Affiliate fee").optional(),buyAsset:N.string().describe("Asset to buy"),destinationAddress:N.string().describe("Destination address"),estimatedTime:QN.optional(),provider:N.z.enum(Q),sellAsset:N.string().describe("Asset to sell"),slipPercentage:N.number().describe("Slippage as a percentage"),sourceAddress:N.string().describe("Source address")}),cH=mA.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),pA=N.object({asset:N.string().describe("Asset name"),image:N.string().describe("Asset image"),price:N.number().describe("Price in USD")}),yA=qA,aN=N.object({assets:N.optional(N.array(pA)),maxStreamingQuantity:N.number().optional(),referrer:N.string().optional(),streamingInterval:N.number().optional(),tags:N.array(N.z.enum(KN))}),NA=aN.extend({affiliate:N.optional(N.string()),affiliateFee:N.optional(N.string()),approvalAddress:N.optional(N.string().describe("Approval address for swap")),chainflip:yA.optional(),garden:kN.optional(),near:kN.optional(),priceImpact:N.optional(N.number().describe("Price impact")),referrer:N.optional(N.string()),txType:N.optional(N.z.enum(nN))}),AA=N.array(N.object({code:N.z.enum(gN),display:N.string(),tooltip:N.string().optional()})),lH=N.object({buyAmount:N.string().describe("Buy amount"),buyAmountMaxSlippage:N.string().describe("Buy amount max slippage"),buyAsset:N.string().describe("Asset to buy"),fees:N.optional(wN),provider:N.z.enum(Q),sellAmount:N.string().describe("Sell amount"),sellAsset:N.string().describe("Asset to sell")}),oA=N.object({buyAsset:N.string().describe("Asset to buy"),destinationAddress:N.optional(N.string().describe("Destination address")),estimatedTime:N.optional(QN),expectedBuyAmount:N.string().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:N.string().describe("Expected Buy amount max slippage"),expiration:N.optional(N.string().describe("Expiration")),fees:wN,inboundAddress:N.optional(N.string().describe("Inbound address")),legs:N.array(lH),memo:N.optional(N.string().describe("Memo")),meta:NA,providers:N.array(N.z.enum(Q)),routeId:N.string().describe("Route ID"),sellAmount:N.string().describe("Sell amount"),sellAsset:N.string().describe("Asset to sell"),sourceAddress:N.optional(N.string().describe("Source address")),targetAddress:N.optional(N.string().describe("Target address")),totalSlippageBps:N.number().describe("Total slippage in bps"),tx:N.optional(N.union([rN,sN,iN,KA,eN,N.string()])),txType:N.optional(N.z.enum(nN)),warnings:AA}),TA=N.object({error:N.optional(N.string().describe("Error message")),providerErrors:N.optional(N.array(N.object({errorCode:N.optional(N.z.enum(l)),message:N.optional(N.string()),provider:N.z.enum(Q).optional()}))),quoteId:N.string().describe("Quote ID"),routes:N.array(oA)}),HA=N.z.object({chainId:N.z.enum(v.ChainId),createdAt:N.z.date(),id:N.z.number(),unit:N.z.string(),value:N.z.string()}),rH=N.z.array(HA),PA=N.z.union([HA,rH]),OL=N.array(N.object({chain:N.z.enum(v.Chain),decimal:N.number(),identifier:N.string(),symbol:N.string(),ticker:N.string(),value:N.string()})),iH=N.z.union([N.z.object({amount:N.z.string(),spender:N.z.string(),tokenIdentifier:N.z.string(),userWalletAddress:N.z.string()}),N.z.object({amount:N.z.string(),chainId:N.z.enum(v.ChainId),spender:N.z.string(),tokenContractAddress:N.z.string(),userWalletAddress:N.z.string()}),N.z.object({routeId:N.z.string()})]),sH=N.z.object({approvalTransaction:N.z.optional(N.z.object({data:N.z.string(),from:N.z.string(),gasLimit:N.z.optional(N.z.string()),gasPrice:N.z.optional(N.z.string()),to:N.z.string(),value:N.z.string()})),approvedAmount:N.z.string(),isApproved:N.z.boolean()}),fA=N.z.object({data:N.z.string().describe("Encoded approval call data"),from:N.z.string().describe("User wallet address"),gasLimit:N.z.string().optional().describe("Estimated gas limit"),gasPrice:N.z.string().optional().describe("Current gas price"),to:N.z.string().describe("Token contract address"),value:N.z.string().describe("ETH value (always '0' for approvals)")}),vA=N.z.object({buyAmount:N.z.string().describe("Buy amount"),buyAmountMaxSlippage:N.z.string().describe("Buy amount max slippage"),buyAsset:N.z.string().describe("Asset to buy"),expectedBuyAmount:N.z.string().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:N.z.string().describe("Expected Buy amount max slippage"),fees:wN,provider:N.z.enum(Q),sellAmount:N.z.string().describe("Sell amount"),sellAsset:N.z.string().describe("Asset to sell")}),CA=vA.extend({estimatedTime:N.z.optional(QN),expiration:N.z.optional(N.z.string().describe("Expiration")),legs:N.z.array(vA),providers:N.z.array(N.z.enum(Q)),routeId:N.z.string().describe("Route ID"),totalSlippageBps:N.z.number().describe("Total slippage in bps"),warnings:AA}).omit({provider:!0}),eH=N.z.object({method:N.z.string(),payload:N.z.optional(N.z.unknown()),url:N.z.string()}),aH=CA.extend({meta:aN,nextActions:N.z.optional(N.z.array(eH))}),NP=N.z.object({error:N.z.optional(N.z.string().describe("Error message")),providerErrors:N.z.optional(N.z.array(N.z.object({errorCode:N.z.optional(N.z.enum(l)),message:N.z.optional(N.z.string()),provider:N.z.enum(Q).optional()}))),quoteId:N.z.string().describe("Quote ID"),routes:N.z.array(aH)}),AP=N.z.object({providers:N.z.array(N.z.enum(Q)).optional().describe("Optional list of providers to query for trading pairs"),sellAsset:N.z.string().describe("Asset identifier to sell (e.g., 'BTC.BTC' or 'ETH.ETH')")}),hA=N.z.object({chain:N.z.enum(v.Chain).describe("Chain the asset is on"),identifier:N.z.string().describe("Asset identifier (e.g., 'ETH.USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')"),providers:N.z.array(N.z.enum(Q)).describe("Providers that support this trading pair"),symbol:N.z.string().describe("Asset symbol"),ticker:N.z.string().describe("Asset ticker")}),TP=N.z.object({buyAssets:N.z.array(hA).describe("List of assets that can be swapped to"),sellAsset:N.z.string().describe("The input sell asset identifier")}),LA=CA.extend({destinationAddress:N.z.string().describe("Destination address"),inboundAddress:N.z.optional(N.z.string().describe("Inbound address")),memo:N.z.optional(N.z.string().describe("Memo to include in the transaction")),meta:NA,sourceAddress:N.z.string().describe("Source address"),targetAddress:N.z.optional(N.z.string().describe("Target address")),tx:N.optional(N.union([rN,sN,iN,eN,N.string()])),txType:N.z.optional(N.z.enum(nN))}),dA=N.z.object({data:N.z.optional(N.z.record(N.z.string(),N.z.string().optional())),errorCode:N.z.enum(l),message:N.z.string().optional(),provider:N.z.enum(Q).optional()}),HP=N.z.object({error:N.z.optional(N.z.string().describe("Error message")),providerErrors:N.z.optional(N.z.array(dA)),quoteId:N.z.string().describe("Quote ID"),routes:N.z.array(LA)}),RA=LA.extend({approvalTx:fA.optional().describe("Optional approval transaction if ERC-20 approval is required before swap"),swapId:N.z.string().describe("The unique swap ID for tracking")});var Z=B.extend({dynamicHeader:async()=>{let A=U.get("widgetKey");if(A&&typeof window<"u"){let H=Math.floor(Date.now()/1000),P=window.location.origin;return{"X-Signature":await qN(A,P,H),"X-Timestamp":H.toString()}}let{swapKit:T}=U.get("apiKeys");return T?{"x-api-key":T}:{}}});async function PP(A){let T=await Z.post(J("/track"),{json:A});try{let H=lN.safeParse(T);if(!H.success)throw new $("api_v2_invalid_response",H.error);return H.data}catch(H){return T}}async function LP(A){let{getQuote:T}=U.get("endpoints");if(T)return T(A);let P=U.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",L=await Z.post(J(P),{json:A});if(L.error)throw new $("api_v2_server_error",{message:L.error});try{let F=TA.safeParse(L);if(!F.success)throw new $("api_v2_invalid_response",F.error);return F.data}catch{return L}}async function RP(A){let{getRouteWithTx:T}=U.get("endpoints");if(T)return T(A);let P=U.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",L=await Z.post(J(P),{json:A});try{let F=RA.safeParse(L);if(!F.success)throw new $("api_v2_invalid_response",F.error);return F.data}catch(F){return console.error(new $("api_v2_invalid_response",F)),L}}async function uP({chain:A,address:T,scamFilter:H=!0}){let{getBalance:P}=U.get("endpoints");if(P)return P({address:T,chain:A});let L=J(`/balance?chain=${A}&address=${T}`),F=await Z.get(L),u=Array.isArray(F)?F:[];return H?tP(u):u}function FP(A){let T=y.match(A).with({routeId:y.P.string,spender:y.P.string},({routeId:H,spender:P})=>J(`/approve?routeId=${H}&sourceAddress=${P}`)).with({assetValue:y.P.instanceOf(z),spender:y.P.string,userWallet:y.P.string},({spender:H,userWallet:P,assetValue:L})=>J(`/approve?tokenIdentifier=${L.toString()}&userWalletAddress=${P}&spender=${H}&amount=${L.getValue("string")}`)).exhaustive();return Z.get(T)}function IP(){let A=J("/providers");return Z.get(A)}function nP(A){let T=J(`/tokens?provider=${A}`);return Z.get(T)}async function BP(A){let T=J("/price"),H=await Z.post(T,{json:A});try{let P=CN.safeParse(H);if(!P.success)throw new $("api_v2_invalid_response",P.error);return P.data}catch(P){throw new $("api_v2_invalid_response",P)}}async function OP(){let A=J("/gas"),T=await Z.get(A);try{let H=PA.safeParse(T);if(!H.success)throw new $("api_v2_invalid_response",H.error);return Array.isArray(H)?H:[H]}catch(H){throw new $("api_v2_invalid_response",H)}}async function $P(A){let{destinationAddress:T}=A;if(!T)throw new $("chainflip_broker_invalid_params");let H=U.get("integrations").chainflip?.brokerUrl||J("/chainflip/broker/channel"),P=await Z.post(H,{json:A});try{let L=dN.safeParse(P);if(!L.success)throw new $("api_v2_invalid_response",L.error);return L.data}catch(L){throw new $("api_v2_invalid_response",L)}}async function GP(A){let{destinationAddress:T}=A;if(!T)throw new $("chainflip_broker_invalid_params");let H=J("/near/channel"),P=await Z.post(H,{json:A});try{let L=cN.safeParse(P);if(!L.success)throw new $("api_v2_invalid_response",L.error);return L.data}catch(L){throw new $("api_v2_invalid_response",L)}}function J(A){let{isDev:T,apiUrl:H,devApiUrl:P}=U.get("envs");return`${T?P:H}${A}`}function gP(A){let[T,H]=A.split(".");if(!cA.EVMChains.includes(T))return!0;let P=H.split("-"),L=P.length===1?void 0:P[P.length-1];return LN({chain:T,symbol:H})||!!L}var MP=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi");function tP(A){return A.filter((T)=>{return!MP.test(T.identifier)&&gP(T.identifier)})}async function _P(A){let{getSwapTo:T}=U.get("endpoints");if(T)return T(A);let H=new URLSearchParams({sellAsset:A.sellAsset});if(A.providers?.length)for(let u of A.providers)H.append("providers",u);let P=J(`/swapTo?${H.toString()}`),L=await Z.get(P);if(!Array.isArray(L))return{buyAssets:[],sellAsset:A.sellAsset};let F=[];for(let u of L)try{let n=z.from({asset:u});F.push({chain:n.chain,identifier:n.toString(),providers:[],symbol:n.symbol,ticker:n.ticker})}catch{}return{buyAssets:F,sellAsset:A.sellAsset}}var FA={};x(FA,{getThorchainQueue:()=>UP,getTcyStakers:()=>zP,getTcyStaker:()=>bP,getTcyClaimers:()=>ZP,getTcyClaimer:()=>JP,getTNSPreferredAsset:()=>wP,getTHORNodeTNSDetails:()=>rA,getRunePoolProviderInfo:()=>xP,getRunePoolInfo:()=>QP,getNodes:()=>SP,getMimirInfo:()=>XP,getLastBlock:()=>YP,getInboundAddresses:()=>EP});var lA=require("ts-pattern");function W(A){let{isStagenet:T}=U.get("envs"),H=U.get("thornodeUrls");return`${lA.match({isStagenet:T,type:A}).with({type:"mayachain"},({isStagenet:L})=>L?H.MAYA_STAGENET:H.MAYA).with({type:"thorchain"},({isStagenet:L})=>L?H.THOR_STAGENET:H.THOR)}/${A}`}function DP(A){let T=A==="mayachain"?"mayaname":"thorname";return`${W(A)}/${T}`}function YP(A="thorchain"){return B.get(`${W(A)}/lastblock`)}function UP(A){return B.get(`${W(A)}/queue`)}function SP(A){return B.get(`${W(A)}/nodes`)}function XP(A){return B.get(`${W(A)}/mimir`)}function EP(A){return B.get(`${W(A)}/inbound_addresses`)}async function rA({type:A,name:T}){try{return await B.get(`${DP(A)}/${T}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:T,owner:"",preferred_asset:""}}}async function wP({type:A,tns:T}){let H=await rA({name:T,type:A});if(!H.preferred_asset||H.preferred_asset===".")return;return z.from({asset:H.preferred_asset,asyncTokenLookup:!0})}function QP(A){return B.get(`${W(A)}/runepool`)}function xP({type:A,thorAddress:T}){return B.get(`${W(A)}/rune_provider/${T}`)}function bP({type:A,address:T}){return B.get(`${W(A)}/tcy_staker/${T}`)}function zP(A){return B.get(`${W(A)}/tcy_stakers`)}function JP({type:A,address:T}){return B.get(`${W(A)}/tcy_claimer/${T}`)}function ZP(A){return B.get(`${W(A)}/tcy_claimers`)}var WP={...uA,mayachainMidgard:WA,thorchainMidgard:VA,thornode:FA};