@tcswap/helpers 4.5.17 → 4.5.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
- var B={};j(B,{wrapWithThrow:()=>M$,wrapMethodWithNetworkSwitch:()=>dF,warnOnce:()=>V,validateTNS:()=>Z$,validateIdentifier:()=>YF,useUSwapStore:()=>S,useUSwapConfig:()=>P$,updateDerivationPath:()=>HF,switchEVMWalletNetwork:()=>cF,providerRequest:()=>qF,prepareNetworkSwitch:()=>TP,okxMobileEnabled:()=>sF,listWeb3EVMWallets:()=>hF,isWeb3Detected:()=>HP,isGasAsset:()=>wF,isDetected:()=>AP,initializeRPCUrlsWithFallback:()=>Q$,getWalletFormatFor:()=>y$,getTHORNameCost:()=>x$,getSymmetricWithdraw:()=>m$,getSymmetricPoolShare:()=>mF,getRPCUrl:()=>u,getMinAmountByChain:()=>W$,getMemoForWithdraw:()=>a$,getMemoForUnbond:()=>s$,getMemoForTcyStake:()=>NP,getMemoForTcyClaim:()=>PP,getMemoForRunePoolWithdraw:()=>e$,getMemoForRunePoolDeposit:()=>i$,getMemoForNameRegister:()=>FP,getMemoForNamePreferredAssetRegister:()=>$P,getMemoForLeaveAndBond:()=>l$,getMemoForDeposit:()=>r$,getMAYANameCost:()=>T$,getLiquiditySlippage:()=>h$,getFeeMultiplierAsBigInt:()=>EF,getFeeMultiplier:()=>ZF,getExplorerTxUrl:()=>E$,getExplorerAddressUrl:()=>u$,getEstimatedPoolShare:()=>t$,getETHDefaultWallet:()=>GP,getEIP6963Wallets:()=>BP,getDerivationPathFor:()=>D$,getCommonAssetInfo:()=>l,getChainIdentifier:()=>G$,getAsymmetricRuneWithdrawAmount:()=>C$,getAsymmetricRuneShare:()=>CF,getAsymmetricAssetWithdrawAmount:()=>n$,getAsymmetricAssetShare:()=>nF,getAssetType:()=>PF,formatBigIntToSafeValue:()=>D,findAssetBy:()=>L$,filterSupportedChains:()=>xP,fetchTokenInfo:()=>zF,derivationPathToString:()=>uF,assetFromString:()=>s,applyFeeMultiplierToBigInt:()=>V$,applyFeeMultiplier:()=>O$,addEVMWalletNetwork:()=>lF,addAccountsChangedCallback:()=>MP,WarningCodeEnum:()=>WF,WalletOption:()=>d,USwapNumber:()=>I,USwapError:()=>L,USwapConfig:()=>g,RequestClient:()=>E,ProviderName:()=>gF,NetworkDerivationPath:()=>b,MemoType:()=>KF,LedgerErrorCode:()=>VF,FeeTypeEnum:()=>IF,FeeOption:()=>BF,ErrorCode:()=>UF,DerivationPath:()=>f$,DEFAULT_FEE_MULTIPLIERS:()=>bF,CommonAssetStrings:()=>z$,BigIntArithmetics:()=>O,AssetValue:()=>t,ApproveMode:()=>kF});module.exports=mP(B);K(B,require("@tcswap/tokens"),module.exports);K(B,require("@tcswap/types"),module.exports);var k$={};j(k$,{getMinAmountByChain:()=>W$,AssetValue:()=>t});var z=require("@tcswap/types"),DF=require("ethers"),XF=require("ts-pattern");var J$={};j(J$,{isGasAsset:()=>wF,getCommonAssetInfo:()=>l,getAssetType:()=>PF,findAssetBy:()=>L$,fetchTokenInfo:()=>zF,assetFromString:()=>s,CommonAssetStrings:()=>z$});var T=require("@tcswap/types"),$F=require("ts-pattern");var H$={};j(H$,{RequestClient:()=>E});var N$={};j(N$,{useUSwapStore:()=>S,useUSwapConfig:()=>P$,USwapConfig:()=>g});var U=require("@tcswap/types"),eF=require("zustand"),F$=require("zustand/shallow");var aF={};j(aF,{WarningCodeEnum:()=>WF,WalletOption:()=>d,ProviderName:()=>gF,NetworkDerivationPath:()=>b,MemoType:()=>KF,LedgerErrorCode:()=>VF,FeeTypeEnum:()=>IF,FeeOption:()=>BF,ErrorCode:()=>UF,ApproveMode:()=>kF});var GF=require("@tcswap/types"),b=GF.AllChains.reduce((F,$)=>{return F[$]=GF.getChainConfig($).networkDerivationPath,F},{});var UF;((H)=>{H.unknownError="unknownError";H.test_error="test_error";H.providerDetailsError="providerDetailsError";H.blockHeaderNotFound="blockHeaderNotFound";H.blockHashNotFoundAtHeight="blockHashNotFoundAtHeight";H.blockHashNotFoundAtHash="blockHashNotFoundAtHash";H.txHashMissing="txHashMissing";H.assetValueMissingInfo="assetValueMissingInfo";H.invalidAsset="invalidAsset";H.blockIsRequired="blockIsRequired";H.currentBlockHeaderNotFound="currentBlockHeaderNotFound";H.failedToRetrieveBalance="failedToRetrieveBalance";H.failedToRetrieveBlock="failedToRetrieveBlock";H.failedToRetrieveFees="failedToRetrieveFees";H.notImplementedBCH="notImplementedBCH";H.notImplementedDoge="notImplementedDoge";H.noPoolsFound="noPoolsFound";H.noVaultsFound="noVaultsFound";H.noTxFound="noTxFound";H.noInputCoinFound="noInputCoinFound";H.noBlockDataFound="noBlockDataFound";H.multipleCosmosMessages="multipleCosmosMessages";H.heightOrHashNotProvided="heightOrHashNotProvided";H.unknownDenom="unknownDenom";H.invalidBlockHeight="invalidBlockHeight";H.timestampExtrinsicNoArgumentsForBlock="timestampExtrinsicNoArgumentsForBlock";H.timestampExtrinsicNoTimestampForBlock="timestampExtrinsicNoTimestampForBlock";H.noTimestampExtrinsicForHash="noTimestampExtrinsicForHash";H.timestampExtrinsicNoArgumentsForHash="timestampExtrinsicNoArgumentsForHash";H.txMemoUndefined="txMemoUndefined";H.txMemoIncorrect="txMemoIncorrect";H.txTypeNotFound="txTypeNotFound";H.txNoMessage="txNoMessage";H.txNotFound="txNotFound";H.txReceiptNotFound="txReceiptNotFound";H.txParsingError="txParsingError";H.txLogsParsingError="txLogsParsingError";H.blockNotFound="blockNotFound";H.balanceNotFound="balanceNotFound";H.configError="configError";H.synthSwapDisallowed="synthSwapDisallowed";H.providerQuoteTimeout="providerQuoteTimeout";H.noQuoteResponse="noQuoteResponse";H.noPoolAssetsFound="noPoolAssetsFound";H.noThorchainPools="noThorchainPools";H.noMayachainPools="noMayachainPools";H.noThorchainNetworkInfo="noThorchainNetworkInfo";H.invalidAffiliateFee="invalidAffiliateFee";H.invalidBuyAssetAddress="invalidBuyAssetAddress";H.invalidSellAssetAddress="invalidSellAssetAddress";H.invalidSourceAddress="invalidSourceAddress";H.invalidDestinationAddress="invalidDestinationAddress";H.sourceAddressIsSmartContract="sourceAddressIsSmartContract";H.destinationAddressIsSmartContract="destinationAddressIsSmartContract";H.invalidChainId="invalidChainId";H.unsupportedChainId="unsupportedChainId";H.unsupportedEVMChainId="unsupportedEVMChainId";H.unsupportedMethod="unsupportedMethod";H.unsupportedProvider="unsupportedProvider";H.invalidParamsForMethod="invalidParamsForMethod";H.unsupportedAdapter="unsupportedAdapter";H.noWhitelistTokens="noWhitelistTokens";H.failedFetchGasPrice="failedFetchGasPrice";H.failedToCreateDepositChannel="failedToCreateDepositChannel";H.noProviderDetailsFound="noProviderDetailsFound";H.noTokenListsFound="noTokenListsFound";H.tokenNotFound="tokenNotFound";H.tokenPriceNotFound="tokenPriceNotFound";H.tokenPriceFailedToUpdate="tokenPriceFailedToUpdate";H.swapAmountTooSmall="swapAmountTooSmall";H.legsArrayIsEmpty="legsArrayIsEmpty";H.failedToFetchQuoteForLeg="failedToFetchQuoteForLeg";H.noBlockHeaderFound="noBlockHeaderFound";H.failedToSimulateSwap="failedToSimulateSwap";H.addressScreeningFailed="addressScreeningFailed";H.noLiquidtyProvidersFound="noLiquidtyProvidersFound";H.insufficientLiquidity="insufficientLiquidity";H.noInboundDataFound="noInbounDataFound";H.noInboundAddressesFound="noInboundAddressesFound";H.noInboundAddressFoundForChain="noInboundAddressFoundForChain";H.noLastBlocksFound="noLastBlocksFound";H.noVersionFound="noVersionFound";H.noConstantsFound="noConstantsFound";H.noMimirsFound="noMimirsFound";H.noRoutesFound="noRoutesFound";H.quoteNotFound="quoteNotFound";H.ledgerSignFailed="ledgerSignFailed";H.ledgerWrongPayload="ledgerWrongPayload";H.ledgerFetchSwapFailed="ledgerFetchSwapFailed";H.failedToFetchTx="failedToFetchTx";H.failedBuildTransactionDetails="failedBuildTransactionDetails";H.noLegsForRoute="noLegsForRoute";H.noRouterAddressFound="noRouterAddressFound";H.noAggregatorAddressFound="noAggregatorAddressFound";H.noContractInstanceFound="noContractInstanceFound";H.noContractAddressFound="noContractAddressFound";H.invalidAffiliate="invalidAffiliate";H.thornameAffiliate="thornameAffiliate";H.providerNotfound="No provider found";H.noRecordFound="No Record found";H.slippageTooLow="Slippage too low";H.tradingHalted="tradingHalted";H.noWrappedGasAsset="noWrappedGasAsset";H.aggregatorAddressNotFound="aggregatorAddressNotFound";H.routerAddressNotFound="routerAddressNotFound";H.dummyAddressNotFound="dummyAddressNotFound";H.trackerError="trackerError";H.thorchainPoolUnavailable="thorchainPoolUnavailable";H.noOhlcvDataFound="noOhlcvDataFound";H.noTradingPairs="noTradingPairs";H.noLendingAvailability="noLendingAvailability";H.lendingRepayTooSmall="lendingRepayTooSmall";H.missingState="missingState";H.ledgerSwapNotFound="ledgerSwapNotFound";H.ledgerSwapNotReadyForTracking="ledgerSwapNotReadyForTracking";H.errorEstimatingGas="errorEstimatingGas";H.apiKeyInvalid="apiKeyInvalid";H.apiKeyFailedToUpdate="apiKeyFailedToUpdate";H.apiKeyExpired="apiKeyExpired";H.unauthorized="unauthorized";H.failedToCreateMemo="failedToCreateMemo";H.radixIncorrectInstructions="radixIncorrectInstructions";H.radixTxMissedParam="radixTxMissedParam";H.radixTxMissedAccount="radixTxMissedAccount";H.radixManifestParseError="radixManifestParseError";H.radixManifestBuildError="radixManifestBuildError";H.invalidAddressForChain="invalidAddressForChain";H.riskyAddress="riskyAddress";H.noRoutesToProcess="noRoutesToProcess";H.sellAssetAmountTooSmall="sellAssetAmountTooSmall";H.missingPrivateKey="missingPrivateKey";H.noMemoPriceProtection="noMemoPriceProtection";H.rateExpired="rateExpired";H.amountTooSmall="amountTooSmall";H.amountTooBig="amountTooBig";H.amountOutOfRange="amountOutOfRange";H.requestTimeOut="requestTimeOut";H.networkError="networkError";H.unknownApiError="unknownApiError";H.invalidResponseFormat="invalidResponseFormat"})(UF||={});var WF;((P)=>{P.highSlippage="highSlippage";P.highPriceImpact="highPriceImpact"})(WF||={});var gF;((J)=>{J.CAVIAR_V1="CAVIAR_V1";J.CAMELOT_V3="CAMELOT_V3";J.CHAINFLIP="CHAINFLIP";J.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";J.JUPITER="JUPITER";J.MAYACHAIN="MAYACHAIN";J.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";J.OCISWAP_V1="OCISWAP_V1";J.ONEINCH="ONEINCH";J.OPENOCEAN_V2="OPENOCEAN_V2";J.PANCAKESWAP="PANCAKESWAP";J.PANGOLIN_V1="PANGOLIN_V1";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"})(gF||={});var IF;((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"})(IF||={});var BF;((N)=>{N.Average="average";N.Fast="fast";N.Fastest="fastest"})(BF||={});var kF;((P)=>{P.Approve="approve";P.CheckOnly="checkOnly"})(kF||={});var KF;((Q)=>{Q.NAME_REGISTER="~";Q.BOND="BOND";Q.DEPOSIT="+";Q.LEAVE="LEAVE";Q.UNBOND="UNBOND";Q.WITHDRAW="-";Q.RUNEPOOL_DEPOSIT="POOL+";Q.RUNEPOOL_WITHDRAW="POOL-";Q.CLAIM_TCY="tcy";Q.STAKE_TCY="tcy+";Q.UNSTAKE_TCY="tcy-"})(KF||={});var d;((w)=>{w.BITGET="BITGET";w.BRAVE="BRAVE";w.COINBASE_MOBILE="COINBASE_MOBILE";w.COINBASE_WEB="COINBASE_WEB";w.COSMOSTATION="COSMOSTATION";w.CTRL="CTRL";w.EIP6963="EIP6963";w.EXODUS="EXODUS";w.KEEPKEY="KEEPKEY";w.KEEPKEY_BEX="KEEPKEY_BEX";w.KEPLR="KEPLR";w.KEYSTORE="KEYSTORE";w.LEAP="LEAP";w.LEDGER="LEDGER";w.LEDGER_LIVE="LEDGER_LIVE";w.METAMASK="METAMASK";w.OKX="OKX";w.OKX_MOBILE="OKX_MOBILE";w.ONEKEY="ONEKEY";w.PASSKEYS="PASSKEYS";w.PHANTOM="PHANTOM";w.POLKADOT_JS="POLKADOT_JS";w.RADIX_WALLET="RADIX_WALLET";w.TALISMAN="TALISMAN";w.TREZOR="TREZOR";w.TRONLINK="TRONLINK";w.TRUSTWALLET_WEB="TRUSTWALLET_WEB";w.VULTISIG="VULTISIG";w.WALLETCONNECT="WALLETCONNECT";w.WALLET_SELECTOR="WALLET_SELECTOR";w.XAMAN="XAMAN"})(d||={});var VF;((N)=>{N[N.NoError=36864]="NoError";N[N.LockedDevice=21781]="LockedDevice";N[N.TC_NotFound=65535]="TC_NotFound"})(VF||={});var QP=U.AllChains.reduce((F,$)=>{if(!F.THOR_STAGENET)F[U.StagenetChain.Maya]=U.StagenetMAYAConfig.rpcUrls,F[U.StagenetChain.THORChain]=U.StagenetTHORConfig.rpcUrls;return F[$]=U.getChainConfig($).rpcUrls,F},{}),$$={apiKeys:{blockchair:"",keepKey:"",memoless:"",passkeys:"",uSwap:"",walletConnectProjectId:"",xaman:""},chains:U.AllChains,endpoints:{},envs:{apiUrl:"https://swap-api.unstoppable.money",blockchairApiUrl:null,devApiUrl:"https://swap-api-dev.unstoppable.money",experimental_apiKey:null,experimental_apiUrlQuote:null,experimental_apiUrlSwap:null,isDev:!1,isStagenet:!1,memolessApiUrl:"https://swap.unstoppable.money/memoless/api/v1"},feeMultipliers:void 0,integrations:{radix:{applicationName:"USwap Playground",applicationVersion:"0.0.1",dAppDefinitionAddress:"account_rdx128r289p58222hcvev7frs6kue76pl7pdcnw8725aw658v0zggkh9ws",network:{dashboardBase:"https://dashboard.radixdlt.com",networkId:1,networkName:"mainnet"}}},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:QP,wallets:Object.values(d)},S=eF.create((F)=>({...$$,setApiKey:($,P)=>F((N)=>({apiKeys:{...N.apiKeys,[$]:P}})),setConfig:($)=>F((P)=>({apiKeys:{...P.apiKeys,...$?.apiKeys},chains:P.chains.concat($?.chains||[]),endpoints:{...P.endpoints,...$?.endpoints},envs:{...P.envs,...$?.envs},feeMultipliers:$?.feeMultipliers||P.feeMultipliers,integrations:{...P.integrations,...$?.integrations},rpcUrls:{...P.rpcUrls,...$?.rpcUrls},wallets:P.wallets.concat($?.wallets||[])})),setEndpoint:($,P)=>F((N)=>({endpoints:{...N.endpoints,[$]:P}})),setEnv:($,P)=>F((N)=>({envs:{...N.envs,[$]:P}})),setFeeMultipliers:($)=>F(()=>({feeMultipliers:$})),setIntegrationConfig:($,P)=>F((N)=>({integrations:{...N.integrations,[$]:P}})),setRequestOptions:($)=>F((P)=>({requestOptions:{retry:{...P.requestOptions.retry,...$.retry},timeoutMs:$.timeoutMs||P.requestOptions.timeoutMs}})),setRpcUrl:($,P)=>F((N)=>({rpcUrls:{...N.rpcUrls,[$]:P}}))})),P$=()=>S(F$.useShallow((F)=>({apiKeys:F?.apiKeys,chains:F?.chains,endpoints:F?.endpoints,envs:F?.envs,feeMultipliers:F?.feeMultipliers,integrations:F?.integrations,rpcUrls:F?.rpcUrls,wallets:F?.wallets}))),g={get:(F)=>S.getState()[F],getState:S.getState,reinitialize:()=>S.setState($$),set:(F)=>S.getState().setConfig(F),setApiKey:(F,$)=>S.getState().setApiKey(F,$),setEndpoint:(F,$)=>S.getState().setEndpoint(F,$),setEnv:(F,$)=>S.getState().setEnv(F,$),setFeeMultipliers:(F)=>S.getState().setFeeMultipliers(F),setIntegrationConfig:(F,$)=>S.getState().setIntegrationConfig(F,$),setRequestOptions:(F)=>S.getState().setRequestOptions(F),setRpcUrl:(F,$)=>S.getState().setRpcUrl(F,$)};var R$={};j(R$,{USwapError:()=>L});var _P={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_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_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_bitkeep_not_found:21001,wallet_bitkeep_failed_to_switch_network:21002,wallet_bitkeep_no_accounts:21003,wallet_passkeys_sign_transaction_error:21101,wallet_passkeys_not_found:21102,wallet_passkeys_no_address:21103,wallet_passkeys_request_canceled:21104,wallet_passkeys_signature_canceled:21105,wallet_passkeys_failed_to_switch_network:21106,wallet_passkeys_chain_not_supported:21107,wallet_passkeys_instance_missing:21108,wallet_onekey_not_found:21201,wallet_onekey_sign_transaction_error:21202,wallet_okx_not_found:21301,wallet_okx_chain_not_supported:21302,wallet_okx_failed_to_switch_network:21303,wallet_okx_no_accounts:21304,wallet_keplr_not_found:21401,wallet_keplr_chain_not_supported:21402,wallet_keplr_signer_not_found:21403,wallet_keplr_no_accounts:21404,wallet_cosmostation_not_found:21501,wallet_cosmostation_chain_not_supported:21502,wallet_cosmostation_evm_provider_not_found:21503,wallet_cosmostation_keplr_provider_not_found:21504,wallet_cosmostation_no_accounts:21505,wallet_cosmostation_no_evm_accounts:21506,wallet_cosmostation_no_evm_address:21507,wallet_cosmostation_signer_not_found:21508,wallet_coinbase_not_found:21701,wallet_coinbase_chain_not_supported:21702,wallet_coinbase_method_not_supported:21703,wallet_coinbase_no_accounts:21704,wallet_evm_extensions_failed_to_switch_network:21801,wallet_evm_extensions_no_provider:21802,wallet_evm_extensions_not_found:21803,wallet_keystore_invalid_password:21901,wallet_keystore_unsupported_version:21902,wallet_near_extensions_failed_to_switch_network:22001,wallet_near_extensions_no_provider:22002,wallet_near_extensions_not_found:22003,wallet_near_method_not_supported:22003,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_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_solana_no_signer:50401,toolbox_solana_fee_estimation_failed:50402,toolbox_solana_broadcast_failed:50403,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_tron_no_signer:50801,toolbox_tron_invalid_token_identifier:50802,toolbox_tron_token_transfer_failed:50803,toolbox_tron_transaction_creation_failed:50804,toolbox_tron_fee_estimation_failed:50805,toolbox_tron_trongrid_api_error:50806,toolbox_tron_approve_failed:50807,toolbox_tron_invalid_token_contract:50808,toolbox_tron_allowance_check_failed:50809,toolbox_near_no_signer:90601,toolbox_near_invalid_address:90602,toolbox_near_invalid_amount:90603,toolbox_near_transfer_failed:90604,toolbox_near_access_key_error:90605,toolbox_near_no_rpc_url:90606,toolbox_near_empty_batch:90607,toolbox_near_balance_failed:90608,toolbox_near_invalid_name:90609,toolbox_near_missing_contract_address:90610,toolbox_near_no_account:90611,toolbox_near_invalid_gas_params:90612,toolbox_near_no_public_key_found:90613,toolbox_sui_address_required:90701,toolbox_sui_keypair_required:90702,toolbox_sui_balance_error:90703,toolbox_sui_transaction_creation_error:90704,toolbox_sui_signing_error:90705,toolbox_sui_broadcast_error:90706,toolbox_sui_no_signer:90707,toolbox_sui_no_sender:90708,toolbox_not_supported:59901,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,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,not_implemented:99999};class L extends Error{static ErrorCode=_P;constructor(F,$){let P=typeof F==="string",N=P?F:F.errorKey,R=P?void 0:F.info,x=`${N}${R?`: ${JSON.stringify(R)}`:""}`;super(x);if(Object.setPrototypeOf(this,L.prototype),this.name="USwapError",this.cause=$,$){let A=$ instanceof Error?`${$.message}${$.cause?` (${$.cause})`:""}`:JSON.stringify($);console.error(`USwapError [${N}]: ${A}`)}else if(R)console.error(`USwapError [${N}]: ${JSON.stringify(R)}`)}}var zP=(F)=>new Promise(($)=>setTimeout($,F)),wP=(F,{baseDelay:$,backoffMultiplier:P,maxDelay:N})=>Math.min($*P**F,N),YP=async(F,$)=>{let P=await fetch(F,$);if(!P.ok){let N=await P.json().catch(()=>null),R={status:P.status,statusText:P.statusText},x={...R,...N&&{errorData:N}};throw new L({errorKey:"helpers_invalid_response",info:R},x)}return P.json()};function QF(F,$={}){return async function(N,R={}){let{searchParams:x,json:A,body:M,headers:G,dynamicHeader:_,retry:Y,timeoutMs:Q,abortController:W,onError:p,onSuccess:v,responseHandler:C,...h}={...$,...R},y=g.get("requestOptions"),k={...y.retry,...Y},c=!!A||N.endsWith(".json"),TF=JP(N,x),J=LP(c,{...G,..._?.()}),FF=c?JSON.stringify(A):M,f;for(let MF=0;MF<=k.maxRetries;MF++){let iF=W||new AbortController,rF=setTimeout(()=>iF.abort(),Q||y.timeoutMs);try{let n=await YP(TF,{...h,body:FF,headers:J,method:F,signal:iF.signal});return clearTimeout(rF),v?.(n)||C?.(n)||n}catch(n){if(clearTimeout(rF),f=n,MF>=k.maxRetries)return p?p(n):Promise.reject(n);await zP(wP(MF,k))}}return p?p(f):Promise.reject(f)}}function LP(F,$){return{...$,...F&&{"Content-Type":"application/json"}}}function JP(F,$){let P=new URL(F);if($)P.search=new URLSearchParams($).toString();return P.toString()}var E={extend:(F)=>({extend:($)=>E.extend({...F,...$}),get:QF("GET",F),post:QF("POST",F)}),get:QF("GET"),post:QF("POST")};var _$={};j(_$,{initializeRPCUrlsWithFallback:()=>Q$,getRPCUrl:()=>u});var Z=require("@tcswap/types"),pF=require("ts-pattern");var B$={};j(B$,{wrapWithThrow:()=>M$,warnOnce:()=>V,getTHORNameCost:()=>x$,getMAYANameCost:()=>T$,getChainIdentifier:()=>G$});var _F=require("@tcswap/types");function x$(F){if(F<0)throw new L({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:F}});return 10+F}function T$(F){if(F<0)throw new L({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:F}});return Math.round((10+F*1.0512)*10000000000)/10000000000}function M$(F,$){try{return F()}catch(P){if($)throw new L($,P);return}}function G$(F){switch(F){case _F.Chain.THORChain:return`${F}.RUNE`;case _F.Chain.Cosmos:return`${F}.ATOM`;case _F.Chain.BinanceSmartChain:return`${F}`;default:return`${F}.${F}`}}var A$=new Set;function V({condition:F,id:$,warning:P}){if(F){if(A$.has($))return;console.warn(P),A$.add($)}}function XP(F){return pF.match(F).with(...Z.EVMChains,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...Z.UTXOChains,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...Z.CosmosChains,...Z.StagenetChains,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(Z.Chain.Polkadot,Z.Chain.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(Z.Chain.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(Z.Chain.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(Z.Chain.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(Z.Chain.Tron,Z.Chain.Radix,()=>"").with(Z.Chain.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(Z.Chain.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).otherwise(()=>{throw new L("helpers_chain_not_supported",{chain:F})})}function ZP(F){return pF.match(F).with(Z.Chain.Radix,()=>"/status/network-configuration").with(Z.Chain.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function K$(F,$){try{let P=$.startsWith("wss")?$.replace("wss","https"):$;return(await fetch(`${P}${ZP(F)}`,{body:JSON.stringify(XP(F)),headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var OF=new Map,jP=120000;async function u(F){let{isStagenet:$}=g.get("envs"),[P="",...N]=g.get("rpcUrls")[F];if(!P)throw V({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 ${F}.`}),new L("helpers_chain_no_public_or_set_rpc_url",{chain:F});if($)return P;let R=OF.get(F);if(R&&Date.now()-R.timestamp<jP)return R.url;if(!await K$(F,P)){for(let A of N)if(await K$(F,A))return OF.set(F,{timestamp:Date.now(),url:A}),A}return OF.set(F,{timestamp:Date.now(),url:P}),P}function Q$(F){V({condition:!0,id:"initializeRPCUrlsWithFallback",warning:"initializeRPCUrlsWithFallback is deprecated. Use static { rpcUrls, fallbackRpcUrls } USwap init config or dynamic USwapConfig.setRpcUrl/setFallbackRpcUrl to configure RPC endpoints."})}var z$=[`${T.Chain.Maya}.MAYA`,`${T.Chain.Maya}.CACAO`,`${T.Chain.Ethereum}.THOR`,`${T.Chain.Ethereum}.vTHOR`,`${T.Chain.Kujira}.USK`,`${T.Chain.Ethereum}.FLIP`,`${T.Chain.Radix}.XRD`],w$=[T.Chain.Arbitrum,T.Chain.Aurora,T.Chain.Base,T.Chain.Ethereum,T.Chain.Optimism];async function SP(F){let{baseDecimal:$}=T.getChainConfig(T.Chain.Radix);try{let P=await u(T.Chain.Radix),{manager:N}=await E.post(`${P}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:F}),headers:{Accept:"*/*","Content-Type":"application/json"}});return N?.divisibility?.value?.divisibility}catch(P){let N=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Radix asset decimals for ${F}: ${N}`),$}}async function qP(F){try{let $=await u(T.Chain.Radix);return(await E.post(`${$}/state/entity/details`,{body:JSON.stringify({addresses:[F],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((R)=>R.key==="symbol")?.value.typed.value||void 0}catch($){let P=$ instanceof Error?$.message:String($);return console.warn(`Failed to fetch Radix asset symbol for ${F}: ${P}`),""}}async function Y$({chain:F,address:$,methodHex:P,id:N}){let R=await u(F);return E.post(R,{body:JSON.stringify({id:N,jsonrpc:"2.0",method:"eth_call",params:[{data:P,to:$.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}async function UP(F){if(!F||F==="0x")return"UNKNOWN";try{let{AbiCoder:$}=await import("ethers");return $.defaultAbiCoder().decode(["string"],F)[0].trim()}catch($){return console.warn(`Failed to decode ABI string from ${F}: ${$}`),"UNKNOWN"}}function WP(F,$){if(!F||F==="0x")return $;try{return Number(F)}catch(P){return console.warn(`Failed to decode ABI uint8 from ${F}: ${P}`),$}}async function gP({chain:F,address:$}){let{baseDecimal:P}=T.getChainConfig(F),N=$.toLowerCase();if($===""||!N.startsWith("0x"))return P;let R=await Y$({address:$,chain:F,id:2,methodHex:"0x313ce567"}).catch((A)=>{return console.warn(`Could not fetch decimals for ${$} on ${F}: ${A.message}`),{result:""}});return WP(R.result,P)}async function IP({chain:F,address:$}){let P=$.toLowerCase();if(P===""||!P.startsWith("0x"))return;let N=await Y$({address:$,chain:F,id:1,methodHex:"0x95d89b41"}).catch((x)=>{return console.warn(`Could not fetch symbol for ${$} on ${F}: ${x.message}`),{result:""}});return await UP(N.result)}function zF({chain:F,address:$}){let{baseDecimal:P}=T.getChainConfig(F),N={decimals:P,ticker:void 0};return $F.match(F).with(...T.EVMChains,async()=>{try{let{isAddress:R,getAddress:x}=await import("ethers");if(!R(x($.replace(/^0X/,"0x"))))return N;let[A,M]=await Promise.all([IP({address:$,chain:F}),gP({address:$,chain:F})]);return{decimals:M,ticker:A}}catch(R){return console.warn(`Failed to fetch token info for ${$} on ${F}: ${R?.code} ${R?.message}`),N}}).with(T.Chain.Solana,async()=>{if(!$)return N;try{let R=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${$}`);if(R.ok){let x=await R.json(),A=Array.isArray(x)?x[0]:x;if(A)return{decimals:A.decimals??P,ticker:A.symbol||void 0}}}catch(R){console.warn(`Failed to fetch Solana token info for ${$}: ${R?.code} ${R?.message}`)}return N}).with(T.Chain.Tron,async()=>{if(!$)return N;try{let R=await import("tronweb"),x=R.TronWeb??R.default?.TronWeb,A=await u(T.Chain.Tron),G=await new x({fullHost:A,privateKey:"0000000000000000000000000000000000000000000000000000000000000001"}).contract().at($),[_,Y]=await Promise.all([G.symbol().call().catch((Q)=>{console.warn(`Could not fetch symbol for ${$} on Tron:`,Q);return}),G.decimals().call().catch((Q)=>{return console.warn(`Could not fetch decimals for ${$} on Tron:`,Q),P})]);return{decimals:typeof Y==="number"?Y:Number(Y||P),ticker:_||void 0}}catch(R){let x=R instanceof Error?R.message:String(R);return console.warn(`Failed to fetch Tron token info for ${$}: ${x}`),N}}).with(T.Chain.Near,async()=>{if(!$)return N;try{let{JsonRpcProvider:R}=await import("@near-js/providers"),x=await u(T.Chain.Near),M=await new R({url:x}).query({account_id:$,args_base64:Buffer.from("{}").toString("base64"),finality:"final",method_name:"ft_metadata",request_type:"call_function"}),G=JSON.parse(Buffer.from(M.result).toString());return{decimals:G?.decimals||P,ticker:G?.symbol}}catch(R){let x=R instanceof Error?R.message:String(R);return console.warn(`Failed to fetch Near token info for ${$}: ${x}`),N}}).with(T.Chain.Radix,async()=>{if(!$)return N;try{let[R,x]=await Promise.all([qP($),SP($)]);return{decimals:x,ticker:R}}catch(R){let x=R instanceof Error?R.message:String(R);return console.warn(`Failed to fetch Radix token info for ${$}: ${x}`),N}}).otherwise(async()=>N)}function wF({chain:F,symbol:$}){return $F.match(F).with(...w$,()=>$==="ETH").with(T.Chain.Avalanche,()=>$==="AVAX").with(T.Chain.Berachain,()=>$==="BERA").with(T.Chain.BinanceSmartChain,()=>$==="BNB").with(T.Chain.Gnosis,()=>$==="xDAI"||$==="XDAI").with(T.Chain.Monad,()=>$==="MON").with(T.Chain.XLayer,()=>$==="OKB").with(T.Chain.Maya,()=>$==="CACAO").with(T.Chain.Cosmos,()=>$==="ATOM").with(T.Chain.THORChain,()=>$==="RUNE").with(T.Chain.Tron,()=>$==="TRX").with(T.Chain.Radix,()=>`${F}.${$}`===l(F).identifier).otherwise(()=>$===F)}var l=(F)=>{let{baseDecimal:$}=T.getChainConfig(F);return $F.match(F.toUpperCase()).with(...w$,(N)=>({decimal:$,identifier:`${N}.ETH`})).with(T.Chain.THORChain,(N)=>({decimal:$,identifier:`${N}.RUNE`})).with(T.Chain.Cosmos,(N)=>({decimal:$,identifier:`${N}.ATOM`})).with(T.Chain.Maya,(N)=>({decimal:10,identifier:`${N}.CACAO`})).with(T.Chain.BinanceSmartChain,(N)=>({decimal:$,identifier:`${N}.BNB`})).with(T.Chain.Monad,(N)=>({decimal:$,identifier:`${N}.MON`})).with(T.Chain.Avalanche,(N)=>({decimal:$,identifier:`${N}.AVAX`})).with(T.Chain.Gnosis,(N)=>({decimal:$,identifier:`${N}.xDAI`})).with(T.Chain.XLayer,(N)=>({decimal:$,identifier:`${N}.OKB`})).with(T.Chain.Berachain,(N)=>({decimal:$,identifier:`${N}.BERA`})).with(T.Chain.Tron,(N)=>({decimal:$,identifier:`${N}.TRX`})).with(T.Chain.Solana,T.Chain.Chainflip,T.Chain.Kujira,T.Chain.Ripple,T.Chain.Polkadot,T.Chain.Near,...T.UTXOChains,(N)=>({decimal:$,identifier:`${N}.${N}`})).with(T.Chain.Radix,"XRD.XRD",()=>({decimal:$,identifier:"XRD.XRD"})).with(T.Chain.Polygon,"POL.POL",()=>({decimal:$,identifier:"POL.POL"})).with("KUJI.USK",(N)=>({decimal:6,identifier:N})).with("ETH.FLIP",()=>({decimal:T.getChainConfig(T.Chain.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:T.getChainConfig(T.Chain.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:T.getChainConfig(T.Chain.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(N)=>({decimal:10,identifier:N})).with("MAYA.MAYA",(N)=>({decimal:4,identifier:N})).otherwise(()=>({decimal:$,identifier:F}))};function PF({chain:F,symbol:$}){if($.includes("/"))return"Synth";if($.includes("~"))return"Trade";return $F.match(F).with(T.Chain.Radix,()=>$===T.Chain.Radix||`${F}.${$}`===l(F).identifier).with(T.Chain.Arbitrum,T.Chain.Optimism,T.Chain.Base,T.Chain.Aurora,()=>$===T.Chain.Ethereum).with(T.Chain.Cosmos,()=>$==="ATOM").with(T.Chain.BinanceSmartChain,()=>$==="BNB").with(T.Chain.Maya,()=>$==="CACAO").with(T.Chain.Monad,()=>$==="MON").with(T.Chain.THORChain,()=>$==="RUNE").with(T.Chain.Tron,()=>$==="TRX").with(T.Chain.XLayer,()=>$==="OKB").otherwise(()=>$===F)?"Native":F}var s=(F)=>{let[$,...P]=F.split("."),N=F.includes("/"),R=P.join("."),x=R?.split("-"),A=x?.length?x.length===1?x[0]:x.slice(0,-1).join("-"):void 0;return{chain:$,symbol:R,synth:N,ticker:A}};async function L$(F){let{loadTokenLists:$}=await import("./tokens.cjs"),P=await $();for(let N of Object.values(P))for(let{identifier:R,chain:x,...A}of N.tokens){if("identifier"in F&&R===F.identifier)return R;if("address"in A&&"chain"in F&&x===F.chain&&A.address&&A.address.toLowerCase()===F.contract.toLowerCase())return R}return}var j$={};j(j$,{validateTNS:()=>Z$,validateIdentifier:()=>YF});var X$=["TERRA",...g.get("chains")];function YF(F=""){let $=F.toUpperCase(),[P]=$.split(".");if(X$.includes(P))return!0;let[N]=$.split("/");if(X$.includes(N))return!0;throw new L({errorKey:"helpers_invalid_identifier",info:{identifier:F,message:`Invalid identifier: ${F}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}function Z$(F){if(F.length>30)return!1;let $=/^[a-zA-Z0-9+_-]+$/g;return!!F.match($)}var q$={};j(q$,{formatBigIntToSafeValue:()=>D,BigIntArithmetics:()=>O});var RF=require("ts-pattern"),i=8,kP=10;function D({value:F,bigIntDecimal:$=i,decimal:P=i}){if(P===0)return F.toString();let N=F<0n,R=F.toString().substring(N?1:0),x=P-(R.length-1);if(x>0)R="0".repeat(x)+R;let A=R.length-P,M=R.slice(-P);if(Number.parseInt(M[$]||"0",10)>=5){let _=Number.parseInt(M[$-1]||"0",10);M=`${M.substring(0,$-1)}${_+1}`}else M=M.substring(0,$);return`${N?"-":""}${R.slice(0,A)}.${M}`.replace(/\.?0*$/,"")}class O{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(F,$){return new O({decimal:$,value:D({bigIntDecimal:$,decimal:$,value:F})})}static shiftDecimals({value:F,from:$,to:P}){return O.fromBigInt(F.getBaseValue("bigint")*m(P)/m($),P)}constructor(F){let $=vF(F),P=typeof F==="object";this.decimal=P?F.decimal:void 0,this.decimalMultiplier=P&&"decimalMultiplier"in F?F.decimalMultiplier:m(Math.max(S$(LF($)),this.decimal||0)),this.#R($)}set(F){return new this.constructor({decimal:this.decimal,identifier:this.toString?.({includeSynthProtocol:!0}),value:F})}add(...F){return this.#$("add",...F)}sub(...F){return this.#$("sub",...F)}mul(...F){return this.#$("mul",...F)}div(...F){return this.#$("div",...F)}gt(F){return this.#F("gt",F)}gte(F){return this.#F("gte",F)}lt(F){return this.#F("lt",F)}lte(F){return this.#F("lte",F)}eqValue(F){return this.#F("eqValue",F)}getValue(F,$){let P=NF(this.decimalMultiplier),N=$!==void 0?$:this.decimal,R=N!==void 0?N:P;if(N!==void 0&&N<P){if(this.formatBigIntToSafeValue(this.bigIntValue,N)==="0"&&this.bigIntValue!==0n)R=P}let x=this.formatBigIntToSafeValue(this.bigIntValue,R);return RF.match(F).with("number",()=>Number(x)).with("string",()=>x).with("bigint",()=>{return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}).otherwise(()=>x)}getBaseValue(F,$){let P=this.decimalMultiplier/m($||this.decimal||i),N=OP(this.bigIntValue,P);return RF.match(F).with("number",()=>Number(N)).with("string",()=>N.toString()).otherwise(()=>N)}getBigIntValue(F,$){if(!$&&typeof F==="object")return F.bigIntValue;let P=vF(F),N=LF(P);if(N==="0"||N==="undefined")return 0n;return this.#N(N,$)}toSignificant(F=6){let $=this.getValue("string"),[P="",N=""]=$.split("."),R=Number.parseInt(P,10)>0;if((R?P.length+N.length:N.length)<=F)return $;if(P.length>=F)return P.slice(0,F).padEnd(P.length,"0");if(R)return`${P}.${N.slice(0,F-P.length)}`;let A=BigInt(N).toString(),M=A.slice(0,F),G=N.length-A.length;return`0.${M.padStart(G+M.length,"0")}`}toFixed(F=6){let $=this.getValue("string"),P=$.startsWith("-"),[N="0",R=""]=(P?$.slice(1):$).split("."),x=N==="0"&&Number.parseInt(R.slice(0,F),10)===0,A=P&&!x?"-":"";if(F===0){if(N==="0"&&!R)return"0";return R&&Number.parseInt(R[0]||"0",10)>=5?`${A}${BigInt(N)+1n}.0`:`${A}${N}.0`}if(!R)return`${A}${N}.${"0".repeat(F)}`;let M=R[F];if(!(M&&Number.parseInt(M,10)>=5))return`${A}${N}.${R.slice(0,F).padEnd(F,"0")}`;let _=BigInt(R.slice(0,F).padEnd(F,"0"))+1n,Y=10n**BigInt(F);if(_>=Y)return`${A}${BigInt(N)+1n}.${"0".repeat(F)}`;return`${A}${N}.${_.toString().padStart(F,"0")}`}toAbbreviation(F=2){let $=this.getValue("string"),P=Number($),N=["","K","M","B","T","Q","Qi","S"],R=Math.floor(Math.log10(Math.abs(P))/3);if(R===0||!N[R])return $;return`${(P/10**(R*3)).toFixed(F)}${N[R]}`}toCurrency(F="$",{currencyPosition:$="start",decimal:P=2,decimalSeparator:N=".",thousandSeparator:R=",",trimTrailingZeros:x=!0}={}){let A=this.toFixed(P),M=$==="end",[G="0",_=""]=A.split("."),Y=G.replace(/\B(?=(\d{3})+(?!\d))/g,R),Q=_&&Number.parseInt(_,10)>0,W=Q?`${Y}${N}${_}`:Y,v=W.length<100&&x&&Q?W.replace(/\.?0*$/,""):W;return M?`${v}${F}`:`${F}${v}`}formatBigIntToSafeValue(F,$){let P=$||this.decimal||i,N=Math.max(P,NF(this.decimalMultiplier));return D({bigIntDecimal:P,decimal:N,value:F})}#$(F,...$){let P=this.#P(this,...$),N=NF(this.decimalMultiplier),x=Math.max(P,N)+kP,A=m(x),M=$.reduce((_,Y)=>{let Q=this.getBigIntValue(Y,x);return RF.match(F).with("add",()=>_+Q).with("sub",()=>_-Q).with("mul",()=>_*Q/A).with("div",()=>{if(Q===0n)throw RangeError("Division by zero");return _*A/Q}).otherwise(()=>_)},this.bigIntValue*A/this.decimalMultiplier),G=D({bigIntDecimal:x,decimal:x,value:M});return new this.constructor({decimal:this.decimal,decimalMultiplier:m(x),identifier:this.toString(),value:G})}#F(F,...$){let P=this.#P(this,...$),N=this.getBigIntValue($[0]||"0",P),R=this.getBigIntValue(this,P);return RF.match(F).with("gt",()=>R>N).with("gte",()=>R>=N).with("lt",()=>R<N).with("lte",()=>R<=N).with("eqValue",()=>R===N).otherwise(()=>!1)}#R(F){let $=LF(F)||"0";this.bigIntValue=this.#N($)}#P(...F){let $=F.map((P)=>{return typeof P==="object"?P.decimal||NF(P.decimalMultiplier):S$(LF(P))}).filter(Boolean);return Math.max(...$,i)}#N(F,$){let P=$?m($):this.decimalMultiplier,N=NF(P),[R="",x=""]=F.split(".");return BigInt(`${R}${x.padEnd(N,"0")}`)}}var VP=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function LF(F){let P=`${typeof F==="number"?VP.format(F):vF(F)}`.replaceAll(",",".").split(".");return P.length>1?`${P.slice(0,-1).join("")}.${P.at(-1)}`:P[0]||"0"}function S$(F){let $=F.split(".")[1]?.length||0;return Math.max($,i)}function vF(F){return typeof F==="object"?"getValue"in F?F.getValue("string"):F.value:F}function OP(F,$){if($===0n)throw Error("Cannot divide by zero");let P=$/2n;return F>=0n&&$>=0n||F<0n&&$<0n?(F+P)/$:(F-P)/$}function m(F){return 10n**BigInt(F)}function NF(F){return Math.log10(Number.parseFloat(F.toString()))}var o=[z.Chain.Solana,z.Chain.Tron,z.Chain.Near,z.Chain.Sui],fF=[z.Chain.THORChain,z.Chain.Maya],r=new Map,JF=new Map,a=new Map,pP=3600000;function vP(F){let $=a.get(F);if($?.timestamp&&Date.now()-$.timestamp>pP){a.delete(F);return}return $}function DP(F,$){if(a.size>1000){let P=a.keys().next().value;if(P)a.delete(P)}a.set(F,{...$,timestamp:Date.now()})}class t extends O{address;chain;isGasAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:F,decimal:$,tax:P,chain:N,symbol:R,identifier:x}){super(typeof F==="object"?F:{decimal:$,value:F});let A=U$(x||`${N}.${R}`);this.type=PF(A),this.tax=P,this.chain=A.chain,this.ticker=A.ticker,this.symbol=A.symbol,this.address=A.address,this.isSynthetic=A.isSynthetic,this.isTradeAsset=A.isTradeAsset,this.isGasAsset=A.isGasAsset,this.chainId=z.getChainConfig(A.chain).chainId}toString({includeSynthProtocol:F}={}){return(this.isSynthetic||this.isTradeAsset)&&!F?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 F=this.symbol.replace(/\./g,"__");return`${this.chain}.${F}`}getIconUrl(){return r.get(this.toString())?.logoURI}eqAsset({chain:F,symbol:$}){return this.chain===F&&this.symbol===$}eq(F){return this.eqAsset(F)&&this.eqValue(F)}static fromUrl(F,$=0){let P=F.indexOf(".");if(P===-1)throw new L({errorKey:"helpers_invalid_asset_url",info:{urlAsset:F}});let N=F.slice(0,P),R=F.slice(P+1),x=XF.match({chain:N,rest:R}).when(({rest:A})=>A.includes(".."),({chain:A,rest:M})=>`${A}.${M.replace(/\.\./g,"~")}`).when(({chain:A,rest:M})=>fF.includes(A)&&M.includes("."),({chain:A,rest:M})=>`${A}.${M.replace(/\./g,"/")}`).otherwise(({chain:A,rest:M})=>`${A}.${M.replace(/__/g,".")}`);return t.from({asset:x,value:$})}static from({value:F=0,fromBaseDecimal:$,asyncTokenLookup:P,...N}){let R=F instanceof O?F.getValue("string"):F,x=EP(N),A=!x.startsWith(z.Chain.Sui)&&x.includes(":");if(P&&A){let[FF,f]=x.split(":");return fP({address:f,chain:FF,fromBaseDecimal:$,parsedValue:R})}let M=A?x.split(":").join(".UNKNOWN-"):x,{identifier:G,decimal:_}=l(M),{chain:Y,isSynthetic:Q,isTradeAsset:W,address:p}=U$(G),{baseDecimal:v}=z.getChainConfig(Y),C=r.get(o.includes(Y)?G:G.toUpperCase());if(!C&&P&&!Q&&!W)return(async()=>{let{ticker:FF}=s(G),f=await g$({address:p,chain:Y,ticker:FF});return yF({decimal:f.decimals,identifier:f.identifier,value:$?e(BigInt(R),$):R})})();let h=C?.decimal||_;V({condition:!h&&!P,id:`assetValue_static_decimal_not_found_${Y}`,warning:`Couldn't find static decimal for one or more tokens on ${Y} (Using default ${v} decimal as fallback).
1
+ var x={};j(x,{wrapWithThrow:()=>B$,wrapMethodWithNetworkSwitch:()=>lF,warnOnce:()=>O,validateTNS:()=>j$,validateIdentifier:()=>wF,useUSwapStore:()=>q,useUSwapConfig:()=>N$,updateDerivationPath:()=>AF,switchEVMWalletNetwork:()=>cF,providerRequest:()=>qF,prepareNetworkSwitch:()=>GP,okxMobileEnabled:()=>sF,listWeb3EVMWallets:()=>tF,isWeb3Detected:()=>AP,isSecuredAssetIdentifier:()=>D,isGasAsset:()=>zF,isDetected:()=>TP,initializeRPCUrlsWithFallback:()=>_$,getWalletFormatFor:()=>b$,getTHORNameCost:()=>M$,getSymmetricWithdraw:()=>h$,getSymmetricPoolShare:()=>nF,getRPCUrl:()=>C,getMinAmountByChain:()=>g$,getMemoForWithdraw:()=>e$,getMemoForUnbond:()=>i$,getMemoForTcyStake:()=>RP,getMemoForTcyClaim:()=>NP,getMemoForRunePoolWithdraw:()=>FP,getMemoForRunePoolDeposit:()=>r$,getMemoForNameRegister:()=>$P,getMemoForNamePreferredAssetRegister:()=>PP,getMemoForLeaveAndBond:()=>s$,getMemoForDeposit:()=>a$,getMAYANameCost:()=>G$,getLiquiditySlippage:()=>c$,getFeeMultiplierAsBigInt:()=>fF,getFeeMultiplier:()=>JF,getExplorerTxUrl:()=>u$,getExplorerAddressUrl:()=>o$,getEstimatedPoolShare:()=>t$,getETHDefaultWallet:()=>xP,getEIP6963Wallets:()=>KP,getDerivationPathFor:()=>y$,getCommonAssetInfo:()=>r,getChainIdentifier:()=>x$,getAsymmetricRuneWithdrawAmount:()=>m$,getAsymmetricRuneShare:()=>CF,getAsymmetricAssetWithdrawAmount:()=>n$,getAsymmetricAssetShare:()=>mF,getAssetType:()=>NF,formatBigIntToSafeValue:()=>y,findAssetBy:()=>L$,filterSupportedChains:()=>MP,fetchTokenInfo:()=>_F,derivationPathToString:()=>uF,assetFromString:()=>a,applyFeeMultiplierToBigInt:()=>O$,applyFeeMultiplier:()=>p$,addEVMWalletNetwork:()=>dF,addAccountsChangedCallback:()=>BP,WarningCodeEnum:()=>SF,WalletOption:()=>i,USwapNumber:()=>k,USwapError:()=>Y,USwapConfig:()=>g,RequestClient:()=>o,ProviderName:()=>gF,NetworkDerivationPath:()=>u,MemoType:()=>xF,LedgerErrorCode:()=>VF,FeeTypeEnum:()=>kF,FeeOption:()=>BF,ErrorCode:()=>UF,DerivationPath:()=>E$,DEFAULT_FEE_MULTIPLIERS:()=>EF,CommonAssetStrings:()=>w$,BigIntArithmetics:()=>p,AssetValue:()=>n,ApproveMode:()=>IF});module.exports=cP(x);K(x,require("@tcswap/tokens"),module.exports);K(x,require("@tcswap/types"),module.exports);var V$={};j(V$,{getMinAmountByChain:()=>g$,AssetValue:()=>n});var _=require("@tcswap/types"),DF=require("ethers"),LF=require("ts-pattern");var J$={};j(J$,{isSecuredAssetIdentifier:()=>D,isGasAsset:()=>zF,getCommonAssetInfo:()=>r,getAssetType:()=>NF,findAssetBy:()=>L$,fetchTokenInfo:()=>_F,assetFromString:()=>a,CommonAssetStrings:()=>w$});var M=require("@tcswap/types"),PF=require("ts-pattern");var A$={};j(A$,{RequestClient:()=>o});var R$={};j(R$,{useUSwapStore:()=>q,useUSwapConfig:()=>N$,USwapConfig:()=>g});var U=require("@tcswap/types"),F$=require("zustand"),$$=require("zustand/shallow");var eF={};j(eF,{WarningCodeEnum:()=>SF,WalletOption:()=>i,ProviderName:()=>gF,NetworkDerivationPath:()=>u,MemoType:()=>xF,LedgerErrorCode:()=>VF,FeeTypeEnum:()=>kF,FeeOption:()=>BF,ErrorCode:()=>UF,ApproveMode:()=>IF});var GF=require("@tcswap/types"),u=GF.AllChains.reduce((F,$)=>{return F[$]=GF.getChainConfig($).networkDerivationPath,F},{});var UF;((H)=>{H.unknownError="unknownError";H.test_error="test_error";H.providerDetailsError="providerDetailsError";H.blockHeaderNotFound="blockHeaderNotFound";H.blockHashNotFoundAtHeight="blockHashNotFoundAtHeight";H.blockHashNotFoundAtHash="blockHashNotFoundAtHash";H.txHashMissing="txHashMissing";H.assetValueMissingInfo="assetValueMissingInfo";H.invalidAsset="invalidAsset";H.blockIsRequired="blockIsRequired";H.currentBlockHeaderNotFound="currentBlockHeaderNotFound";H.failedToRetrieveBalance="failedToRetrieveBalance";H.failedToRetrieveBlock="failedToRetrieveBlock";H.failedToRetrieveFees="failedToRetrieveFees";H.notImplementedBCH="notImplementedBCH";H.notImplementedDoge="notImplementedDoge";H.noPoolsFound="noPoolsFound";H.noVaultsFound="noVaultsFound";H.noTxFound="noTxFound";H.noInputCoinFound="noInputCoinFound";H.noBlockDataFound="noBlockDataFound";H.multipleCosmosMessages="multipleCosmosMessages";H.heightOrHashNotProvided="heightOrHashNotProvided";H.unknownDenom="unknownDenom";H.invalidBlockHeight="invalidBlockHeight";H.timestampExtrinsicNoArgumentsForBlock="timestampExtrinsicNoArgumentsForBlock";H.timestampExtrinsicNoTimestampForBlock="timestampExtrinsicNoTimestampForBlock";H.noTimestampExtrinsicForHash="noTimestampExtrinsicForHash";H.timestampExtrinsicNoArgumentsForHash="timestampExtrinsicNoArgumentsForHash";H.txMemoUndefined="txMemoUndefined";H.txMemoIncorrect="txMemoIncorrect";H.txTypeNotFound="txTypeNotFound";H.txNoMessage="txNoMessage";H.txNotFound="txNotFound";H.txReceiptNotFound="txReceiptNotFound";H.txParsingError="txParsingError";H.txLogsParsingError="txLogsParsingError";H.blockNotFound="blockNotFound";H.balanceNotFound="balanceNotFound";H.configError="configError";H.synthSwapDisallowed="synthSwapDisallowed";H.providerQuoteTimeout="providerQuoteTimeout";H.noQuoteResponse="noQuoteResponse";H.noPoolAssetsFound="noPoolAssetsFound";H.noThorchainPools="noThorchainPools";H.noMayachainPools="noMayachainPools";H.noThorchainNetworkInfo="noThorchainNetworkInfo";H.invalidAffiliateFee="invalidAffiliateFee";H.invalidBuyAssetAddress="invalidBuyAssetAddress";H.invalidSellAssetAddress="invalidSellAssetAddress";H.invalidSourceAddress="invalidSourceAddress";H.invalidDestinationAddress="invalidDestinationAddress";H.sourceAddressIsSmartContract="sourceAddressIsSmartContract";H.destinationAddressIsSmartContract="destinationAddressIsSmartContract";H.invalidChainId="invalidChainId";H.unsupportedChainId="unsupportedChainId";H.unsupportedEVMChainId="unsupportedEVMChainId";H.unsupportedMethod="unsupportedMethod";H.unsupportedProvider="unsupportedProvider";H.invalidParamsForMethod="invalidParamsForMethod";H.unsupportedAdapter="unsupportedAdapter";H.noWhitelistTokens="noWhitelistTokens";H.failedFetchGasPrice="failedFetchGasPrice";H.failedToCreateDepositChannel="failedToCreateDepositChannel";H.noProviderDetailsFound="noProviderDetailsFound";H.noTokenListsFound="noTokenListsFound";H.tokenNotFound="tokenNotFound";H.tokenPriceNotFound="tokenPriceNotFound";H.tokenPriceFailedToUpdate="tokenPriceFailedToUpdate";H.swapAmountTooSmall="swapAmountTooSmall";H.legsArrayIsEmpty="legsArrayIsEmpty";H.failedToFetchQuoteForLeg="failedToFetchQuoteForLeg";H.noBlockHeaderFound="noBlockHeaderFound";H.failedToSimulateSwap="failedToSimulateSwap";H.addressScreeningFailed="addressScreeningFailed";H.noLiquidtyProvidersFound="noLiquidtyProvidersFound";H.insufficientLiquidity="insufficientLiquidity";H.noInboundDataFound="noInbounDataFound";H.noInboundAddressesFound="noInboundAddressesFound";H.noInboundAddressFoundForChain="noInboundAddressFoundForChain";H.noLastBlocksFound="noLastBlocksFound";H.noVersionFound="noVersionFound";H.noConstantsFound="noConstantsFound";H.noMimirsFound="noMimirsFound";H.noRoutesFound="noRoutesFound";H.quoteNotFound="quoteNotFound";H.ledgerSignFailed="ledgerSignFailed";H.ledgerWrongPayload="ledgerWrongPayload";H.ledgerFetchSwapFailed="ledgerFetchSwapFailed";H.failedToFetchTx="failedToFetchTx";H.failedBuildTransactionDetails="failedBuildTransactionDetails";H.noLegsForRoute="noLegsForRoute";H.noRouterAddressFound="noRouterAddressFound";H.noAggregatorAddressFound="noAggregatorAddressFound";H.noContractInstanceFound="noContractInstanceFound";H.noContractAddressFound="noContractAddressFound";H.invalidAffiliate="invalidAffiliate";H.thornameAffiliate="thornameAffiliate";H.providerNotfound="No provider found";H.noRecordFound="No Record found";H.slippageTooLow="Slippage too low";H.tradingHalted="tradingHalted";H.noWrappedGasAsset="noWrappedGasAsset";H.aggregatorAddressNotFound="aggregatorAddressNotFound";H.routerAddressNotFound="routerAddressNotFound";H.dummyAddressNotFound="dummyAddressNotFound";H.trackerError="trackerError";H.thorchainPoolUnavailable="thorchainPoolUnavailable";H.noOhlcvDataFound="noOhlcvDataFound";H.noTradingPairs="noTradingPairs";H.noLendingAvailability="noLendingAvailability";H.lendingRepayTooSmall="lendingRepayTooSmall";H.missingState="missingState";H.ledgerSwapNotFound="ledgerSwapNotFound";H.ledgerSwapNotReadyForTracking="ledgerSwapNotReadyForTracking";H.errorEstimatingGas="errorEstimatingGas";H.apiKeyInvalid="apiKeyInvalid";H.apiKeyFailedToUpdate="apiKeyFailedToUpdate";H.apiKeyExpired="apiKeyExpired";H.unauthorized="unauthorized";H.failedToCreateMemo="failedToCreateMemo";H.radixIncorrectInstructions="radixIncorrectInstructions";H.radixTxMissedParam="radixTxMissedParam";H.radixTxMissedAccount="radixTxMissedAccount";H.radixManifestParseError="radixManifestParseError";H.radixManifestBuildError="radixManifestBuildError";H.invalidAddressForChain="invalidAddressForChain";H.riskyAddress="riskyAddress";H.noRoutesToProcess="noRoutesToProcess";H.sellAssetAmountTooSmall="sellAssetAmountTooSmall";H.missingPrivateKey="missingPrivateKey";H.noMemoPriceProtection="noMemoPriceProtection";H.rateExpired="rateExpired";H.amountTooSmall="amountTooSmall";H.amountTooBig="amountTooBig";H.amountOutOfRange="amountOutOfRange";H.requestTimeOut="requestTimeOut";H.networkError="networkError";H.unknownApiError="unknownApiError";H.invalidResponseFormat="invalidResponseFormat"})(UF||={});var SF;((P)=>{P.highSlippage="highSlippage";P.highPriceImpact="highPriceImpact"})(SF||={});var gF;((L)=>{L.CAVIAR_V1="CAVIAR_V1";L.CAMELOT_V3="CAMELOT_V3";L.CHAINFLIP="CHAINFLIP";L.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";L.JUPITER="JUPITER";L.MAYACHAIN="MAYACHAIN";L.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";L.OCISWAP_V1="OCISWAP_V1";L.ONEINCH="ONEINCH";L.OPENOCEAN_V2="OPENOCEAN_V2";L.PANCAKESWAP="PANCAKESWAP";L.PANGOLIN_V1="PANGOLIN_V1";L.SUSHISWAP_V2="SUSHISWAP_V2";L.THORCHAIN="THORCHAIN";L.THORCHAIN_STREAMING="THORCHAIN_STREAMING";L.TRADERJOE_V2="TRADERJOE_V2";L.UNISWAP_V2="UNISWAP_V2";L.UNISWAP_V3="UNISWAP_V3";L.NEAR="NEAR";L.GARDEN="GARDEN";L.OKX="OKX"})(gF||={});var kF;((B)=>{B.LIQUIDITY="liquidity";B.NETWORK="network";B.INBOUND="inbound";B.OUTBOUND="outbound";B.AFFILIATE="affiliate";B.TAX="tax";B.PRIORITY="priority";B.SERVICE="service"})(kF||={});var BF;((N)=>{N.Average="average";N.Fast="fast";N.Fastest="fastest"})(BF||={});var IF;((P)=>{P.Approve="approve";P.CheckOnly="checkOnly"})(IF||={});var xF;((Q)=>{Q.NAME_REGISTER="~";Q.BOND="BOND";Q.DEPOSIT="+";Q.LEAVE="LEAVE";Q.UNBOND="UNBOND";Q.WITHDRAW="-";Q.RUNEPOOL_DEPOSIT="POOL+";Q.RUNEPOOL_WITHDRAW="POOL-";Q.CLAIM_TCY="tcy";Q.STAKE_TCY="tcy+";Q.UNSTAKE_TCY="tcy-"})(xF||={});var i;((w)=>{w.BITGET="BITGET";w.BRAVE="BRAVE";w.COINBASE_MOBILE="COINBASE_MOBILE";w.COINBASE_WEB="COINBASE_WEB";w.COSMOSTATION="COSMOSTATION";w.CTRL="CTRL";w.EIP6963="EIP6963";w.EXODUS="EXODUS";w.KEEPKEY="KEEPKEY";w.KEEPKEY_BEX="KEEPKEY_BEX";w.KEPLR="KEPLR";w.KEYSTORE="KEYSTORE";w.LEAP="LEAP";w.LEDGER="LEDGER";w.LEDGER_LIVE="LEDGER_LIVE";w.METAMASK="METAMASK";w.OKX="OKX";w.OKX_MOBILE="OKX_MOBILE";w.ONEKEY="ONEKEY";w.PASSKEYS="PASSKEYS";w.PHANTOM="PHANTOM";w.POLKADOT_JS="POLKADOT_JS";w.RADIX_WALLET="RADIX_WALLET";w.TALISMAN="TALISMAN";w.TREZOR="TREZOR";w.TRONLINK="TRONLINK";w.TRUSTWALLET_WEB="TRUSTWALLET_WEB";w.VULTISIG="VULTISIG";w.WALLETCONNECT="WALLETCONNECT";w.WALLET_SELECTOR="WALLET_SELECTOR";w.XAMAN="XAMAN"})(i||={});var VF;((N)=>{N[N.NoError=36864]="NoError";N[N.LockedDevice=21781]="LockedDevice";N[N.TC_NotFound=65535]="TC_NotFound"})(VF||={});var _P=U.AllChains.reduce((F,$)=>{if(!F.THOR_STAGENET)F[U.StagenetChain.Maya]=U.StagenetMAYAConfig.rpcUrls,F[U.StagenetChain.THORChain]=U.StagenetTHORConfig.rpcUrls;return F[$]=U.getChainConfig($).rpcUrls,F},{}),P$={apiKeys:{blockchair:"",keepKey:"",memoless:"",passkeys:"",uSwap:"",walletConnectProjectId:"",xaman:""},chains:U.AllChains,endpoints:{},envs:{apiUrl:"https://swap-api.unstoppable.money",blockchairApiUrl:null,devApiUrl:"https://swap-api-dev.unstoppable.money",experimental_apiKey:null,experimental_apiUrlQuote:null,experimental_apiUrlSwap:null,isDev:!1,isStagenet:!1,memolessApiUrl:"https://swap.unstoppable.money/memoless/api/v1"},feeMultipliers:void 0,integrations:{radix:{applicationName:"USwap Playground",applicationVersion:"0.0.1",dAppDefinitionAddress:"account_rdx128r289p58222hcvev7frs6kue76pl7pdcnw8725aw658v0zggkh9ws",network:{dashboardBase:"https://dashboard.radixdlt.com",networkId:1,networkName:"mainnet"}}},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:_P,wallets:Object.values(i)},q=F$.create((F)=>({...P$,setApiKey:($,P)=>F((N)=>({apiKeys:{...N.apiKeys,[$]:P}})),setConfig:($)=>F((P)=>({apiKeys:{...P.apiKeys,...$?.apiKeys},chains:P.chains.concat($?.chains||[]),endpoints:{...P.endpoints,...$?.endpoints},envs:{...P.envs,...$?.envs},feeMultipliers:$?.feeMultipliers||P.feeMultipliers,integrations:{...P.integrations,...$?.integrations},rpcUrls:{...P.rpcUrls,...$?.rpcUrls},wallets:P.wallets.concat($?.wallets||[])})),setEndpoint:($,P)=>F((N)=>({endpoints:{...N.endpoints,[$]:P}})),setEnv:($,P)=>F((N)=>({envs:{...N.envs,[$]:P}})),setFeeMultipliers:($)=>F(()=>({feeMultipliers:$})),setIntegrationConfig:($,P)=>F((N)=>({integrations:{...N.integrations,[$]:P}})),setRequestOptions:($)=>F((P)=>({requestOptions:{retry:{...P.requestOptions.retry,...$.retry},timeoutMs:$.timeoutMs||P.requestOptions.timeoutMs}})),setRpcUrl:($,P)=>F((N)=>({rpcUrls:{...N.rpcUrls,[$]:P}}))})),N$=()=>q($$.useShallow((F)=>({apiKeys:F?.apiKeys,chains:F?.chains,endpoints:F?.endpoints,envs:F?.envs,feeMultipliers:F?.feeMultipliers,integrations:F?.integrations,rpcUrls:F?.rpcUrls,wallets:F?.wallets}))),g={get:(F)=>q.getState()[F],getState:q.getState,reinitialize:()=>q.setState(P$),set:(F)=>q.getState().setConfig(F),setApiKey:(F,$)=>q.getState().setApiKey(F,$),setEndpoint:(F,$)=>q.getState().setEndpoint(F,$),setEnv:(F,$)=>q.getState().setEnv(F,$),setFeeMultipliers:(F)=>q.getState().setFeeMultipliers(F),setIntegrationConfig:(F,$)=>q.getState().setIntegrationConfig(F,$),setRequestOptions:(F)=>q.getState().setRequestOptions(F),setRpcUrl:(F,$)=>q.getState().setRpcUrl(F,$)};var H$={};j(H$,{USwapError:()=>Y});var zP={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_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_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_bitkeep_not_found:21001,wallet_bitkeep_failed_to_switch_network:21002,wallet_bitkeep_no_accounts:21003,wallet_passkeys_sign_transaction_error:21101,wallet_passkeys_not_found:21102,wallet_passkeys_no_address:21103,wallet_passkeys_request_canceled:21104,wallet_passkeys_signature_canceled:21105,wallet_passkeys_failed_to_switch_network:21106,wallet_passkeys_chain_not_supported:21107,wallet_passkeys_instance_missing:21108,wallet_onekey_not_found:21201,wallet_onekey_sign_transaction_error:21202,wallet_okx_not_found:21301,wallet_okx_chain_not_supported:21302,wallet_okx_failed_to_switch_network:21303,wallet_okx_no_accounts:21304,wallet_keplr_not_found:21401,wallet_keplr_chain_not_supported:21402,wallet_keplr_signer_not_found:21403,wallet_keplr_no_accounts:21404,wallet_cosmostation_not_found:21501,wallet_cosmostation_chain_not_supported:21502,wallet_cosmostation_evm_provider_not_found:21503,wallet_cosmostation_keplr_provider_not_found:21504,wallet_cosmostation_no_accounts:21505,wallet_cosmostation_no_evm_accounts:21506,wallet_cosmostation_no_evm_address:21507,wallet_cosmostation_signer_not_found:21508,wallet_coinbase_not_found:21701,wallet_coinbase_chain_not_supported:21702,wallet_coinbase_method_not_supported:21703,wallet_coinbase_no_accounts:21704,wallet_evm_extensions_failed_to_switch_network:21801,wallet_evm_extensions_no_provider:21802,wallet_evm_extensions_not_found:21803,wallet_keystore_invalid_password:21901,wallet_keystore_unsupported_version:21902,wallet_near_extensions_failed_to_switch_network:22001,wallet_near_extensions_no_provider:22002,wallet_near_extensions_not_found:22003,wallet_near_method_not_supported:22003,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_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_solana_no_signer:50401,toolbox_solana_fee_estimation_failed:50402,toolbox_solana_broadcast_failed:50403,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_tron_no_signer:50801,toolbox_tron_invalid_token_identifier:50802,toolbox_tron_token_transfer_failed:50803,toolbox_tron_transaction_creation_failed:50804,toolbox_tron_fee_estimation_failed:50805,toolbox_tron_trongrid_api_error:50806,toolbox_tron_approve_failed:50807,toolbox_tron_invalid_token_contract:50808,toolbox_tron_allowance_check_failed:50809,toolbox_near_no_signer:90601,toolbox_near_invalid_address:90602,toolbox_near_invalid_amount:90603,toolbox_near_transfer_failed:90604,toolbox_near_access_key_error:90605,toolbox_near_no_rpc_url:90606,toolbox_near_empty_batch:90607,toolbox_near_balance_failed:90608,toolbox_near_invalid_name:90609,toolbox_near_missing_contract_address:90610,toolbox_near_no_account:90611,toolbox_near_invalid_gas_params:90612,toolbox_near_no_public_key_found:90613,toolbox_sui_address_required:90701,toolbox_sui_keypair_required:90702,toolbox_sui_balance_error:90703,toolbox_sui_transaction_creation_error:90704,toolbox_sui_signing_error:90705,toolbox_sui_broadcast_error:90706,toolbox_sui_no_signer:90707,toolbox_sui_no_sender:90708,toolbox_not_supported:59901,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,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,not_implemented:99999};class Y extends Error{static ErrorCode=zP;constructor(F,$){let P=typeof F==="string",N=P?F:F.errorKey,R=P?void 0:F.info,T=`${N}${R?`: ${JSON.stringify(R)}`:""}`;super(T);if(Object.setPrototypeOf(this,Y.prototype),this.name="USwapError",this.cause=$,$){let A=$ instanceof Error?`${$.message}${$.cause?` (${$.cause})`:""}`:JSON.stringify($);console.error(`USwapError [${N}]: ${A}`)}else if(R)console.error(`USwapError [${N}]: ${JSON.stringify(R)}`)}}var wP=(F)=>new Promise(($)=>setTimeout($,F)),XP=(F,{baseDelay:$,backoffMultiplier:P,maxDelay:N})=>Math.min($*P**F,N),YP=async(F,$)=>{let P=await fetch(F,$);if(!P.ok){let N=await P.json().catch(()=>null),R={status:P.status,statusText:P.statusText},T={...R,...N&&{errorData:N}};throw new Y({errorKey:"helpers_invalid_response",info:R},T)}return P.json()};function KF(F,$={}){return async function(N,R={}){let{searchParams:T,json:A,body:G,headers:B,dynamicHeader:z,retry:X,timeoutMs:Q,abortController:S,onError:I,onSuccess:b,responseHandler:s,...h}={...$,...R},E=g.get("requestOptions"),V={...E.retry,...X},f=!!A||N.endsWith(".json"),WF=JP(N,T),L=LP(f,{...B,...z?.()}),iF=f?JSON.stringify(A):G,t;for(let v=0;v<=V.maxRetries;v++){let rF=S||new AbortController,aF=setTimeout(()=>rF.abort(),Q||E.timeoutMs);try{let c=await YP(WF,{...h,body:iF,headers:L,method:F,signal:rF.signal});return clearTimeout(aF),b?.(c)||s?.(c)||c}catch(c){if(clearTimeout(aF),t=c,v>=V.maxRetries)return I?I(c):Promise.reject(c);await wP(XP(v,V))}}return I?I(t):Promise.reject(t)}}function LP(F,$){return{...$,...F&&{"Content-Type":"application/json"}}}function JP(F,$){let P=new URL(F);if($)P.search=new URLSearchParams($).toString();return P.toString()}var o={extend:(F)=>({extend:($)=>o.extend({...F,...$}),get:KF("GET",F),post:KF("POST",F)}),get:KF("GET"),post:KF("POST")};var z$={};j(z$,{initializeRPCUrlsWithFallback:()=>_$,getRPCUrl:()=>C});var Z=require("@tcswap/types"),pF=require("ts-pattern");var K$={};j(K$,{wrapWithThrow:()=>B$,warnOnce:()=>O,getTHORNameCost:()=>M$,getMAYANameCost:()=>G$,getChainIdentifier:()=>x$});var QF=require("@tcswap/types");function M$(F){if(F<0)throw new Y({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:F}});return 10+F}function G$(F){if(F<0)throw new Y({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:F}});return Math.round((10+F*1.0512)*10000000000)/10000000000}function B$(F,$){try{return F()}catch(P){if($)throw new Y($,P);return}}function x$(F){switch(F){case QF.Chain.THORChain:return`${F}.RUNE`;case QF.Chain.Cosmos:return`${F}.ATOM`;case QF.Chain.BinanceSmartChain:return`${F}`;default:return`${F}.${F}`}}var T$=new Set;function O({condition:F,id:$,warning:P}){if(F){if(T$.has($))return;console.warn(P),T$.add($)}}function ZP(F){return pF.match(F).with(...Z.EVMChains,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...Z.UTXOChains,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...Z.CosmosChains,...Z.StagenetChains,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(Z.Chain.Polkadot,Z.Chain.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(Z.Chain.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(Z.Chain.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(Z.Chain.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(Z.Chain.Tron,Z.Chain.Radix,()=>"").with(Z.Chain.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(Z.Chain.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).otherwise(()=>{throw new Y("helpers_chain_not_supported",{chain:F})})}function jP(F){return pF.match(F).with(Z.Chain.Radix,()=>"/status/network-configuration").with(Z.Chain.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function Q$(F,$){try{let P=$.startsWith("wss")?$.replace("wss","https"):$;return(await fetch(`${P}${jP(F)}`,{body:JSON.stringify(ZP(F)),headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var OF=new Map,qP=120000;async function C(F){let{isStagenet:$}=g.get("envs"),[P="",...N]=g.get("rpcUrls")[F];if(!P)throw O({condition:!0,id:"helpers_chain_no_public_or_set_rpc_url",warning:`No public or set RPC URL found for chain. Please ensure you configured rpcUrls for ${F}.`}),new Y("helpers_chain_no_public_or_set_rpc_url",{chain:F});if($)return P;let R=OF.get(F);if(R&&Date.now()-R.timestamp<qP)return R.url;if(!await Q$(F,P)){for(let A of N)if(await Q$(F,A))return OF.set(F,{timestamp:Date.now(),url:A}),A}return OF.set(F,{timestamp:Date.now(),url:P}),P}function _$(F){O({condition:!0,id:"initializeRPCUrlsWithFallback",warning:"initializeRPCUrlsWithFallback is deprecated. Use static { rpcUrls, fallbackRpcUrls } USwap init config or dynamic USwapConfig.setRpcUrl/setFallbackRpcUrl to configure RPC endpoints."})}var w$=[`${M.Chain.Maya}.MAYA`,`${M.Chain.Maya}.CACAO`,`${M.Chain.Ethereum}.THOR`,`${M.Chain.Ethereum}.vTHOR`,`${M.Chain.Kujira}.USK`,`${M.Chain.Ethereum}.FLIP`,`${M.Chain.Radix}.XRD`],X$=[M.Chain.Arbitrum,M.Chain.Aurora,M.Chain.Base,M.Chain.Ethereum,M.Chain.Optimism];async function WP(F){let{baseDecimal:$}=M.getChainConfig(M.Chain.Radix);try{let P=await C(M.Chain.Radix),{manager:N}=await o.post(`${P}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:F}),headers:{Accept:"*/*","Content-Type":"application/json"}});return N?.divisibility?.value?.divisibility}catch(P){let N=P instanceof Error?P.message:String(P);return console.warn(`Failed to fetch Radix asset decimals for ${F}: ${N}`),$}}async function UP(F){try{let $=await C(M.Chain.Radix);return(await o.post(`${$}/state/entity/details`,{body:JSON.stringify({addresses:[F],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((R)=>R.key==="symbol")?.value.typed.value||void 0}catch($){let P=$ instanceof Error?$.message:String($);return console.warn(`Failed to fetch Radix asset symbol for ${F}: ${P}`),""}}async function Y$({chain:F,address:$,methodHex:P,id:N}){let R=await C(F);return o.post(R,{body:JSON.stringify({id:N,jsonrpc:"2.0",method:"eth_call",params:[{data:P,to:$.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}async function SP(F){if(!F||F==="0x")return"UNKNOWN";try{let{AbiCoder:$}=await import("ethers");return $.defaultAbiCoder().decode(["string"],F)[0].trim()}catch($){return console.warn(`Failed to decode ABI string from ${F}: ${$}`),"UNKNOWN"}}function gP(F,$){if(!F||F==="0x")return $;try{return Number(F)}catch(P){return console.warn(`Failed to decode ABI uint8 from ${F}: ${P}`),$}}async function kP({chain:F,address:$}){let{baseDecimal:P}=M.getChainConfig(F),N=$.toLowerCase();if($===""||!N.startsWith("0x"))return P;let R=await Y$({address:$,chain:F,id:2,methodHex:"0x313ce567"}).catch((A)=>{return console.warn(`Could not fetch decimals for ${$} on ${F}: ${A.message}`),{result:""}});return gP(R.result,P)}async function IP({chain:F,address:$}){let P=$.toLowerCase();if(P===""||!P.startsWith("0x"))return;let N=await Y$({address:$,chain:F,id:1,methodHex:"0x95d89b41"}).catch((T)=>{return console.warn(`Could not fetch symbol for ${$} on ${F}: ${T.message}`),{result:""}});return await SP(N.result)}function _F({chain:F,address:$}){let{baseDecimal:P}=M.getChainConfig(F),N={decimals:P,ticker:void 0};return PF.match(F).with(...M.EVMChains,async()=>{try{let{isAddress:R,getAddress:T}=await import("ethers");if(!R(T($.replace(/^0X/,"0x"))))return N;let[A,G]=await Promise.all([IP({address:$,chain:F}),kP({address:$,chain:F})]);return{decimals:G,ticker:A}}catch(R){return console.warn(`Failed to fetch token info for ${$} on ${F}: ${R?.code} ${R?.message}`),N}}).with(M.Chain.Solana,async()=>{if(!$)return N;try{let R=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${$}`);if(R.ok){let T=await R.json(),A=Array.isArray(T)?T[0]:T;if(A)return{decimals:A.decimals??P,ticker:A.symbol||void 0}}}catch(R){console.warn(`Failed to fetch Solana token info for ${$}: ${R?.code} ${R?.message}`)}return N}).with(M.Chain.Tron,async()=>{if(!$)return N;try{let R=await import("tronweb"),T=R.TronWeb??R.default?.TronWeb,A=await C(M.Chain.Tron),B=await new T({fullHost:A,privateKey:"0000000000000000000000000000000000000000000000000000000000000001"}).contract().at($),[z,X]=await Promise.all([B.symbol().call().catch((Q)=>{console.warn(`Could not fetch symbol for ${$} on Tron:`,Q);return}),B.decimals().call().catch((Q)=>{return console.warn(`Could not fetch decimals for ${$} on Tron:`,Q),P})]);return{decimals:typeof X==="number"?X:Number(X||P),ticker:z||void 0}}catch(R){let T=R instanceof Error?R.message:String(R);return console.warn(`Failed to fetch Tron token info for ${$}: ${T}`),N}}).with(M.Chain.Near,async()=>{if(!$)return N;try{let{JsonRpcProvider:R}=await import("@near-js/providers"),T=await C(M.Chain.Near),G=await new R({url:T}).query({account_id:$,args_base64:Buffer.from("{}").toString("base64"),finality:"final",method_name:"ft_metadata",request_type:"call_function"}),B=JSON.parse(Buffer.from(G.result).toString());return{decimals:B?.decimals||P,ticker:B?.symbol}}catch(R){let T=R instanceof Error?R.message:String(R);return console.warn(`Failed to fetch Near token info for ${$}: ${T}`),N}}).with(M.Chain.Radix,async()=>{if(!$)return N;try{let[R,T]=await Promise.all([UP($),WP($)]);return{decimals:T,ticker:R}}catch(R){let T=R instanceof Error?R.message:String(R);return console.warn(`Failed to fetch Radix token info for ${$}: ${T}`),N}}).otherwise(async()=>N)}function zF({chain:F,symbol:$}){return PF.match(F).with(...X$,()=>$==="ETH").with(M.Chain.Avalanche,()=>$==="AVAX").with(M.Chain.Berachain,()=>$==="BERA").with(M.Chain.BinanceSmartChain,()=>$==="BNB").with(M.Chain.Gnosis,()=>$==="xDAI"||$==="XDAI").with(M.Chain.Monad,()=>$==="MON").with(M.Chain.XLayer,()=>$==="OKB").with(M.Chain.Maya,()=>$==="CACAO").with(M.Chain.Cosmos,()=>$==="ATOM").with(M.Chain.THORChain,()=>$==="RUNE").with(M.Chain.Tron,()=>$==="TRX").with(M.Chain.Radix,()=>`${F}.${$}`===r(F).identifier).otherwise(()=>$===F)}var r=(F)=>{let{baseDecimal:$}=M.getChainConfig(F);return PF.match(F.toUpperCase()).with(...X$,(N)=>({decimal:$,identifier:`${N}.ETH`})).with(M.Chain.THORChain,(N)=>({decimal:$,identifier:`${N}.RUNE`})).with(M.Chain.Cosmos,(N)=>({decimal:$,identifier:`${N}.ATOM`})).with(M.Chain.Maya,(N)=>({decimal:10,identifier:`${N}.CACAO`})).with(M.Chain.BinanceSmartChain,(N)=>({decimal:$,identifier:`${N}.BNB`})).with(M.Chain.Monad,(N)=>({decimal:$,identifier:`${N}.MON`})).with(M.Chain.Avalanche,(N)=>({decimal:$,identifier:`${N}.AVAX`})).with(M.Chain.Gnosis,(N)=>({decimal:$,identifier:`${N}.xDAI`})).with(M.Chain.XLayer,(N)=>({decimal:$,identifier:`${N}.OKB`})).with(M.Chain.Berachain,(N)=>({decimal:$,identifier:`${N}.BERA`})).with(M.Chain.Tron,(N)=>({decimal:$,identifier:`${N}.TRX`})).with(M.Chain.Solana,M.Chain.Chainflip,M.Chain.Kujira,M.Chain.Ripple,M.Chain.Polkadot,M.Chain.Near,...M.UTXOChains,(N)=>({decimal:$,identifier:`${N}.${N}`})).with(M.Chain.Radix,"XRD.XRD",()=>({decimal:$,identifier:"XRD.XRD"})).with(M.Chain.Polygon,"POL.POL",()=>({decimal:$,identifier:"POL.POL"})).with("KUJI.USK",(N)=>({decimal:6,identifier:N})).with("ETH.FLIP",()=>({decimal:M.getChainConfig(M.Chain.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:M.getChainConfig(M.Chain.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:M.getChainConfig(M.Chain.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(N)=>({decimal:10,identifier:N})).with("MAYA.MAYA",(N)=>({decimal:4,identifier:N})).otherwise(()=>({decimal:$,identifier:F}))};function D(F=""){if(!F)return!1;if(F.includes("/")||F.includes("~"))return!1;let $=F.toUpperCase();if($.includes("."))return!1;let P=$.indexOf("-");if(P<=0)return!1;let N=$.slice(0,P),R=$.slice(P+1);if(!N||!R)return!1;if(N===M.Chain.THORChain||N===M.Chain.Maya)return!1;if(!M.AllChains.includes(N))return!1;if(R.startsWith("0X"))return!1;return!0}function NF({chain:F,symbol:$}){if($.includes("/"))return"Synth";if($.includes("~"))return"Trade";if(F===M.Chain.THORChain&&D($))return"Secured";return PF.match(F).with(M.Chain.Radix,()=>$===M.Chain.Radix||`${F}.${$}`===r(F).identifier).with(M.Chain.Arbitrum,M.Chain.Optimism,M.Chain.Base,M.Chain.Aurora,()=>$===M.Chain.Ethereum).with(M.Chain.Cosmos,()=>$==="ATOM").with(M.Chain.BinanceSmartChain,()=>$==="BNB").with(M.Chain.Maya,()=>$==="CACAO").with(M.Chain.Monad,()=>$==="MON").with(M.Chain.THORChain,()=>$==="RUNE").with(M.Chain.Tron,()=>$==="TRX").with(M.Chain.XLayer,()=>$==="OKB").otherwise(()=>$===F)?"Native":F}var a=(F)=>{let[$,...P]=F.split("."),N=F.includes("/"),R=P.join("."),T=R?.split("-"),A=T?.length?T.length===1?T[0]:T.slice(0,-1).join("-"):void 0;return{chain:$,symbol:R,synth:N,ticker:A}};async function L$(F){let{loadTokenLists:$}=await import("./tokens.cjs"),P=await $();for(let N of Object.values(P))for(let{identifier:R,chain:T,...A}of N.tokens){if("identifier"in F&&R===F.identifier)return R;if("address"in A&&"chain"in F&&T===F.chain&&A.address&&A.address.toLowerCase()===F.contract.toLowerCase())return R}return}var q$={};j(q$,{validateTNS:()=>j$,validateIdentifier:()=>wF});var Z$=["TERRA",...g.get("chains")];function wF(F=""){let $=F.toUpperCase(),[P]=$.split(".");if(Z$.includes(P))return!0;let[N]=$.split("/");if(Z$.includes(N))return!0;if(D(F))return!0;throw new Y({errorKey:"helpers_invalid_identifier",info:{identifier:F,message:`Invalid identifier: ${F}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}function j$(F){if(F.length>30)return!1;let $=/^[a-zA-Z0-9+_-]+$/g;return!!F.match($)}var U$={};j(U$,{formatBigIntToSafeValue:()=>y,BigIntArithmetics:()=>p});var HF=require("ts-pattern"),e=8,VP=10;function y({value:F,bigIntDecimal:$=e,decimal:P=e}){if(P===0)return F.toString();let N=F<0n,R=F.toString().substring(N?1:0),T=P-(R.length-1);if(T>0)R="0".repeat(T)+R;let A=R.length-P,G=R.slice(-P);if(Number.parseInt(G[$]||"0",10)>=5){let z=Number.parseInt(G[$-1]||"0",10);G=`${G.substring(0,$-1)}${z+1}`}else G=G.substring(0,$);return`${N?"-":""}${R.slice(0,A)}.${G}`.replace(/\.?0*$/,"")}class p{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(F,$){return new p({decimal:$,value:y({bigIntDecimal:$,decimal:$,value:F})})}static shiftDecimals({value:F,from:$,to:P}){return p.fromBigInt(F.getBaseValue("bigint")*l(P)/l($),P)}constructor(F){let $=vF(F),P=typeof F==="object";this.decimal=P?F.decimal:void 0,this.decimalMultiplier=P&&"decimalMultiplier"in F?F.decimalMultiplier:l(Math.max(W$(XF($)),this.decimal||0)),this.#R($)}set(F){return new this.constructor({decimal:this.decimal,identifier:this.toString?.({includeSynthProtocol:!0}),value:F})}add(...F){return this.#$("add",...F)}sub(...F){return this.#$("sub",...F)}mul(...F){return this.#$("mul",...F)}div(...F){return this.#$("div",...F)}gt(F){return this.#F("gt",F)}gte(F){return this.#F("gte",F)}lt(F){return this.#F("lt",F)}lte(F){return this.#F("lte",F)}eqValue(F){return this.#F("eqValue",F)}getValue(F,$){let P=RF(this.decimalMultiplier),N=$!==void 0?$:this.decimal,R=N!==void 0?N:P;if(N!==void 0&&N<P){if(this.formatBigIntToSafeValue(this.bigIntValue,N)==="0"&&this.bigIntValue!==0n)R=P}let T=this.formatBigIntToSafeValue(this.bigIntValue,R);return HF.match(F).with("number",()=>Number(T)).with("string",()=>T).with("bigint",()=>{return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}).otherwise(()=>T)}getBaseValue(F,$){let P=this.decimalMultiplier/l($||this.decimal||e),N=pP(this.bigIntValue,P);return HF.match(F).with("number",()=>Number(N)).with("string",()=>N.toString()).otherwise(()=>N)}getBigIntValue(F,$){if(!$&&typeof F==="object")return F.bigIntValue;let P=vF(F),N=XF(P);if(N==="0"||N==="undefined")return 0n;return this.#N(N,$)}toSignificant(F=6){let $=this.getValue("string"),[P="",N=""]=$.split("."),R=Number.parseInt(P,10)>0;if((R?P.length+N.length:N.length)<=F)return $;if(P.length>=F)return P.slice(0,F).padEnd(P.length,"0");if(R)return`${P}.${N.slice(0,F-P.length)}`;let A=BigInt(N).toString(),G=A.slice(0,F),B=N.length-A.length;return`0.${G.padStart(B+G.length,"0")}`}toFixed(F=6){let $=this.getValue("string"),P=$.startsWith("-"),[N="0",R=""]=(P?$.slice(1):$).split("."),T=N==="0"&&Number.parseInt(R.slice(0,F),10)===0,A=P&&!T?"-":"";if(F===0){if(N==="0"&&!R)return"0";return R&&Number.parseInt(R[0]||"0",10)>=5?`${A}${BigInt(N)+1n}.0`:`${A}${N}.0`}if(!R)return`${A}${N}.${"0".repeat(F)}`;let G=R[F];if(!(G&&Number.parseInt(G,10)>=5))return`${A}${N}.${R.slice(0,F).padEnd(F,"0")}`;let z=BigInt(R.slice(0,F).padEnd(F,"0"))+1n,X=10n**BigInt(F);if(z>=X)return`${A}${BigInt(N)+1n}.${"0".repeat(F)}`;return`${A}${N}.${z.toString().padStart(F,"0")}`}toAbbreviation(F=2){let $=this.getValue("string"),P=Number($),N=["","K","M","B","T","Q","Qi","S"],R=Math.floor(Math.log10(Math.abs(P))/3);if(R===0||!N[R])return $;return`${(P/10**(R*3)).toFixed(F)}${N[R]}`}toCurrency(F="$",{currencyPosition:$="start",decimal:P=2,decimalSeparator:N=".",thousandSeparator:R=",",trimTrailingZeros:T=!0}={}){let A=this.toFixed(P),G=$==="end",[B="0",z=""]=A.split("."),X=B.replace(/\B(?=(\d{3})+(?!\d))/g,R),Q=z&&Number.parseInt(z,10)>0,S=Q?`${X}${N}${z}`:X,b=S.length<100&&T&&Q?S.replace(/\.?0*$/,""):S;return G?`${b}${F}`:`${F}${b}`}formatBigIntToSafeValue(F,$){let P=$||this.decimal||e,N=Math.max(P,RF(this.decimalMultiplier));return y({bigIntDecimal:P,decimal:N,value:F})}#$(F,...$){let P=this.#P(this,...$),N=RF(this.decimalMultiplier),T=Math.max(P,N)+VP,A=l(T),G=$.reduce((z,X)=>{let Q=this.getBigIntValue(X,T);return HF.match(F).with("add",()=>z+Q).with("sub",()=>z-Q).with("mul",()=>z*Q/A).with("div",()=>{if(Q===0n)throw RangeError("Division by zero");return z*A/Q}).otherwise(()=>z)},this.bigIntValue*A/this.decimalMultiplier),B=y({bigIntDecimal:T,decimal:T,value:G});return new this.constructor({decimal:this.decimal,decimalMultiplier:l(T),identifier:this.toString(),value:B})}#F(F,...$){let P=this.#P(this,...$),N=this.getBigIntValue($[0]||"0",P),R=this.getBigIntValue(this,P);return HF.match(F).with("gt",()=>R>N).with("gte",()=>R>=N).with("lt",()=>R<N).with("lte",()=>R<=N).with("eqValue",()=>R===N).otherwise(()=>!1)}#R(F){let $=XF(F)||"0";this.bigIntValue=this.#N($)}#P(...F){let $=F.map((P)=>{return typeof P==="object"?P.decimal||RF(P.decimalMultiplier):W$(XF(P))}).filter(Boolean);return Math.max(...$,e)}#N(F,$){let P=$?l($):this.decimalMultiplier,N=RF(P),[R="",T=""]=F.split(".");return BigInt(`${R}${T.padEnd(N,"0")}`)}}var OP=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function XF(F){let P=`${typeof F==="number"?OP.format(F):vF(F)}`.replaceAll(",",".").split(".");return P.length>1?`${P.slice(0,-1).join("")}.${P.at(-1)}`:P[0]||"0"}function W$(F){let $=F.split(".")[1]?.length||0;return Math.max($,e)}function vF(F){return typeof F==="object"?"getValue"in F?F.getValue("string"):F.value:F}function pP(F,$){if($===0n)throw Error("Cannot divide by zero");let P=$/2n;return F>=0n&&$>=0n||F<0n&&$<0n?(F+P)/$:(F-P)/$}function l(F){return 10n**BigInt(F)}function RF(F){return Math.log10(Number.parseFloat(F.toString()))}var m=[_.Chain.Solana,_.Chain.Tron,_.Chain.Near,_.Chain.Sui],bF=[_.Chain.THORChain,_.Chain.Maya],FF=new Map,YF=new Map,$F=new Map,vP=3600000;function DP(F){let $=$F.get(F);if($?.timestamp&&Date.now()-$.timestamp>vP){$F.delete(F);return}return $}function yP(F,$){if($F.size>1000){let P=$F.keys().next().value;if(P)$F.delete(P)}$F.set(F,{...$,timestamp:Date.now()})}class n extends p{address;chain;isGasAsset=!1;isSecuredAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:F,decimal:$,tax:P,chain:N,symbol:R,identifier:T}){super(typeof F==="object"?F:{decimal:$,value:F});let A=S$(T||`${N}.${R}`);this.type=NF(A),this.tax=P,this.chain=A.chain,this.ticker=A.ticker,this.symbol=A.symbol,this.address=A.address,this.isSynthetic=A.isSynthetic,this.isTradeAsset=A.isTradeAsset,this.isSecuredAsset=A.isSecuredAsset??!1,this.isGasAsset=A.isGasAsset,this.chainId=_.getChainConfig(A.chain).chainId}toString({includeSynthProtocol:F}={}){return(this.isSynthetic||this.isTradeAsset||this.isSecuredAsset)&&!F?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,"..")}`;if(this.isSecuredAsset)return`${this.chain}.${this.symbol}`;let F=this.symbol.replace(/\./g,"__");return`${this.chain}.${F}`}getIconUrl(){return FF.get(this.toString())?.logoURI}eqAsset({chain:F,symbol:$}){return this.chain===F&&this.symbol===$}eq(F){return this.eqAsset(F)&&this.eqValue(F)}static fromUrl(F,$=0){let P=F.indexOf(".");if(P===-1)throw new Y({errorKey:"helpers_invalid_asset_url",info:{urlAsset:F}});let N=F.slice(0,P),R=F.slice(P+1),T=LF.match({chain:N,rest:R}).when(({rest:A})=>A.includes(".."),({chain:A,rest:G})=>`${A}.${G.replace(/\.\./g,"~")}`).when(({chain:A,rest:G})=>bF.includes(A)&&G.includes("."),({chain:A,rest:G})=>`${A}.${G.replace(/\./g,"/")}`).otherwise(({chain:A,rest:G})=>`${A}.${G.replace(/__/g,".")}`);return n.from({asset:T,value:$})}static from({value:F=0,fromBaseDecimal:$,asyncTokenLookup:P,...N}){let R=F instanceof p?F.getValue("string"):F,T=oP(N),A=!T.startsWith(_.Chain.Sui)&&T.includes(":");if(P&&A){let[t,v]=T.split(":");return fP({address:v,chain:t,fromBaseDecimal:$,parsedValue:R})}let G=A?T.split(":").join(".UNKNOWN-"):T,{identifier:B,decimal:z}=r(G),{chain:X,isSynthetic:Q,isTradeAsset:S,isSecuredAsset:I,address:b}=S$(B),{baseDecimal:s}=_.getChainConfig(X),h=FF.get(m.includes(X)?B:B.toUpperCase());if(!h&&P&&!Q&&!S&&!I)return(async()=>{let{ticker:t}=a(B),v=await k$({address:b,chain:X,ticker:t});return yF({decimal:v.decimals,identifier:v.identifier,value:$?d(BigInt(R),$):R})})();let E=h?.decimal||z;O({condition:!E&&!P,id:`assetValue_static_decimal_not_found_${X}`,warning:`Couldn't find static decimal for one or more tokens on ${X} (Using default ${s} decimal as fallback).
2
2
  This can result in incorrect calculations and mess with amount sent on transactions.
3
3
  You can load static assets by installing @tcswap/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:y,identifier:k,tax:c}=C||{decimal:h||v,identifier:G},TF=$?e(BigInt(R),$):e(R,y);return Q||W?yP(k,TF):yF({decimal:y,identifier:k,tax:c,value:TF})}static async loadStaticAssets(F){let{loadTokenLists:$}=await import("@tcswap/tokens"),P=await $(F);for(let{tokens:N}of Object.values(P))for(let{identifier:R,chain:x,...A}of N){let M=z.getChainConfig(x),G=o.includes(M.chain)?R:R.toUpperCase(),Y={decimal:"decimals"in A?A.decimals:M.baseDecimal,identifier:R,logoURI:"logoURI"in A?A.logoURI:void 0,tax:"tax"in A?A.tax:void 0};if(r.set(G,Y),"address"in A&&A.address){let Q=o.includes(M.chain)?`${M.chain}:${A.address}`:`${M.chain}:${A.address.toUpperCase()}`;JF.set(Q,R)}}return!0}static setStaticAssets(F){r.clear(),JF.clear();for(let[$,P]of F.entries()){let N=o.includes(P.chain)?P.identifier:P.identifier.toUpperCase(),R="decimals"in P?P.decimals:P.decimal,x={...P,decimal:R,identifier:N};if(r.set($,x),P.address){let A=o.includes(P.chain)?`${P.chain}:${P.address}`:`${P.chain}:${P.address.toUpperCase()}`;JF.set(A,P.identifier)}}return!0}static get staticAssets(){return r}}function W$(F){let $=t.from({chain:F});return XF.match(F).with(z.Chain.Bitcoin,z.Chain.Litecoin,z.Chain.BitcoinCash,z.Chain.Dash,()=>$.set(0.00010001)).with(z.Chain.Dogecoin,()=>$.set(1.00000001)).with(z.Chain.Avalanche,z.Chain.Ethereum,z.Chain.Arbitrum,z.Chain.BinanceSmartChain,()=>$.set(0.00000001)).with(z.Chain.THORChain,z.Chain.Maya,()=>$.set(0)).with(z.Chain.Cosmos,z.Chain.Kujira,()=>$.set(0.000001)).otherwise(()=>$.set(0.00000001))}async function g$({chain:F,address:$,ticker:P}){let R=o.includes(F)?`${F}:${$||P}`:`${F}:${$||P}`.toUpperCase(),x=vP(R);if(x)return x;if(!$){let{baseDecimal:G}=z.getChainConfig(F);return{decimals:G,identifier:`${F}.${P||"UNKNOWN"}`}}let A=await zF({address:$,chain:F}),M=`${F}.${A.ticker||P||"UNKNOWN"}-${$}`;return V({condition:!!(!A.ticker&&P),id:`async_token_lookup_failed_${F}_${$}`,warning:`Could not fetch token metadata for ${F}:${$} from chain. Using user-provided ticker (${P}) with baseDecimal (${A.decimals}).`}),A.ticker&&DP(R,{decimals:A.decimals,identifier:M}),{decimals:A.decimals,identifier:M}}function yF({identifier:F,decimal:$,value:P,tax:N}){return YF(F),new t({decimal:$,identifier:F,tax:N,value:e(P,$)})}function yP(F,$=0){let P=F.includes(".")?F.split(".")?.[0]?.toUpperCase():void 0,N=P?fF.includes(P):!1,R=F.slice(0,14).includes("~")?"~":"/",[x,A]=N?F.split(".").slice(1).join().split(R):F.split(R);if(!(x&&A))throw new L({errorKey:"helpers_invalid_asset_identifier",info:{identifier:F}});return new t({decimal:8,identifier:`${P||z.Chain.THORChain}.${x}${R}${A}`,value:e($,8)})}async function fP({address:F,chain:$,fromBaseDecimal:P,parsedValue:N}){let{decimals:R,identifier:x}=await g$({address:F,chain:$}),A=P?e(BigInt(N),P):N;return yF({decimal:R,identifier:x,value:A})}function e(F,$){return typeof F==="bigint"?D({bigIntDecimal:$,decimal:$,value:F}):F}function bP(F){let $=XF.match(F).when((P)=>("chain"in P)&&P.chain!==void 0,({chain:P})=>P).otherwise((P)=>{let N=s(P.asset);return N.synth?z.Chain.THORChain:N.chain});if(!z.AllChains.includes($.toUpperCase()))throw new L({errorKey:"helpers_invalid_asset_identifier",info:{message:"Please use the AssetValue constructor for unsupported chains"}})}function EP(F){if(bP(F),"chain"in F){let{chain:R,address:x}=F;if(x){let A=o.includes(R)?`${R}:${x}`:`${R}:${x.toUpperCase()}`,M=JF.get(A);if(M)return M;return A}return R}let{chain:$,symbol:P}=s(F.asset);return PF({chain:$,symbol:P})==="Native"?$:F.asset}function uP(F,$,P){let N=F.split("."),R=N[0]?.toUpperCase(),x=fF.includes(R),A=P?"~":"/",[M,G=""]=x?N.slice(1).join(".").split(A):F.split(A);if(!(M&&G))throw new L({errorKey:"helpers_invalid_asset_identifier",info:{identifier:F}});let{ticker:_,address:Y}=I$({chain:M,symbol:G}),Q=`${M}${A}${G}`;return{address:Y,chain:R,isGasAsset:!1,isSynthetic:$,isTradeAsset:P,symbol:Q,ticker:_}}function oP(F){let $=F.indexOf("."),P=($===-1?F:F.slice(0,$)).toUpperCase(),N=$===-1?F:F.slice($+1),{address:R,ticker:x}=I$({chain:P,symbol:N}),A;try{A=R&&z.EVMChains.includes(P)&&DF.getAddress(R)?DF.getAddress(R):R}catch{A=R}let M=A?`${x}-${A}`:N;return{address:A,chain:P,isGasAsset:wF({chain:P,symbol:N}),isSynthetic:!1,isTradeAsset:!1,symbol:M,ticker:x}}function U$(F){let $=F.slice(0,14),P=$.includes("/"),N=$.includes("~");if(P||N)return uP(F,P,N);return oP(F)}function CP(F,$=!1){let P=$?F.indexOf("-"):F.lastIndexOf("-");if(P===-1)return{address:void 0,ticker:F};let N=F.slice(0,P);return{address:F.slice(P+1),ticker:N}}function I$({symbol:F,chain:$}){let{ticker:P,address:N}=CP(F,$===z.Chain.Near);return{address:N&&!o.includes($)?N.toLowerCase():N,ticker:P}}var p$={};j(p$,{getFeeMultiplierAsBigInt:()=>EF,getFeeMultiplier:()=>ZF,applyFeeMultiplierToBigInt:()=>V$,applyFeeMultiplier:()=>O$,DEFAULT_FEE_MULTIPLIERS:()=>bF});var bF={average:1,fast:1.5,fastest:2};function ZF(F="average"){let $=g.get("feeMultipliers");if($&&$[F]!==void 0)return $[F];return bF[F]}function EF(F="average"){let $=ZF(F),P=10n,N=BigInt(Math.round($*10));return{denominator:P,numerator:N}}function V$(F,$="average"){let{numerator:P,denominator:N}=EF($);return F*P/N}function O$(F,$="average",P=!1){let N=ZF($),R=F*N;return P?Math.floor(R):R}var v$={};j(v$,{USwapNumber:()=>I});class I extends O{eq(F){return this.eqValue(F)}static fromBigInt(F,$){return new I({decimal:$,value:D({bigIntDecimal:$,decimal:$,value:F})})}}var b$={};j(b$,{updateDerivationPath:()=>HF,getWalletFormatFor:()=>y$,getDerivationPathFor:()=>D$,derivationPathToString:()=>uF,DerivationPath:()=>f$});var AF=require("@tcswap/types");function HF(F,$){if("index"in $)return[...F.slice(0,F.length-1),$.index];if("change"in $){let[P,N,R,,x]=F;return[P,N,R,$.change,x]}if("account"in $){let[P,N,,R,x]=F;return[P,N,$.account,R,x]}return F}function uF([F,$,P,N,R]){let x=typeof R!=="number";if(typeof N!=="number")return`m/${F}'/${$}'/${P}'`;return`m/${F}'/${$}'/${P}'/${N}${x?"":`/${R}`}`}function D$({chain:F,index:$,addressIndex:P=0,type:N}){if(AF.EVMChains.includes(F)){if(N&&["legacy","account"].includes(N))return[44,60,0,$];if(N==="ledgerLive")return[44,60,$,0,P];return HF(b[F],{index:$})}if(F===AF.Chain.Solana){if(N==="account")return[44,501,0,$];return HF(b[F],{index:$})}let R=F===AF.Chain.Litecoin?2:0;switch(N){case"nativeSegwitMiddleAccount":return[84,R,$,0,P];case"segwit":return[49,R,0,0,$];case"legacy":return[44,R,0,0,$];default:return HF(b[F],{index:$})}}function y$(F){let[$,P,N]=F.split("/").map((R)=>Number.parseInt(R,10));switch(P){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var f$=Object.keys(b).reduce((F,$)=>{return F[$]=uF(b[$]),F},{});var o$={};j(o$,{getExplorerTxUrl:()=>E$,getExplorerAddressUrl:()=>u$});var X=require("@tcswap/types"),oF=require("ts-pattern");function E$({chain:F,txHash:$}){let{explorerUrl:P}=X.getChainConfig(F);return oF.match(F).with(...X.CosmosChains,X.Chain.Solana,()=>`${P}/tx/${$.startsWith("0x")?$.slice(2):$}`).with(...X.EVMChains,...X.SubstrateChains,()=>`${P}/tx/${$.startsWith("0x")?$:`0x${$}`}`).with(...X.UTXOChains,X.Chain.Radix,X.Chain.Tron,()=>`${P}/transaction/${$.toLowerCase()}`).with(X.Chain.Near,()=>`${P}/txns/${$}`).with(X.Chain.Ripple,()=>`${P}/transactions/${$}`).with(X.Chain.Sui,()=>`${P}/txblock/${$}`).with(X.Chain.Cardano,X.Chain.Ton,()=>`${P}/tx/${$}`).otherwise(()=>"")}function u$({chain:F,address:$}){let{explorerUrl:P}=X.getChainConfig(F);return oF.match(F).with(X.Chain.Solana,X.Chain.Sui,X.Chain.Radix,()=>`${P}/account/${$}`).otherwise(()=>`${P}/address/${$}`)}var c$={};j(c$,{getSymmetricWithdraw:()=>m$,getSymmetricPoolShare:()=>mF,getLiquiditySlippage:()=>h$,getEstimatedPoolShare:()=>t$,getAsymmetricRuneWithdrawAmount:()=>C$,getAsymmetricRuneShare:()=>CF,getAsymmetricAssetWithdrawAmount:()=>n$,getAsymmetricAssetShare:()=>nF});var jF=require("@tcswap/types");function CF({liquidityUnits:F,poolUnits:$,runeDepth:P}){let N=q(F),R=q($),x=q(P),A=N.mul(x),M=R.mul(R).mul(2),G=R.mul(N).mul(2),_=N.mul(N),Y=R.mul(R).mul(R);return A.mul(M.sub(G).add(_)).div(Y)}function nF({liquidityUnits:F,poolUnits:$,assetDepth:P}){let N=q(F),R=q($),x=q(P),A=N.mul(x),M=R.mul(R).mul(2),G=R.mul(N).mul(2),_=N.mul(N),Y=A.mul(M.sub(G).add(_)),Q=R.mul(R).mul(R);return Y.div(Q)}function C$({percent:F,runeDepth:$,liquidityUnits:P,poolUnits:N}){return CF({liquidityUnits:P,poolUnits:N,runeDepth:$}).mul(F)}function n$({percent:F,assetDepth:$,liquidityUnits:P,poolUnits:N}){return nF({assetDepth:$,liquidityUnits:P,poolUnits:N}).mul(F)}function q(F){return I.fromBigInt(BigInt(F),jF.getChainConfig(jF.Chain.THORChain).baseDecimal)}function mF({liquidityUnits:F,poolUnits:$,runeDepth:P,assetDepth:N}){return{assetAmount:q(N).mul(F).div($),runeAmount:q(P).mul(F).div($)}}function m$({liquidityUnits:F,poolUnits:$,runeDepth:P,assetDepth:N,percent:R}){return Object.fromEntries(Object.entries(mF({assetDepth:N,liquidityUnits:F,poolUnits:$,runeDepth:P})).map(([x,A])=>[x,A.mul(R)]))}function t$({runeDepth:F,poolUnits:$,assetDepth:P,liquidityUnits:N,runeAmount:R,assetAmount:x}){let A=new I({decimal:8,value:F}),M=new I({decimal:8,value:P}),G=new I({decimal:8,value:$}),_=new I({decimal:8,value:R}),Y=new I({decimal:8,value:x}),Q=_.mul(M),W=Y.mul(A),p=_.mul(Y),v=A.mul(M),C=G.mul(Q.add(W.add(p.mul(2)))),h=Q.add(W.add(v.mul(2))),y=C.div(h),k=q(N).add(y);if(y.getBaseValue("number")===0)return k.div(G).getBaseValue("number");let c=G.add(k);return k.div(c).getBaseValue("number")}function h$({runeAmount:F,assetAmount:$,runeDepth:P,assetDepth:N}){if(F==="0"||$==="0"||P==="0"||N==="0")return 0;let R=q(P),x=q(N),A=q($),M=q(F),G=A.mul(R).sub(x.mul(M)),_=x.mul(M).add(R.mul(x));return Math.abs(G.div(_).getBaseValue("number"))}var RP={};j(RP,{getMemoForWithdraw:()=>a$,getMemoForUnbond:()=>s$,getMemoForTcyStake:()=>NP,getMemoForTcyClaim:()=>PP,getMemoForRunePoolWithdraw:()=>e$,getMemoForRunePoolDeposit:()=>i$,getMemoForNameRegister:()=>FP,getMemoForNamePreferredAssetRegister:()=>$P,getMemoForLeaveAndBond:()=>l$,getMemoForDeposit:()=>r$});var xF=require("@tcswap/types"),d$=require("ts-pattern");function l$({type:F,address:$}){return`${F}:${$}`}function s$({address:F,unbondAmount:$}){return`${"UNBOND"}:${F}:${$}`}function i$(F){return SF("POOL+",F)}function r$({chain:F,symbol:$,address:P,...N}){let R=nP({chain:F,symbol:$}),x=P?`:${P}:`:":";return SF(`${"+"}:${R}${x}`,N)}function a$({chain:F,symbol:$,ticker:P,basisPoints:N,targetAsset:R}){let x=F==="ETH"&&P!=="ETH"?`${P}-${$.slice(-3)}`:$,A=R?`:${R}`:"";return`${"-"}:${F}.${x}:${N}${A}`}function e$({basisPoints:F,...$}){return SF(`${"POOL-"}:${F}`,$)}function FP({name:F,chain:$,address:P,owner:N}){let R=`${"~"}:${F}:${$}:${P}`,x=N?`:${N}`:"";return`${R}${x}`}function $P({name:F,chain:$,asset:P,payout:N,owner:R}){return`${"~"}:${F}:${$}:${N}:${R}:${P}`}function PP(F,{address:$}){return`${F}:${$}`}function NP(F,{unstakeBps:$,...P}){let N=$?`:${$}`:"",R=`${F}${N}`;return SF(`${R}`,P)}function SF(F,{affiliateAddress:$,affiliateBasisPoints:P}={}){let N=`${F}${$?`:${$}:${P||0}`:""}`;return N.endsWith(":")?N.slice(0,-1):N}function nP({chain:F,symbol:$}){return d$.match(F).with(xF.Chain.Bitcoin,xF.Chain.Dogecoin,xF.Chain.Litecoin,()=>F.slice(0,1).toLowerCase()).with(xF.Chain.BitcoinCash,()=>"c").otherwise(()=>`${F}.${$}`)}var KP={};j(KP,{wrapMethodWithNetworkSwitch:()=>dF,switchEVMWalletNetwork:()=>cF,providerRequest:()=>qF,prepareNetworkSwitch:()=>TP,okxMobileEnabled:()=>sF,listWeb3EVMWallets:()=>hF,isWeb3Detected:()=>HP,isDetected:()=>AP,getETHDefaultWallet:()=>GP,getEIP6963Wallets:()=>BP,filterSupportedChains:()=>xP,addEVMWalletNetwork:()=>lF,addAccountsChangedCallback:()=>MP});var tF=require("@tcswap/types");function HP(){return typeof window.ethereum<"u"}function AP(F){return hF().includes(F)}function hF(){let F=window?.ethereum&&!window.ethereum?.isBraveWallet,$=window?.ctrl||window?.ethereum?.__XDEFI,P=window?.vultisig,N=window?.ethereum?.isBraveWallet,R=window?.ethereum?.isTrust||window?.trustwallet,x=window?.ethereum?.overrideIsMetaMask&&window?.ethereum?.selectedProvider?.isCoinbaseWallet||window?.coinbaseWalletExtension,A=window?.bitkeep?.ethereum,M=window?.$onekey?.ethereum,G=[];if(F)G.push("METAMASK");if($)G.push("CTRL");if(P)G.push("VULTISIG");if(N)G.push("BRAVE");if(R)G.push("TRUSTWALLET_WEB");if(x)G.push("COINBASE_WEB");if(sF())G.push("OKX_MOBILE");if(A)G.push("BITGET");if(M)G.push("ONEKEY");return G}async function cF(F,$,P){let N=tF.getChainConfig($);try{await qF({method:"wallet_switchEthereumChain",params:[{chainId:N.chainIdHex}],provider:F})}catch(R){if(!P)throw new L("helpers_failed_to_switch_network",{error:R,reason:"networkParams not provided"});await lF(F,P)}}function xP({chains:F,supportedChains:$,walletType:P}){let N=F.filter((x)=>!x||$.includes(x));if(N.length===0)throw new L("wallet_chain_not_supported",{chain:F.join(", "),wallet:P});let R=F.filter((x)=>!$.includes(x));return V({condition:R.length>0,id:`wallet_chain_not_supported_${P}`,warning:`${P} wallet does not support the following chains: ${R.join(", ")}. These chains will be ignored.`}),N}function dF(F,$,P){return async(...N)=>{let{chainIdHex:R}=tF.getChainConfig(P);if((await $.getNetwork()).chainId.toString()===R)return F(...N);try{await cF($,P)}catch(x){throw new L({errorKey:"helpers_failed_to_switch_network",info:{error:x}})}return F(...N)}}function TP({toolbox:F,chain:$,provider:P=window.ethereum,methodNames:N=[]}){let x=[...N,"approve","approvedAmount","call","sendTransaction","transfer","isApproved","approvedAmount","EIP1193SendTransaction","getFeeData","broadcastTransaction","estimateCall","estimateGasLimit","estimateGasPrices","createContractTxObject"].reduce((A,M)=>{if(!F[M])return A;let G=F[M];if(typeof G!=="function")return A;let _=dF(G,P,$);return{...A,[M]:_}},{});return{...F,...x}}function lF(F,$){return qF({method:"wallet_addEthereumChain",params:[$],provider:F})}function MP(F){window.ethereum?.on("accountsChanged",()=>F()),window.ctrl?.ethereum.on("accountsChanged",()=>F())}function GP(){let{isTrust:F,isBraveWallet:$,__XDEFI:P,overrideIsMetaMask:N,selectedProvider:R}=window?.ethereum||{};if(F)return"TRUSTWALLET_WEB";if($)return"BRAVE";if(N&&R?.isCoinbaseWallet)return"COINBASE_WEB";if(P)return"CTRL";if(window?.$onekey?.ethereum)return"ONEKEY";return"METAMASK"}function BP(){let F=[];function $(N){if(F.map((R)=>R.info.uuid).includes(N.detail.info.uuid))return;F.push(N.detail)}window.addEventListener("eip6963:announceProvider",$),window.dispatchEvent(new Event("eip6963:requestProvider"));function P(){window.removeEventListener("eip6963:announceProvider",$)}return{providers:F,removeEIP6963EventListener:P}}function sF(){let F=navigator.userAgent,$=/iphone|ipad|ipod|ios/i.test(F),P=/android|XiaoMi|MiuiBrowser/i.test(F),N=$||P,R=/OKApp/i.test(F);return N&&R}function qF({provider:F,params:$,method:P}){if(!F?.send)throw new L("helpers_not_found_provider");let N=$?Array.isArray($)?$:[$]:[];return F.send(P,N)}
4
+ or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`});let{decimal:V,identifier:f,tax:WF}=h||{decimal:E||s,identifier:B},L=$?d(BigInt(R),$):d(R,V);return Q||S?bP(f,L):I?EP(f,L):yF({decimal:V,identifier:f,tax:WF,value:L})}static async loadStaticAssets(F){let{loadTokenLists:$}=await import("@tcswap/tokens"),P=await $(F);for(let{tokens:N}of Object.values(P))for(let{identifier:R,chain:T,...A}of N){let G=_.getChainConfig(T),B=m.includes(G.chain)?R:R.toUpperCase(),X={decimal:"decimals"in A?A.decimals:G.baseDecimal,identifier:R,logoURI:"logoURI"in A?A.logoURI:void 0,tax:"tax"in A?A.tax:void 0};if(FF.set(B,X),"address"in A&&A.address){let Q=m.includes(G.chain)?`${G.chain}:${A.address}`:`${G.chain}:${A.address.toUpperCase()}`;YF.set(Q,R)}}return!0}static setStaticAssets(F){FF.clear(),YF.clear();for(let[$,P]of F.entries()){let N=m.includes(P.chain)?P.identifier:P.identifier.toUpperCase(),R="decimals"in P?P.decimals:P.decimal,T={...P,decimal:R,identifier:N};if(FF.set($,T),P.address){let A=m.includes(P.chain)?`${P.chain}:${P.address}`:`${P.chain}:${P.address.toUpperCase()}`;YF.set(A,P.identifier)}}return!0}static get staticAssets(){return FF}}function g$(F){let $=n.from({chain:F});return LF.match(F).with(_.Chain.Bitcoin,_.Chain.Litecoin,_.Chain.BitcoinCash,_.Chain.Dash,()=>$.set(0.00010001)).with(_.Chain.Dogecoin,()=>$.set(1.00000001)).with(_.Chain.Avalanche,_.Chain.Ethereum,_.Chain.Arbitrum,_.Chain.BinanceSmartChain,()=>$.set(0.00000001)).with(_.Chain.THORChain,_.Chain.Maya,()=>$.set(0)).with(_.Chain.Cosmos,_.Chain.Kujira,()=>$.set(0.000001)).otherwise(()=>$.set(0.00000001))}async function k$({chain:F,address:$,ticker:P}){let R=m.includes(F)?`${F}:${$||P}`:`${F}:${$||P}`.toUpperCase(),T=DP(R);if(T)return T;if(!$){let{baseDecimal:B}=_.getChainConfig(F);return{decimals:B,identifier:`${F}.${P||"UNKNOWN"}`}}let A=await _F({address:$,chain:F}),G=`${F}.${A.ticker||P||"UNKNOWN"}-${$}`;return O({condition:!!(!A.ticker&&P),id:`async_token_lookup_failed_${F}_${$}`,warning:`Could not fetch token metadata for ${F}:${$} from chain. Using user-provided ticker (${P}) with baseDecimal (${A.decimals}).`}),A.ticker&&yP(R,{decimals:A.decimals,identifier:G}),{decimals:A.decimals,identifier:G}}function yF({identifier:F,decimal:$,value:P,tax:N}){return wF(F),new n({decimal:$,identifier:F,tax:N,value:d(P,$)})}function bP(F,$=0){let P=F.includes(".")?F.split(".")?.[0]?.toUpperCase():void 0,N=P?bF.includes(P):!1,R=F.slice(0,14).includes("~")?"~":"/",[T,A]=N?F.split(".").slice(1).join().split(R):F.split(R);if(!(T&&A))throw new Y({errorKey:"helpers_invalid_asset_identifier",info:{identifier:F}});return new n({decimal:8,identifier:`${P||_.Chain.THORChain}.${T}${R}${A}`,value:d($,8)})}function EP(F,$=0){let P=F.indexOf("-");if(P===-1)throw new Y({errorKey:"helpers_invalid_asset_identifier",info:{identifier:F}});let N=F.slice(0,P).toUpperCase(),R=F.slice(P+1).toUpperCase();if(!N||!R)throw new Y({errorKey:"helpers_invalid_asset_identifier",info:{identifier:F}});return new n({decimal:8,identifier:`${N}-${R}`,value:d($,8)})}async function fP({address:F,chain:$,fromBaseDecimal:P,parsedValue:N}){let{decimals:R,identifier:T}=await k$({address:F,chain:$}),A=P?d(BigInt(N),P):N;return yF({decimal:R,identifier:T,value:A})}function d(F,$){return typeof F==="bigint"?y({bigIntDecimal:$,decimal:$,value:F}):F}function uP(F){let $=LF.match(F).when((P)=>("chain"in P)&&P.chain!==void 0,({chain:P})=>P).otherwise((P)=>{let N=P.asset;if(D(N))return _.Chain.THORChain;if(N.includes("/")||N.includes("~"))return _.Chain.THORChain;return a(N).chain});if(!_.AllChains.includes($.toUpperCase()))throw new Y({errorKey:"helpers_invalid_asset_identifier",info:{message:"Please use the AssetValue constructor for unsupported chains"}})}function oP(F){if(uP(F),"chain"in F){let{chain:R,address:T}=F;if(T){let A=m.includes(R)?`${R}:${T}`:`${R}:${T.toUpperCase()}`,G=YF.get(A);if(G)return G;return A}return R}if(D(F.asset))return F.asset.toUpperCase();let{chain:$,symbol:P}=a(F.asset);return NF({chain:$,symbol:P})==="Native"?$:F.asset}function CP(F,$,P){let N=F.split("."),R=N[0]?.toUpperCase(),T=bF.includes(R),A=P?"~":"/",[G,B=""]=T?N.slice(1).join(".").split(A):F.split(A);if(!(G&&B))throw new Y({errorKey:"helpers_invalid_asset_identifier",info:{identifier:F}});let{ticker:z,address:X}=I$({chain:G,symbol:B}),Q=`${G}${A}${B}`;return{address:X,chain:R,isGasAsset:!1,isSecuredAsset:!1,isSynthetic:$,isTradeAsset:P,symbol:Q,ticker:z}}function mP(F){let $=F.indexOf("-"),P=F.slice(0,$).toUpperCase(),N=F.slice($+1);if(!P||!N)throw new Y({errorKey:"helpers_invalid_asset_identifier",info:{identifier:F}});let R=N.lastIndexOf("-"),T=R!==-1&&/^0[xX]/.test(N.slice(R+1)),A=(T?N.slice(0,R):N).toUpperCase(),G=T?N.slice(R+1):void 0,B=`${P}-${N.toUpperCase()}`;return{address:G,chain:_.Chain.THORChain,isGasAsset:!1,isSecuredAsset:!0,isSynthetic:!1,isTradeAsset:!1,symbol:B,ticker:A}}function nP(F){let $=F.indexOf("."),P=($===-1?F:F.slice(0,$)).toUpperCase(),N=$===-1?F:F.slice($+1),{address:R,ticker:T}=I$({chain:P,symbol:N}),A;try{A=R&&_.EVMChains.includes(P)&&DF.getAddress(R)?DF.getAddress(R):R}catch{A=R}let G=A?`${T}-${A}`:N;return{address:A,chain:P,isGasAsset:zF({chain:P,symbol:N}),isSecuredAsset:!1,isSynthetic:!1,isTradeAsset:!1,symbol:G,ticker:T}}function S$(F){let $=F.slice(0,14),P=$.includes("/"),N=$.includes("~");if(P||N)return CP(F,P,N);if(D(F))return mP(F);return nP(F)}function hP(F,$=!1){let P=$?F.indexOf("-"):F.lastIndexOf("-");if(P===-1)return{address:void 0,ticker:F};let N=F.slice(0,P);return{address:F.slice(P+1),ticker:N}}function I$({symbol:F,chain:$}){let{ticker:P,address:N}=hP(F,$===_.Chain.Near);return{address:N&&!m.includes($)?N.toLowerCase():N,ticker:P}}var v$={};j(v$,{getFeeMultiplierAsBigInt:()=>fF,getFeeMultiplier:()=>JF,applyFeeMultiplierToBigInt:()=>O$,applyFeeMultiplier:()=>p$,DEFAULT_FEE_MULTIPLIERS:()=>EF});var EF={average:1,fast:1.5,fastest:2};function JF(F="average"){let $=g.get("feeMultipliers");if($&&$[F]!==void 0)return $[F];return EF[F]}function fF(F="average"){let $=JF(F),P=10n,N=BigInt(Math.round($*10));return{denominator:P,numerator:N}}function O$(F,$="average"){let{numerator:P,denominator:N}=fF($);return F*P/N}function p$(F,$="average",P=!1){let N=JF($),R=F*N;return P?Math.floor(R):R}var D$={};j(D$,{USwapNumber:()=>k});class k extends p{eq(F){return this.eqValue(F)}static fromBigInt(F,$){return new k({decimal:$,value:y({bigIntDecimal:$,decimal:$,value:F})})}}var f$={};j(f$,{updateDerivationPath:()=>AF,getWalletFormatFor:()=>b$,getDerivationPathFor:()=>y$,derivationPathToString:()=>uF,DerivationPath:()=>E$});var TF=require("@tcswap/types");function AF(F,$){if("index"in $)return[...F.slice(0,F.length-1),$.index];if("change"in $){let[P,N,R,,T]=F;return[P,N,R,$.change,T]}if("account"in $){let[P,N,,R,T]=F;return[P,N,$.account,R,T]}return F}function uF([F,$,P,N,R]){let T=typeof R!=="number";if(typeof N!=="number")return`m/${F}'/${$}'/${P}'`;return`m/${F}'/${$}'/${P}'/${N}${T?"":`/${R}`}`}function y$({chain:F,index:$,addressIndex:P=0,type:N}){if(TF.EVMChains.includes(F)){if(N&&["legacy","account"].includes(N))return[44,60,0,$];if(N==="ledgerLive")return[44,60,$,0,P];return AF(u[F],{index:$})}if(F===TF.Chain.Solana){if(N==="account")return[44,501,0,$];return AF(u[F],{index:$})}let R=F===TF.Chain.Litecoin?2:0;switch(N){case"nativeSegwitMiddleAccount":return[84,R,$,0,P];case"segwit":return[49,R,0,0,$];case"legacy":return[44,R,0,0,$];default:return AF(u[F],{index:$})}}function b$(F){let[$,P,N]=F.split("/").map((R)=>Number.parseInt(R,10));switch(P){case 44:return"legacy";case 49:return"p2sh";default:return"bech32"}}var E$=Object.keys(u).reduce((F,$)=>{return F[$]=uF(u[$]),F},{});var C$={};j(C$,{getExplorerTxUrl:()=>u$,getExplorerAddressUrl:()=>o$});var J=require("@tcswap/types"),oF=require("ts-pattern");function u$({chain:F,txHash:$}){let{explorerUrl:P}=J.getChainConfig(F);return oF.match(F).with(...J.CosmosChains,J.Chain.Solana,()=>`${P}/tx/${$.startsWith("0x")?$.slice(2):$}`).with(...J.EVMChains,...J.SubstrateChains,()=>`${P}/tx/${$.startsWith("0x")?$:`0x${$}`}`).with(...J.UTXOChains,J.Chain.Radix,J.Chain.Tron,()=>`${P}/transaction/${$.toLowerCase()}`).with(J.Chain.Near,()=>`${P}/txns/${$}`).with(J.Chain.Ripple,()=>`${P}/transactions/${$}`).with(J.Chain.Sui,()=>`${P}/txblock/${$}`).with(J.Chain.Cardano,J.Chain.Ton,()=>`${P}/tx/${$}`).otherwise(()=>"")}function o$({chain:F,address:$}){let{explorerUrl:P}=J.getChainConfig(F);return oF.match(F).with(J.Chain.Solana,J.Chain.Sui,J.Chain.Radix,()=>`${P}/account/${$}`).otherwise(()=>`${P}/address/${$}`)}var l$={};j(l$,{getSymmetricWithdraw:()=>h$,getSymmetricPoolShare:()=>nF,getLiquiditySlippage:()=>c$,getEstimatedPoolShare:()=>t$,getAsymmetricRuneWithdrawAmount:()=>m$,getAsymmetricRuneShare:()=>CF,getAsymmetricAssetWithdrawAmount:()=>n$,getAsymmetricAssetShare:()=>mF});var ZF=require("@tcswap/types");function CF({liquidityUnits:F,poolUnits:$,runeDepth:P}){let N=W(F),R=W($),T=W(P),A=N.mul(T),G=R.mul(R).mul(2),B=R.mul(N).mul(2),z=N.mul(N),X=R.mul(R).mul(R);return A.mul(G.sub(B).add(z)).div(X)}function mF({liquidityUnits:F,poolUnits:$,assetDepth:P}){let N=W(F),R=W($),T=W(P),A=N.mul(T),G=R.mul(R).mul(2),B=R.mul(N).mul(2),z=N.mul(N),X=A.mul(G.sub(B).add(z)),Q=R.mul(R).mul(R);return X.div(Q)}function m$({percent:F,runeDepth:$,liquidityUnits:P,poolUnits:N}){return CF({liquidityUnits:P,poolUnits:N,runeDepth:$}).mul(F)}function n$({percent:F,assetDepth:$,liquidityUnits:P,poolUnits:N}){return mF({assetDepth:$,liquidityUnits:P,poolUnits:N}).mul(F)}function W(F){return k.fromBigInt(BigInt(F),ZF.getChainConfig(ZF.Chain.THORChain).baseDecimal)}function nF({liquidityUnits:F,poolUnits:$,runeDepth:P,assetDepth:N}){return{assetAmount:W(N).mul(F).div($),runeAmount:W(P).mul(F).div($)}}function h$({liquidityUnits:F,poolUnits:$,runeDepth:P,assetDepth:N,percent:R}){return Object.fromEntries(Object.entries(nF({assetDepth:N,liquidityUnits:F,poolUnits:$,runeDepth:P})).map(([T,A])=>[T,A.mul(R)]))}function t$({runeDepth:F,poolUnits:$,assetDepth:P,liquidityUnits:N,runeAmount:R,assetAmount:T}){let A=new k({decimal:8,value:F}),G=new k({decimal:8,value:P}),B=new k({decimal:8,value:$}),z=new k({decimal:8,value:R}),X=new k({decimal:8,value:T}),Q=z.mul(G),S=X.mul(A),I=z.mul(X),b=A.mul(G),s=B.mul(Q.add(S.add(I.mul(2)))),h=Q.add(S.add(b.mul(2))),E=s.div(h),V=W(N).add(E);if(E.getBaseValue("number")===0)return V.div(B).getBaseValue("number");let f=B.add(V);return V.div(f).getBaseValue("number")}function c$({runeAmount:F,assetAmount:$,runeDepth:P,assetDepth:N}){if(F==="0"||$==="0"||P==="0"||N==="0")return 0;let R=W(P),T=W(N),A=W($),G=W(F),B=A.mul(R).sub(T.mul(G)),z=T.mul(G).add(R.mul(T));return Math.abs(B.div(z).getBaseValue("number"))}var HP={};j(HP,{getMemoForWithdraw:()=>e$,getMemoForUnbond:()=>i$,getMemoForTcyStake:()=>RP,getMemoForTcyClaim:()=>NP,getMemoForRunePoolWithdraw:()=>FP,getMemoForRunePoolDeposit:()=>r$,getMemoForNameRegister:()=>$P,getMemoForNamePreferredAssetRegister:()=>PP,getMemoForLeaveAndBond:()=>s$,getMemoForDeposit:()=>a$});var MF=require("@tcswap/types"),d$=require("ts-pattern");function s$({type:F,address:$}){return`${F}:${$}`}function i$({address:F,unbondAmount:$}){return`${"UNBOND"}:${F}:${$}`}function r$(F){return jF("POOL+",F)}function a$({chain:F,symbol:$,address:P,...N}){let R=tP({chain:F,symbol:$}),T=P?`:${P}:`:":";return jF(`${"+"}:${R}${T}`,N)}function e$({chain:F,symbol:$,ticker:P,basisPoints:N,targetAsset:R}){let T=F==="ETH"&&P!=="ETH"?`${P}-${$.slice(-3)}`:$,A=R?`:${R}`:"";return`${"-"}:${F}.${T}:${N}${A}`}function FP({basisPoints:F,...$}){return jF(`${"POOL-"}:${F}`,$)}function $P({name:F,chain:$,address:P,owner:N}){let R=`${"~"}:${F}:${$}:${P}`,T=N?`:${N}`:"";return`${R}${T}`}function PP({name:F,chain:$,asset:P,payout:N,owner:R}){return`${"~"}:${F}:${$}:${N}:${R}:${P}`}function NP(F,{address:$}){return`${F}:${$}`}function RP(F,{unstakeBps:$,...P}){let N=$?`:${$}`:"",R=`${F}${N}`;return jF(`${R}`,P)}function jF(F,{affiliateAddress:$,affiliateBasisPoints:P}={}){let N=`${F}${$?`:${$}:${P||0}`:""}`;return N.endsWith(":")?N.slice(0,-1):N}function tP({chain:F,symbol:$}){return d$.match(F).with(MF.Chain.Bitcoin,MF.Chain.Dogecoin,MF.Chain.Litecoin,()=>F.slice(0,1).toLowerCase()).with(MF.Chain.BitcoinCash,()=>"c").otherwise(()=>`${F}.${$}`)}var QP={};j(QP,{wrapMethodWithNetworkSwitch:()=>lF,switchEVMWalletNetwork:()=>cF,providerRequest:()=>qF,prepareNetworkSwitch:()=>GP,okxMobileEnabled:()=>sF,listWeb3EVMWallets:()=>tF,isWeb3Detected:()=>AP,isDetected:()=>TP,getETHDefaultWallet:()=>xP,getEIP6963Wallets:()=>KP,filterSupportedChains:()=>MP,addEVMWalletNetwork:()=>dF,addAccountsChangedCallback:()=>BP});var hF=require("@tcswap/types");function AP(){return typeof window.ethereum<"u"}function TP(F){return tF().includes(F)}function tF(){let F=window?.ethereum&&!window.ethereum?.isBraveWallet,$=window?.ctrl||window?.ethereum?.__XDEFI,P=window?.vultisig,N=window?.ethereum?.isBraveWallet,R=window?.ethereum?.isTrust||window?.trustwallet,T=window?.ethereum?.overrideIsMetaMask&&window?.ethereum?.selectedProvider?.isCoinbaseWallet||window?.coinbaseWalletExtension,A=window?.bitkeep?.ethereum,G=window?.$onekey?.ethereum,B=[];if(F)B.push("METAMASK");if($)B.push("CTRL");if(P)B.push("VULTISIG");if(N)B.push("BRAVE");if(R)B.push("TRUSTWALLET_WEB");if(T)B.push("COINBASE_WEB");if(sF())B.push("OKX_MOBILE");if(A)B.push("BITGET");if(G)B.push("ONEKEY");return B}async function cF(F,$,P){let N=hF.getChainConfig($);try{await qF({method:"wallet_switchEthereumChain",params:[{chainId:N.chainIdHex}],provider:F})}catch(R){if(!P)throw new Y("helpers_failed_to_switch_network",{error:R,reason:"networkParams not provided"});await dF(F,P)}}function MP({chains:F,supportedChains:$,walletType:P}){let N=F.filter((T)=>!T||$.includes(T));if(N.length===0)throw new Y("wallet_chain_not_supported",{chain:F.join(", "),wallet:P});let R=F.filter((T)=>!$.includes(T));return O({condition:R.length>0,id:`wallet_chain_not_supported_${P}`,warning:`${P} wallet does not support the following chains: ${R.join(", ")}. These chains will be ignored.`}),N}function lF(F,$,P){return async(...N)=>{let{chainIdHex:R}=hF.getChainConfig(P);if((await $.getNetwork()).chainId.toString()===R)return F(...N);try{await cF($,P)}catch(T){throw new Y({errorKey:"helpers_failed_to_switch_network",info:{error:T}})}return F(...N)}}function GP({toolbox:F,chain:$,provider:P=window.ethereum,methodNames:N=[]}){let T=[...N,"approve","approvedAmount","call","sendTransaction","transfer","isApproved","approvedAmount","EIP1193SendTransaction","getFeeData","broadcastTransaction","estimateCall","estimateGasLimit","estimateGasPrices","createContractTxObject"].reduce((A,G)=>{if(!F[G])return A;let B=F[G];if(typeof B!=="function")return A;let z=lF(B,P,$);return{...A,[G]:z}},{});return{...F,...T}}function dF(F,$){return qF({method:"wallet_addEthereumChain",params:[$],provider:F})}function BP(F){window.ethereum?.on("accountsChanged",()=>F()),window.ctrl?.ethereum.on("accountsChanged",()=>F())}function xP(){let{isTrust:F,isBraveWallet:$,__XDEFI:P,overrideIsMetaMask:N,selectedProvider:R}=window?.ethereum||{};if(F)return"TRUSTWALLET_WEB";if($)return"BRAVE";if(N&&R?.isCoinbaseWallet)return"COINBASE_WEB";if(P)return"CTRL";if(window?.$onekey?.ethereum)return"ONEKEY";return"METAMASK"}function KP(){let F=[];function $(N){if(F.map((R)=>R.info.uuid).includes(N.detail.info.uuid))return;F.push(N.detail)}window.addEventListener("eip6963:announceProvider",$),window.dispatchEvent(new Event("eip6963:requestProvider"));function P(){window.removeEventListener("eip6963:announceProvider",$)}return{providers:F,removeEIP6963EventListener:P}}function sF(){let F=navigator.userAgent,$=/iphone|ipad|ipod|ios/i.test(F),P=/android|XiaoMi|MiuiBrowser/i.test(F),N=$||P,R=/OKApp/i.test(F);return N&&R}function qF({provider:F,params:$,method:P}){if(!F?.send)throw new Y("helpers_not_found_provider");let N=$?Array.isArray($)?$:[$]:[];return F.send(P,N)}
5
5
 
6
- //# debugId=8BBB849362867AD064756E2164756E21
6
+ //# debugId=637A354B0CED521C64756E2164756E21
7
7
  //# sourceMappingURL=index.cjs.map