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