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