@swapkit/helpers 4.20.5 → 5.0.1

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