@swapkit/helpers 4.20.5 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -18
- package/dist/api/index.js +1 -1
- package/dist/chunk-g60m4sgr.js +5 -0
- package/dist/index.js +1 -1
- package/dist/types/api/index.d.ts +24 -0
- package/dist/types/api/swapkitApi/endpoints.d.ts +24 -0
- package/dist/types/api/swapkitApi/types.d.ts +194 -18
- package/dist/types/index.d.ts +0 -3
- package/dist/types/modules/assetValue.d.ts +2 -1
- package/dist/types/modules/requestClient.d.ts +5 -0
- package/dist/types/modules/swapKitError.d.ts +12 -0
- package/dist/types/types/quotes.d.ts +2 -1
- package/dist/types/utils/asset.d.ts +3 -1
- package/dist/types/utils/chains.d.ts +9 -0
- package/dist/types/utils/evmAddress.d.ts +14 -0
- package/dist/types/utils/memo.d.ts +3 -0
- package/dist/types/utils/others.d.ts +0 -4
- package/package.json +13 -22
- package/dist/api/index.cjs +0 -4
- package/dist/chunk-8pyeeg27.js +0 -5
- package/dist/contracts.cjs +0 -1
- package/dist/index.cjs +0 -4
- package/dist/tokens.cjs +0 -1
- package/dist/types/modules/widgetAuth.d.ts +0 -5
- package/dist/types/utils/explorerUrls.d.ts +0 -9
- package/dist/types/utils/validators.d.ts +0 -2
|
@@ -27,4 +27,9 @@ export declare const RequestClient: {
|
|
|
27
27
|
get: <T>(url: string, options?: Options) => Promise<T>;
|
|
28
28
|
post: <T>(url: string, options?: Options) => Promise<T>;
|
|
29
29
|
};
|
|
30
|
+
/**
|
|
31
|
+
* Widget authentication: HMAC signature so the widget can authenticate requests without
|
|
32
|
+
* exposing API keys. Used by the SwapKit API endpoints.
|
|
33
|
+
*/
|
|
34
|
+
export declare function signWidgetRequest(signingSecret: string, widgetId: string, origin: string, timestamp: number): Promise<string>;
|
|
30
35
|
export {};
|
|
@@ -385,6 +385,11 @@ declare const errorCodes: {
|
|
|
385
385
|
* Toolboxes - HyperCore
|
|
386
386
|
*/
|
|
387
387
|
readonly toolbox_hypercore_no_signer: 51001;
|
|
388
|
+
readonly toolbox_hypercore_payload_mismatch: 51002;
|
|
389
|
+
readonly toolbox_hypercore_insufficient_balance: 51003;
|
|
390
|
+
readonly toolbox_hypercore_destination_sanctioned: 51004;
|
|
391
|
+
readonly toolbox_hypercore_transfer_hash_not_found: 51005;
|
|
392
|
+
readonly toolbox_hypercore_pre_transfer_check_failed: 51006;
|
|
388
393
|
/**
|
|
389
394
|
* Toolboxes - Cardano
|
|
390
395
|
*/
|
|
@@ -499,6 +504,7 @@ declare const errorCodes: {
|
|
|
499
504
|
readonly plugin_swapkit_swap_invalid_data: 43001;
|
|
500
505
|
readonly plugin_swapkit_invalid_transaction: 43002;
|
|
501
506
|
readonly plugin_swapkit_stellar_destination_wallet_not_found: 43003;
|
|
507
|
+
readonly plugin_swapkit_unsupported_tx_type: 43004;
|
|
502
508
|
/**
|
|
503
509
|
* SwapKit API
|
|
504
510
|
*/
|
|
@@ -918,6 +924,11 @@ export declare class SwapKitError extends Error {
|
|
|
918
924
|
* Toolboxes - HyperCore
|
|
919
925
|
*/
|
|
920
926
|
readonly toolbox_hypercore_no_signer: 51001;
|
|
927
|
+
readonly toolbox_hypercore_payload_mismatch: 51002;
|
|
928
|
+
readonly toolbox_hypercore_insufficient_balance: 51003;
|
|
929
|
+
readonly toolbox_hypercore_destination_sanctioned: 51004;
|
|
930
|
+
readonly toolbox_hypercore_transfer_hash_not_found: 51005;
|
|
931
|
+
readonly toolbox_hypercore_pre_transfer_check_failed: 51006;
|
|
921
932
|
/**
|
|
922
933
|
* Toolboxes - Cardano
|
|
923
934
|
*/
|
|
@@ -1032,6 +1043,7 @@ export declare class SwapKitError extends Error {
|
|
|
1032
1043
|
readonly plugin_swapkit_swap_invalid_data: 43001;
|
|
1033
1044
|
readonly plugin_swapkit_invalid_transaction: 43002;
|
|
1034
1045
|
readonly plugin_swapkit_stellar_destination_wallet_not_found: 43003;
|
|
1046
|
+
readonly plugin_swapkit_unsupported_tx_type: 43004;
|
|
1035
1047
|
/**
|
|
1036
1048
|
* SwapKit API
|
|
1037
1049
|
*/
|
|
@@ -134,7 +134,8 @@ export declare enum ErrorCode {
|
|
|
134
134
|
}
|
|
135
135
|
export declare enum WarningCodeEnum {
|
|
136
136
|
highSlippage = "highSlippage",
|
|
137
|
-
highPriceImpact = "highPriceImpact"
|
|
137
|
+
highPriceImpact = "highPriceImpact",
|
|
138
|
+
insufficientBalance = "insufficientBalance"
|
|
138
139
|
}
|
|
139
140
|
export declare enum ProviderName {
|
|
140
141
|
CHAINFLIP = "CHAINFLIP",
|
|
@@ -3,12 +3,14 @@ import type { AssetValue } from "../modules/assetValue";
|
|
|
3
3
|
export type CommonAssetString = (typeof CommonAssetStrings)[number] | Chain;
|
|
4
4
|
export type ConditionalAssetValueReturn<T extends boolean> = T extends true ? Promise<AssetValue[]> : AssetValue[];
|
|
5
5
|
export declare const CommonAssetStrings: readonly ["MAYA.MAYA", "MAYA.CACAO", "ETH.THOR", "ETH.vTHOR", "KUJI.USK", "ETH.FLIP", "XRD.XRD"];
|
|
6
|
+
export declare function decodeABIString(hexResult: string): string;
|
|
7
|
+
export declare function decodeABIDynamicString(hex: string | undefined): string | undefined;
|
|
6
8
|
export declare function fetchTokenInfo({ chain, address }: {
|
|
7
9
|
chain: Chain;
|
|
8
10
|
address: string;
|
|
9
11
|
}): Promise<{
|
|
10
12
|
decimals: number;
|
|
11
|
-
ticker:
|
|
13
|
+
ticker: string | undefined;
|
|
12
14
|
}>;
|
|
13
15
|
export declare function isGasAsset({ chain, symbol }: {
|
|
14
16
|
chain: Chain;
|
|
@@ -12,3 +12,12 @@ export declare function getRPCUrl(chain: Chain | StagenetChain): Promise<string>
|
|
|
12
12
|
* This function is obsolete and will be removed in a future release.
|
|
13
13
|
*/
|
|
14
14
|
export declare function initializeRPCUrlsWithFallback(_chains: never): void;
|
|
15
|
+
export declare function getExplorerTxUrl({ chain, txHash }: {
|
|
16
|
+
txHash: string;
|
|
17
|
+
chain: Chain;
|
|
18
|
+
}): string;
|
|
19
|
+
export declare function getExplorerAddressUrl({ chain, address }: {
|
|
20
|
+
address: string;
|
|
21
|
+
chain: Chain;
|
|
22
|
+
}): string;
|
|
23
|
+
export declare function getChainIdentifier<T extends Chain>(chain: T): string;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* EIP-55 checksum + validation for EVM addresses, replacing ethers' `getAddress`.
|
|
3
|
+
*
|
|
4
|
+
* Kept in helpers (not the EVM toolbox) because `AssetValue` checksums contract
|
|
5
|
+
* addresses synchronously while building identifiers, and toolboxes depend on
|
|
6
|
+
* helpers — not the other way around. Backed by `@noble/hashes` keccak256 so the
|
|
7
|
+
* core asset path no longer pulls in the whole of `ethers`.
|
|
8
|
+
*
|
|
9
|
+
* Throws on malformed input or a bad mixed-case checksum, mirroring ethers
|
|
10
|
+
* semantics so existing `try/catch` fallbacks keep behaving identically.
|
|
11
|
+
*/
|
|
12
|
+
export declare function getAddress(address: string): string;
|
|
13
|
+
/** Returns true for a valid EVM address (incl. a correct EIP-55 checksum), false otherwise. */
|
|
14
|
+
export declare function isAddress(value: string): boolean;
|
|
@@ -61,4 +61,7 @@ type WithdrawParams = {
|
|
|
61
61
|
basisPoints: number;
|
|
62
62
|
targetAsset?: string;
|
|
63
63
|
};
|
|
64
|
+
export declare function getTHORNameCost(numberOfYears: number): number;
|
|
65
|
+
export declare function getMAYANameCost(numberOfYears: number): number;
|
|
66
|
+
export declare function validateTNS(name: string): boolean;
|
|
64
67
|
export {};
|
|
@@ -1,9 +1,5 @@
|
|
|
1
|
-
import { Chain } from "@swapkit/types";
|
|
2
1
|
import { type ErrorKeys } from "../modules/swapKitError";
|
|
3
|
-
export declare function getTHORNameCost(numberOfYears: number): number;
|
|
4
|
-
export declare function getMAYANameCost(numberOfYears: number): number;
|
|
5
2
|
export declare function wrapWithThrow<T>(fn: () => T, errorKey?: ErrorKeys): T | undefined;
|
|
6
|
-
export declare function getChainIdentifier<T extends Chain>(chain: T): string;
|
|
7
3
|
export declare function warnOnce({ condition, id, warning }: {
|
|
8
4
|
condition: boolean;
|
|
9
5
|
id: string;
|
package/package.json
CHANGED
|
@@ -1,33 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"author": "swapkit-dev",
|
|
3
|
-
"dependencies": {
|
|
3
|
+
"dependencies": {
|
|
4
|
+
"@noble/hashes": "2.2.0",
|
|
5
|
+
"@swapkit/contracts": "5.0.0",
|
|
6
|
+
"@swapkit/tokens": "5.0.1",
|
|
7
|
+
"@swapkit/types": "1.0.1"
|
|
8
|
+
},
|
|
4
9
|
"description": "SwapKit - Helpers",
|
|
5
|
-
"devDependencies": { "@
|
|
10
|
+
"devDependencies": { "@swapkit/toolboxes": "5.1.0" },
|
|
6
11
|
"exports": {
|
|
7
|
-
".": { "default": "./dist/index.js", "
|
|
8
|
-
"./api": {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
"types": "./dist/types/api/index.d.ts"
|
|
12
|
-
},
|
|
13
|
-
"./contracts": {
|
|
14
|
-
"default": "./dist/contracts.js",
|
|
15
|
-
"require": "./dist/contracts.cjs",
|
|
16
|
-
"types": "./dist/types/contracts.d.ts"
|
|
17
|
-
},
|
|
18
|
-
"./tokens": { "default": "./dist/tokens.js", "require": "./dist/tokens.cjs", "types": "./dist/types/tokens.d.ts" }
|
|
12
|
+
".": { "default": "./dist/index.js", "types": "./dist/types/index.d.ts" },
|
|
13
|
+
"./api": { "default": "./dist/api/index.js", "types": "./dist/types/api/index.d.ts" },
|
|
14
|
+
"./contracts": { "default": "./dist/contracts.js", "types": "./dist/types/contracts.d.ts" },
|
|
15
|
+
"./tokens": { "default": "./dist/tokens.js", "types": "./dist/types/tokens.d.ts" }
|
|
19
16
|
},
|
|
20
17
|
"files": ["dist/", "CHANGELOG.md"],
|
|
21
18
|
"homepage": "https://github.com/swapkit/SwapKit",
|
|
22
19
|
"license": "SEE LICENSE IN LICENSE",
|
|
23
20
|
"name": "@swapkit/helpers",
|
|
24
|
-
"peerDependencies": {
|
|
25
|
-
"@near-js/providers": "2.5.1",
|
|
26
|
-
"ethers": "6.16.0",
|
|
27
|
-
"ts-pattern": "5.9.0",
|
|
28
|
-
"zod": "4.4.3",
|
|
29
|
-
"zustand": "5.0.13"
|
|
30
|
-
},
|
|
21
|
+
"peerDependencies": { "ts-pattern": "5.9.0", "zod": "4.4.3", "zustand": "5.0.13" },
|
|
31
22
|
"publishConfig": { "access": "public" },
|
|
32
23
|
"repository": { "directory": "packages/helpers", "type": "git", "url": "git+https://github.com/swapkit/SwapKit.git" },
|
|
33
24
|
"scripts": {
|
|
@@ -39,5 +30,5 @@
|
|
|
39
30
|
"type-check:go": "tsgo"
|
|
40
31
|
},
|
|
41
32
|
"type": "module",
|
|
42
|
-
"version": "
|
|
33
|
+
"version": "5.0.1"
|
|
43
34
|
}
|
package/dist/api/index.cjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var{defineProperty:IN,getOwnPropertyNames:XA,getOwnPropertyDescriptor:uH}=Object,WN=Object.prototype.hasOwnProperty;function jN(A){return this[A]}var YN=(A,H,T)=>{var P=XA(H);for(let L of P)if(!WN.call(A,L)&&L!=="default")IN(A,L,{get:jN.bind(H,L),enumerable:!0});if(T){for(let L of P)if(!WN.call(T,L)&&L!=="default")IN(T,L,{get:jN.bind(H,L),enumerable:!0});return T}};var SA=(A)=>{var H=(UA??=new WeakMap).get(A),T;if(H)return H;if(H=IN({},"__esModule",{value:!0}),A&&typeof A==="object"||typeof A==="function"){for(var P of XA(A))if(!WN.call(H,P))IN(H,P,{get:jN.bind(A,P),enumerable:!(T=uH(A,P))||T.enumerable})}return UA.set(A,H),H},UA;var MH=(A)=>A;function _H(A,H){this[A]=MH.bind(null,H)}var Q=(A,H)=>{for(var T in H)IN(A,T,{get:H[T],enumerable:!0,configurable:!0,set:_H.bind(H,T)})};var YH=(A,H)=>()=>(A&&(H=A(A=0)),H);var r={};module.exports=SA(r);var nA=YH(()=>{YN(r,require("@swapkit/tokens"),module.exports)});var HL={};Q(HL,{toHexTransactionValue:()=>BP,parseTransactionValue:()=>RP,isTransactionValue:()=>rA,TxnType:()=>hN,TxnStatus:()=>lN,TronTransactionSchema:()=>TA,TransactionSchema:()=>LP,TransactionDTOSchema:()=>FP,TrackingStatus:()=>rN,TrackingRequestSchema:()=>dT,TrackingRequestQuerySchema:()=>hT,TrackerResponseSchema:()=>AA,TokenSchema:()=>CT,TokenDetailsMetadataSchema:()=>lT,TONTransactionSchema:()=>LA,TONTransactionMessageSchema:()=>eA,SwapToResponseSchema:()=>EP,SwapToRequestSchema:()=>nP,SwapToAssetSchema:()=>RH,SwapRouteV2ResponseSchema:()=>uA,SwapKitApi:()=>AL,SwapApprovalTransactionSchema:()=>LH,StellarApprovalTransactionSchema:()=>PH,StarknetTransactionSchema:()=>sA,RouteQuoteWarningSchema:()=>RA,RouteQuoteTxType:()=>GN,RouteQuoteProviderErrorSchema:()=>BH,RouteQuoteMetadataV2Schema:()=>IA,RouteQuoteMetadataSchema:()=>FA,RouteQuoteMetadataAssetSchema:()=>NH,RouteLegWithoutAddressesSchema:()=>_P,RouteLegSchema:()=>aA,QuoteV3ResponseSchema:()=>SP,QuoteV2ResponseSchema:()=>bP,QuoteRouteV2Response:()=>GA,QuoteResponseSchema:()=>BA,QuoteResponseRouteItem:()=>HH,QuoteRequestSchema:()=>rT,ProviderAction:()=>cN,PriorityLabel:()=>dN,PriceResponseSchema:()=>sN,PriceRequestSchema:()=>iT,NearSwapResponseSchema:()=>NA,NearDepositChannelResultSchema:()=>sT,NearDepositChannelParamsSchema:()=>CN,GasSchema:()=>$A,GasResponseSchema:()=>OA,FeesSchema:()=>wN,EstimatedTimeSchema:()=>JN,EVMTransactionSchema:()=>HA,EVMTransactionDetailsSchema:()=>$P,EVMTransactionDetailsParamsSchema:()=>iA,DepositChannelResponseSchema:()=>aN,DepositChannelParamsSchema:()=>eN,CosmosTransactionSchema:()=>PA,CoinGeckoMetadataSchema:()=>iN,ChainflipMetadataSchema:()=>AH,BrokerDepositChannelParamsSchema:()=>lA,AssetValueSchema:()=>h,ApproveResponseSchema:()=>UP,ApproveRequestParams:()=>gP,ApprovalTransactionSchema:()=>TH,ApiV2ErrorSchema:()=>cT});module.exports=SA(HL);var d=require("@swapkit/types");var uT={};Q(uT,{getMinAmountByChain:()=>FT,AssetValue:()=>J});var M=require("@swapkit/types"),yN=require("ethers"),QN=require("ts-pattern");var iH={};Q(iH,{parseSymbolForAddress:()=>e,isGasAsset:()=>kN,getTokenLogoURI:()=>lH,getCommonAssetInfo:()=>RN,getAssetType:()=>bN,findAssetBy:()=>rH,fetchTokenInfo:()=>qN,assetFromString:()=>K,CommonAssetStrings:()=>yH});var B=require("@swapkit/types"),s=require("ts-pattern");var ZH={};Q(ZH,{RequestClient:()=>G});var SH={};Q(SH,{swapKitConfigStore:()=>w,SKConfig:()=>g});var n=require("@swapkit/types"),QA=require("zustand/vanilla");var gH={};Q(gH,{WarningCodeEnum:()=>gN,WalletOption:()=>XN,ProviderName:()=>z,NetworkDerivationPath:()=>DH,MemoType:()=>xA,LedgerErrorCode:()=>zA,FeeTypeEnum:()=>UN,FeeOption:()=>EA,ErrorCode:()=>i,ApproveMode:()=>bA});var DN=require("@swapkit/types"),DH=DN.AllChains.reduce((A,H)=>{return A[H]=DN.getChainConfig(H).networkDerivationPath,A},{});var i;((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"})(i||={});var gN;((T)=>{T.highSlippage="highSlippage";T.highPriceImpact="highPriceImpact"})(gN||={});var z;((S)=>{S.CHAINFLIP="CHAINFLIP";S.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";S.JUPITER="JUPITER";S.MAYACHAIN="MAYACHAIN";S.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";S.ONEINCH="ONEINCH";S.PANCAKESWAP="PANCAKESWAP";S.SUSHISWAP_V2="SUSHISWAP_V2";S.THORCHAIN="THORCHAIN";S.THORCHAIN_STREAMING="THORCHAIN_STREAMING";S.TRADERJOE_V2="TRADERJOE_V2";S.UNISWAP_V2="UNISWAP_V2";S.UNISWAP_V3="UNISWAP_V3";S.NEAR="NEAR";S.GARDEN="GARDEN";S.OKX="OKX";S.HARBOR="HARBOR";S.FLASHNET="FLASHNET";S.MAYAN="MAYAN"})(z||={});var UN;((O)=>{O.LIQUIDITY="liquidity";O.NETWORK="network";O.INBOUND="inbound";O.OUTBOUND="outbound";O.AFFILIATE="affiliate";O.TAX="tax";O.PRIORITY="priority";O.SERVICE="service"})(UN||={});var EA;((P)=>{P.Average="average";P.Fast="fast";P.Fastest="fastest"})(EA||={});var bA;((T)=>{T.Approve="approve";T.CheckOnly="checkOnly"})(bA||={});var xA;((_)=>{_.NAME_REGISTER="~";_.BOND="BOND";_.DEPOSIT="+";_.LEAVE="LEAVE";_.UNBOND="UNBOND";_.WITHDRAW="-";_.RUNEPOOL_DEPOSIT="POOL+";_.RUNEPOOL_WITHDRAW="POOL-";_.CLAIM_TCY="tcy";_.STAKE_TCY="tcy+";_.UNSTAKE_TCY="tcy-"})(xA||={});var XN;((Y)=>{Y.BITGET="BITGET";Y.BRAVE="BRAVE";Y.COINBASE_MOBILE="COINBASE_MOBILE";Y.COINBASE_WEB="COINBASE_WEB";Y.COSMOSTATION="COSMOSTATION";Y.CTRL="CTRL";Y.EIP6963="EIP6963";Y.EXODUS="EXODUS";Y.KEEPKEY="KEEPKEY";Y.KEEPKEY_BEX="KEEPKEY_BEX";Y.KEPLR="KEPLR";Y.KEYSTORE="KEYSTORE";Y.LEAP="LEAP";Y.LEDGER="LEDGER";Y.METAMASK="METAMASK";Y.OKX="OKX";Y.OKX_MOBILE="OKX_MOBILE";Y.ONEKEY="ONEKEY";Y.PASSKEYS="PASSKEYS";Y.PASSKEY_WALLET="PASSKEY_WALLET";Y.PETRA="PETRA";Y.PHANTOM="PHANTOM";Y.POLKADOT_JS="POLKADOT_JS";Y.RADIX_WALLET="RADIX_WALLET";Y.TALISMAN="TALISMAN";Y.TREZOR="TREZOR";Y.TRONLINK="TRONLINK";Y.TRUSTWALLET_WEB="TRUSTWALLET_WEB";Y.VULTISIG="VULTISIG";Y.WALLETCONNECT="WALLETCONNECT";Y.WALLET_SELECTOR="WALLET_SELECTOR";Y.XAMAN="XAMAN"})(XN||={});var zA;((P)=>{P[P.NoError=36864]="NoError";P[P.LockedDevice=21781]="LockedDevice";P[P.TC_NotFound=65535]="TC_NotFound"})(zA||={});var UH=n.AllChains.reduce((A,H)=>{if(!A.THOR_STAGENET)A[n.StagenetChain.Maya]=n.StagenetMAYAConfig.rpcUrls,A[n.StagenetChain.THORChain]=n.StagenetTHORConfig.rpcUrls;return A[H]=n.getChainConfig(H).rpcUrls,A},{}),XH={[n.Chain.THORChain]:n.THORConfig.nodeUrl,[n.Chain.Maya]:n.MAYAConfig.nodeUrl,[n.StagenetChain.THORChain]:n.StagenetTHORConfig.nodeUrl,[n.StagenetChain.Maya]:n.StagenetMAYAConfig.nodeUrl},wA={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:n.AllChains,endpoints:{},envs:{apiUrl:"https://api.swapkit.dev",devApiUrl:"https://dev-api.swapkit.dev",isDev:!1,isStagenet:!1},feeMultipliers:void 0,integrations:{radix:{applicationName:"Swapkit Playground",applicationVersion:"0.0.1",dAppDefinitionAddress:"account_rdx128r289p58222hcvev7frs6kue76pl7pdcnw8725aw658v0zggkh9ws",network:{dashboardBase:"https://dashboard.radixdlt.com",networkId:1,networkName:"mainnet"}}},localMode:{enabled:!1,quoteUrl:"http://localhost:3000",swapUrl:"http://localhost:3001"},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:UH,thornodeUrls:XH,v3SwapFlow:{enabled:typeof process<"u"&&process.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(XN),widgetId:"",widgetKey:""},w=QA.createStore((A)=>({...wA,setApiKey:(H,T)=>A((P)=>({apiKeys:{...P.apiKeys,[H]:T}})),setConfig:(H)=>A((T)=>({apiKeys:{...T.apiKeys,...H?.apiKeys},chains:T.chains.concat(H?.chains||[]),endpoints:{...T.endpoints,...H?.endpoints},envs:{...T.envs,...H?.envs},feeMultipliers:H?.feeMultipliers||T.feeMultipliers,integrations:{...T.integrations,...H?.integrations},localMode:{...T.localMode,...H?.localMode},rpcUrls:{...T.rpcUrls,...H?.rpcUrls},thornodeUrls:{...T.thornodeUrls,...H?.thornodeUrls},v3SwapFlow:{...T.v3SwapFlow,...H?.v3SwapFlow},wallets:T.wallets.concat(H?.wallets||[]),widgetId:H?.widgetId||T.widgetId,widgetKey:H?.widgetKey||T.widgetKey})),setEndpoint:(H,T)=>A((P)=>({endpoints:{...P.endpoints,[H]:T}})),setEnv:(H,T)=>A((P)=>({envs:{...P.envs,[H]:T}})),setFeeMultipliers:(H)=>A(()=>({feeMultipliers:H})),setIntegrationConfig:(H,T)=>A((P)=>({integrations:{...P.integrations,[H]:T}})),setRequestOptions:(H)=>A((T)=>({requestOptions:{retry:{...T.requestOptions.retry,...H.retry},timeoutMs:H.timeoutMs||T.requestOptions.timeoutMs}})),setRpcUrl:(H,T)=>A((P)=>({rpcUrls:{...P.rpcUrls,[H]:T}})),setThornodeUrl:(H,T)=>A((P)=>({thornodeUrls:{...P.thornodeUrls,[H]:T}})),setWidgetId:(H)=>A({widgetId:H}),setWidgetKey:(H)=>A({widgetKey:H})})),g={get:(A)=>w.getState()[A],getState:w.getState,reinitialize:()=>w.setState(wA),set:(A)=>w.getState().setConfig(A),setApiKey:(A,H)=>w.getState().setApiKey(A,H),setEndpoint:(A,H)=>w.getState().setEndpoint(A,H),setEnv:(A,H)=>w.getState().setEnv(A,H),setFeeMultipliers:(A)=>w.getState().setFeeMultipliers(A),setIntegrationConfig:(A,H)=>w.getState().setIntegrationConfig(A,H),setRequestOptions:(A)=>w.getState().setRequestOptions(A),setRpcUrl:(A,H)=>w.getState().setRpcUrl(A,H),setThornodeUrl:(A,H)=>w.getState().setThornodeUrl(A,H),setWidgetId:(A)=>w.getState().setWidgetId(A),setWidgetKey:(A)=>w.getState().setWidgetKey(A)};var EH={};Q(EH,{SwapKitError:()=>u});var nH={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 VN(A){return JSON.stringify(A,(H,T)=>typeof T==="bigint"?T.toString():T)}class u extends Error{static ErrorCode=nH;errorKey;info;constructor(A,H){let T=typeof A==="string",P=T?A:A.errorKey,L=T?void 0:A.info,F=`${P}${L?`: ${VN(L)}`:""}`;super(F);if(Object.setPrototypeOf(this,u.prototype),this.name="SwapKitError",this.errorKey=P,this.info=L,this.cause=H,H){let R=H instanceof Error?`${H.message}${H.cause?` (${H.cause})`:""}`:VN(H);console.error(`SwapKitError [${P}]: ${R}`)}else if(L)console.error(`SwapKitError [${P}]: ${VN(L)}`)}}var bH=(A)=>new Promise((H)=>setTimeout(H,A)),xH=(A,{baseDelay:H,backoffMultiplier:T,maxDelay:P})=>Math.min(H*T**A,P);function zH(A,H){if(A instanceof Error&&A.name==="AbortError")return!0;if(A instanceof TypeError)return!0;if(H===429)return!0;if(H&&H>=500&&H<600)return!0;return!1}var QH=async(A,H)=>{let T=await fetch(A,H),P;try{P=await T.json()}catch{if(!T.ok)throw new u({errorKey:"helpers_invalid_response",info:{status:T.status,statusText:T.statusText}},{status:T.status,statusText:T.statusText});return{}}if(!T.ok){let F={data:P?.data,error:P?.error,message:P?.message,status:T.status};throw new u({errorKey:P?.error||"helpers_invalid_response",info:F},F)}let L=P?.routes?.length||P?.result||P?.data&&!P?.error;if(P?.error&&!L){let F={data:P.data,error:P.error,message:P.message,status:T.status};throw new u({errorKey:P.error,info:F},F)}if(P?.providerErrors?.length||P?.error&&L)console.warn("[SwapKit] Partial errors in response:",P.providerErrors||P.error);return P};function SN(A,H={}){return async function(P,L={}){let{searchParams:F,json:R,body:$,headers:O,dynamicHeader:U,retry:E,timeoutMs:_,abortController:W,onError:X,onSuccess:V,responseHandler:b,...x}={...H,...L},LN=g.get("requestOptions"),c={...LN.retry,...E},S=!!R||P.endsWith(".json"),MN=JH(P,F),YA=U?await U():{},FN=wH(S,{...O,...YA}),l=S?JSON.stringify(R):$,tN;for(let _N=0;_N<=c.maxRetries;_N++){let DA=W||new AbortController,gA=setTimeout(()=>DA.abort(),_||LN.timeoutMs);try{let q=await QH(MN,{...x,body:l,headers:FN,method:A,signal:DA.signal});return clearTimeout(gA),V?.(q)||b?.(q)||q}catch(q){clearTimeout(gA),tN=q;let GH=q?.cause?.status;if(_N>=c.maxRetries||!zH(q,GH))return X?X(q):Promise.reject(q);await bH(xH(_N,c))}}return X?X(tN):Promise.reject(tN)}}function wH(A,H){return{...H,...A&&{"Content-Type":"application/json"}}}function JH(A,H){let T=new URL(A);if(H)T.search=new URLSearchParams(H).toString();return T.toString()}var G={extend:(A)=>({extend:(H)=>G.extend({...A,...H}),get:SN("GET",A),post:SN("POST",A)}),get:SN("GET"),post:SN("POST")};var mH={};Q(mH,{initializeRPCUrlsWithFallback:()=>KH,getRPCUrlSync:()=>WA,getRPCUrl:()=>o,_rpcCache:()=>EN});var D=require("@swapkit/types"),vN=require("ts-pattern");var vH={};Q(vH,{wrapWithThrow:()=>jH,warnOnce:()=>f,getTHORNameCost:()=>tH,getMAYANameCost:()=>WH,getChainIdentifier:()=>VH});var nN=require("@swapkit/types");function tH(A){if(A<0)throw new u({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:A}});return 10+A}function WH(A){if(A<0)throw new u({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:A}});return Math.round((10+A*1.0512)*10000000000)/10000000000}function jH(A,H){try{return A()}catch(T){if(H)throw new u(H,T);return}}function VH(A){switch(A){case nN.Chain.THORChain:return`${A}.RUNE`;case nN.Chain.Cosmos:return`${A}.ATOM`;case nN.Chain.BinanceSmartChain:return`${A}`;default:return`${A}.${A}`}}var JA=new Set;function f({condition:A,id:H,warning:T}){if(A){if(JA.has(H))return;console.warn(T),JA.add(H)}}function qH(A){return vN.match(A).with(...D.EVMChains,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...D.UTXOChains,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(...D.CosmosChains,...D.StagenetChains,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(D.Chain.Polkadot,D.Chain.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(D.Chain.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(D.Chain.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(D.Chain.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(D.Chain.Aleo,D.Chain.Aptos,D.Chain.Tron,D.Chain.Radix,D.Chain.Stellar,()=>"").with(D.Chain.Hype,()=>({type:"meta"})).with(D.Chain.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(D.Chain.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(D.Chain.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new u("helpers_chain_not_supported",{chain:A})})}function ZA(A){return vN.match(A).with(D.Chain.Aptos,()=>"/-/healthy").with(D.Chain.Aleo,()=>"/mainnet/block/height/latest").with(D.Chain.Hype,()=>"/info").with(D.Chain.Radix,()=>"/status/network-configuration").with(D.Chain.Stellar,()=>"").with(D.Chain.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function tA(A,H){try{let T=H.startsWith("wss")?H.replace("wss","https"):H;if(A===D.Chain.Aleo||A===D.Chain.Stellar)return(await fetch(`${T}${ZA(A)}`,{cache:"no-store",method:"GET",signal:AbortSignal.timeout(3000)})).ok;return(await fetch(`${T}${ZA(A)}`,{body:JSON.stringify(qH(A)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}var EN=new Map,kH=120000;function WA(A){let[H=""]=g.get("rpcUrls")[A];if(!H)throw f({condition:!0,id:"helpers_chain_no_public_or_set_rpc_url",warning:`No public or set RPC URL found for chain. Please ensure you configured rpcUrls for ${A}.`}),new u("helpers_chain_no_public_or_set_rpc_url",{chain:A});let T=EN.get(A);if(T&&Date.now()-T.timestamp<kH)return T.url;return EN.set(A,{timestamp:Date.now(),url:H}),H}async function o(A){let H=WA(A),[,...T]=g.get("rpcUrls")[A];if(await tA(A,H))return H;for(let L of T)if(await tA(A,L))return EN.set(A,{timestamp:Date.now(),url:L}),L;throw new u("helpers_chain_rpc_connection_failed",{chain:A,fallbackUrls:T,primaryRpcUrl:H})}function KH(A){f({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 yH=[`${B.Chain.Maya}.MAYA`,`${B.Chain.Maya}.CACAO`,`${B.Chain.Ethereum}.THOR`,`${B.Chain.Ethereum}.vTHOR`,`${B.Chain.Kujira}.USK`,`${B.Chain.Ethereum}.FLIP`,`${B.Chain.Radix}.XRD`],vA=[B.Chain.Arbitrum,B.Chain.Aurora,B.Chain.Base,B.Chain.Ethereum,B.Chain.Optimism,B.Chain.Robinhood];async function pH(A){let{baseDecimal:H}=B.getChainConfig(B.Chain.Radix);try{let T=await o(B.Chain.Radix),{manager:P}=await G.post(`${T}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:A}),headers:{Accept:"*/*","Content-Type":"application/json"}});return P?.divisibility?.value?.divisibility}catch(T){let P=T instanceof Error?T.message:String(T);return console.warn(`Failed to fetch Radix asset decimals for ${A}: ${P}`),H}}async function fH(A){try{let H=await o(B.Chain.Radix);return(await G.post(`${H}/state/entity/details`,{body:JSON.stringify({addresses:[A],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((L)=>L.key==="symbol")?.value.typed.value||void 0}catch(H){let T=H instanceof Error?H.message:String(H);return console.warn(`Failed to fetch Radix asset symbol for ${A}: ${T}`),""}}async function qA({chain:A,address:H,methodHex:T,id:P}){let L=await o(A);return G.post(L,{body:JSON.stringify({id:P,jsonrpc:"2.0",method:"eth_call",params:[{data:T,to:H.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}async function oH(A){if(!A||A==="0x")return"UNKNOWN";try{let{AbiCoder:H}=await import("ethers");return H.defaultAbiCoder().decode(["string"],A)[0].trim()}catch(H){return console.warn(`Failed to decode ABI string from ${A}: ${H}`),"UNKNOWN"}}function CH(A,H){if(!A||A==="0x")return H;try{return Number(A)}catch(T){return console.warn(`Failed to decode ABI uint8 from ${A}: ${T}`),H}}async function dH({chain:A,address:H}){let{baseDecimal:T}=B.getChainConfig(A),P=H.toLowerCase();if(H===""||!P.startsWith("0x"))return T;let L=await qA({address:H,chain:A,id:2,methodHex:"0x313ce567"}).catch((R)=>{return console.warn(`Could not fetch decimals for ${H} on ${A}: ${R.message}`),{result:""}});return CH(L.result,T)}async function hH({chain:A,address:H}){let T=H.toLowerCase();if(T===""||!T.startsWith("0x"))return;let P=await qA({address:H,chain:A,id:1,methodHex:"0x95d89b41"}).catch((F)=>{return console.warn(`Could not fetch symbol for ${H} on ${A}: ${F.message}`),{result:""}});return await oH(P.result)}async function jA({rpcUrl:A,contractAddress:H,functionSelector:T}){return(await G.post(`${A}/wallet/triggerconstantcontract`,{body:JSON.stringify({contract_address:H,function_selector:T,owner_address:H,parameter:"",visible:!0}),headers:{accept:"application/json","content-type":"application/json"}}).catch(()=>{return}))?.constant_result?.[0]}function VA(A){let H=A.match(/.{2}/g)?.map((T)=>Number.parseInt(T,16))??[];return new TextDecoder().decode(new Uint8Array(H))}function cH(A){return s.match(A).with(void 0,()=>{return}).when((H)=>H.length>=128,(H)=>{let T=Number.parseInt(H.slice(64,128),16);return VA(H.slice(128,128+T*2))}).when((H)=>H.length===64,(H)=>{let T=H.replace(/0+$/,"");if(T.length>0&&T.length%2===0)return VA(T);return}).otherwise(()=>{return})}function qN({chain:A,address:H}){let{baseDecimal:T}=B.getChainConfig(A),P={decimals:T,ticker:void 0};return s.match(A).with(...B.EVMChains,async()=>{try{let{isAddress:L,getAddress:F}=await import("ethers");if(!L(F(H.replace(/^0X/,"0x"))))return P;let[R,$]=await Promise.all([hH({address:H,chain:A}),dH({address:H,chain:A})]);return{decimals:$,ticker:R}}catch(L){return console.warn(`Failed to fetch token info for ${H} on ${A}: ${L?.code} ${L?.message}`),P}}).with(B.Chain.Solana,async()=>{if(!H)return P;try{let L=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${H}`);if(L.ok){let F=await L.json(),R=Array.isArray(F)?F[0]:F;if(R)return{decimals:R.decimals??T,ticker:R.symbol||void 0}}}catch(L){console.warn(`Failed to fetch Solana token info for ${H}: ${L?.code} ${L?.message}`)}return P}).with(B.Chain.Tron,async()=>{if(!H)return P;try{let L=await o(B.Chain.Tron),[F,R]=await Promise.all([jA({contractAddress:H,functionSelector:"symbol()",rpcUrl:L}),jA({contractAddress:H,functionSelector:"decimals()",rpcUrl:L})]),$=cH(F);return{decimals:F!==void 0&&R?Number(BigInt(`0x${R}`)):T,ticker:$}}catch(L){let F=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Tron token info for ${H}: ${F}`),P}}).with(B.Chain.Near,async()=>{if(!H)return P;try{let{JsonRpcProvider:L}=await import("@near-js/providers"),F=await o(B.Chain.Near),$=await new L({url:F}).query({account_id:H,args_base64:Buffer.from("{}").toString("base64"),finality:"final",method_name:"ft_metadata",request_type:"call_function"}),O=JSON.parse(Buffer.from($.result).toString());return{decimals:O?.decimals||T,ticker:O?.symbol}}catch(L){let F=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Near token info for ${H}: ${F}`),P}}).with(B.Chain.Radix,async()=>{if(!H)return P;try{let[L,F]=await Promise.all([fH(H),pH(H)]);return{decimals:F,ticker:L}}catch(L){let F=L instanceof Error?L.message:String(L);return console.warn(`Failed to fetch Radix token info for ${H}: ${F}`),P}}).otherwise(async()=>P)}function kN({chain:A,symbol:H}){return s.match(A).with(...vA,()=>H==="ETH").with(B.Chain.Avalanche,()=>H==="AVAX").with(B.Chain.Berachain,()=>H==="BERA").with(B.Chain.Hyperevm,()=>H==="HYPE").with(B.Chain.Hype,()=>H==="HYPE").with(B.Chain.Spark,()=>H==="BTC").with(B.Chain.BinanceSmartChain,()=>H==="BNB").with(B.Chain.Gnosis,()=>H==="xDAI"||H==="XDAI").with(B.Chain.Monad,()=>H==="MON").with(B.Chain.XLayer,()=>H==="OKB").with(B.Chain.Maya,()=>H==="CACAO").with(B.Chain.Cosmos,()=>H==="ATOM").with(B.Chain.THORChain,()=>H==="RUNE").with(B.Chain.Tron,()=>H==="TRX").with(B.Chain.Ripple,()=>H==="XRP").with(B.Chain.Radix,()=>`${A}.${H}`===RN(A).identifier).otherwise(()=>H===A)}var RN=(A)=>{let{baseDecimal:H}=B.getChainConfig(A);return s.match(A.toUpperCase()).with(...vA,(P)=>({decimal:H,identifier:`${P}.ETH`})).with(B.Chain.THORChain,(P)=>({decimal:H,identifier:`${P}.RUNE`})).with(B.Chain.Cosmos,(P)=>({decimal:H,identifier:`${P}.ATOM`})).with(B.Chain.Maya,(P)=>({decimal:10,identifier:`${P}.CACAO`})).with(B.Chain.BinanceSmartChain,(P)=>({decimal:H,identifier:`${P}.BNB`})).with(B.Chain.Monad,(P)=>({decimal:H,identifier:`${P}.MON`})).with(B.Chain.Avalanche,(P)=>({decimal:H,identifier:`${P}.AVAX`})).with(B.Chain.Gnosis,(P)=>({decimal:H,identifier:`${P}.xDAI`})).with(B.Chain.XLayer,(P)=>({decimal:H,identifier:`${P}.OKB`})).with(B.Chain.Berachain,(P)=>({decimal:H,identifier:`${P}.BERA`})).with(B.Chain.Hyperevm,(P)=>({decimal:H,identifier:`${P}.HYPE`})).with(B.Chain.Hype,(P)=>({decimal:H,identifier:`${P}.HYPE`})).with(B.Chain.Spark,(P)=>({decimal:H,identifier:`${P}.BTC`})).with(B.Chain.Tron,(P)=>({decimal:H,identifier:`${P}.TRX`})).with(B.Chain.Solana,B.Chain.Chainflip,B.Chain.Kujira,B.Chain.Ripple,B.Chain.Polkadot,B.Chain.Near,...B.UTXOChains,(P)=>({decimal:H,identifier:`${P}.${P}`})).with(B.Chain.Radix,"XRD.XRD",()=>({decimal:H,identifier:"XRD.XRD"})).with(B.Chain.Polygon,"POL.POL",()=>({decimal:H,identifier:"POL.POL"})).with("KUJI.USK",(P)=>({decimal:6,identifier:P})).with("ETH.FLIP",()=>({decimal:B.getChainConfig(B.Chain.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:B.getChainConfig(B.Chain.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:B.getChainConfig(B.Chain.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(P)=>({decimal:10,identifier:P})).with("MAYA.MAYA",(P)=>({decimal:4,identifier:P})).otherwise(()=>({decimal:H,identifier:A}))};function bN({chain:A,symbol:H}){if(H.includes("/"))return"Synth";if(H.includes("~"))return"Trade";return s.match(A).with(B.Chain.Radix,()=>H===B.Chain.Radix||`${A}.${H}`===RN(A).identifier).with(B.Chain.Arbitrum,B.Chain.Optimism,B.Chain.Base,B.Chain.Aurora,B.Chain.Robinhood,()=>H===B.Chain.Ethereum).with(B.Chain.Cosmos,()=>H==="ATOM").with(B.Chain.BinanceSmartChain,()=>H==="BNB").with(B.Chain.Maya,()=>H==="CACAO").with(B.Chain.Monad,()=>H==="MON").with(B.Chain.THORChain,()=>H==="RUNE").with(B.Chain.Tron,()=>H==="TRX").with(B.Chain.Hyperevm,()=>H==="HYPE").with(B.Chain.Hype,()=>H==="HYPE").with(B.Chain.Spark,()=>H==="BTC").with(B.Chain.XLayer,()=>H==="OKB").otherwise(()=>H===A)?"Native":A}var K=(A)=>{let[H,...T]=A.split("."),P=A.includes("/"),L=T.join("."),F=L?.split("-"),R=F?.length?F.length===1?F[0]:F.slice(0,-1).join("-"):void 0;return{chain:H,symbol:L,synth:P,ticker:R}};function e(A,H){let P=H===B.Chain.Near?A.indexOf("-"):A.lastIndexOf("-");if(P===-1)return{address:void 0,ticker:A};return{address:A.slice(P+1),ticker:A.slice(0,P)}}function lH(A){return`https://storage.googleapis.com/token-list-swapkit-dev/images/${A.toLowerCase()}.png`}async function rH(A){let{loadTokenLists:H}=await Promise.resolve().then(() => (nA(),r)),T=await H(void 0,{source:g.get("envs").isDev?"dev":"prod"}),P=Object.values(T).flatMap((F)=>F.tokens);if("identifier"in A)return P.find((F)=>F.identifier===A.identifier)?.identifier;let L=A.contract.toLowerCase();for(let F of P){let{chain:R,symbol:$}=K(F.identifier);if(R!==A.chain)continue;let{address:O}=e($,R);if(O?.toLowerCase()===L)return F.identifier}return}var eH={};Q(eH,{validateTNS:()=>sH,validateIdentifier:()=>KN});var kA=["TERRA",...g.get("chains")];function KN(A=""){let H=A.toUpperCase(),[T]=H.split(".");if(kA.includes(T))return!0;let[P]=H.split("/");if(kA.includes(P))return!0;throw new u({errorKey:"helpers_invalid_identifier",info:{identifier:A,message:`Invalid identifier: ${A}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}function sH(A){if(A.length>30)return!1;let H=/^[a-zA-Z0-9+_-]+$/g;return!!A.match(H)}var HT={};Q(HT,{formatBigIntToSafeValue:()=>m,BigIntArithmetics:()=>k});var $N=require("ts-pattern"),a=8,aH=10;function m({value:A,bigIntDecimal:H=a,decimal:T=a}){if(T===0)return A.toString();let P=A<0n,L=A.toString().substring(P?1:0),F=T-(L.length-1);if(F>0)L="0".repeat(F)+L;let R=L.length-T,$=L.slice(-T);if(Number.parseInt($[H]||"0",10)>=5){let U=Number.parseInt($[H-1]||"0",10);$=`${$.substring(0,H-1)}${U+1}`}else $=$.substring(0,H);return`${P?"-":""}${L.slice(0,R)}.${$}`.replace(/\.?0*$/,"")}class k{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(A,H){return new k({decimal:H,value:m({bigIntDecimal:H,decimal:H,value:A})})}static shiftDecimals({value:A,from:H,to:T}){return k.fromBigInt(A.getBaseValue("bigint")*C(T)/C(H),T)}constructor(A){let H=mN(A),T=typeof A==="object";this.decimal=T?A.decimal:void 0,this.decimalMultiplier=T&&"decimalMultiplier"in A?A.decimalMultiplier:C(Math.max(KA(xN(H)),this.decimal||0)),this.#P(H)}set(A){return new this.constructor({decimal:this.decimal,identifier:this.toString?.({includeSynthProtocol:!0}),value:A})}add(...A){return this.#A("add",...A)}sub(...A){return this.#A("sub",...A)}mul(...A){return this.#A("mul",...A)}div(...A){return this.#A("div",...A)}gt(A){return this.#N("gt",A)}gte(A){return this.#N("gte",A)}lt(A){return this.#N("lt",A)}lte(A){return this.#N("lte",A)}eqValue(A){return this.#N("eqValue",A)}getValue(A,H){let T=BN(this.decimalMultiplier),P=H!==void 0?H:this.decimal,L=P!==void 0?P:T;if(P!==void 0&&P<T){if(this.formatBigIntToSafeValue(this.bigIntValue,P)==="0"&&this.bigIntValue!==0n)L=T}let F=this.formatBigIntToSafeValue(this.bigIntValue,L);return $N.match(A).with("number",()=>Number(F)).with("string",()=>F).with("bigint",()=>{return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}).otherwise(()=>F)}getBaseValue(A,H){let T=this.decimalMultiplier/C(H||this.decimal||a),P=AT(this.bigIntValue,T);return $N.match(A).with("number",()=>Number(P)).with("string",()=>P.toString()).otherwise(()=>P)}getBigIntValue(A,H){if(!H&&typeof A==="object")return A.bigIntValue;let T=mN(A),P=xN(T);if(P==="0"||P==="undefined")return 0n;return this.#T(P,H)}toSignificant(A=6){let H=this.getValue("string"),[T="",P=""]=H.split("."),L=Number.parseInt(T,10)>0;if((L?T.length+P.length:P.length)<=A)return H;if(T.length>=A)return T.slice(0,A).padEnd(T.length,"0");if(L)return`${T}.${P.slice(0,A-T.length)}`;let R=P.replace(/^0+/,"")||"0",$=R.slice(0,A),O=P.length-R.length;return`0.${$.padStart(O+$.length,"0")}`}toFixed(A=6){let H=this.getValue("string"),T=H.startsWith("-"),[P="0",L=""]=(T?H.slice(1):H).split("."),F=P==="0"&&Number.parseInt(L.slice(0,A),10)===0,R=T&&!F?"-":"";if(A===0){if(P==="0"&&!L)return"0";return L&&Number.parseInt(L[0]||"0",10)>=5?`${R}${BigInt(P)+1n}.0`:`${R}${P}.0`}if(!L)return`${R}${P}.${"0".repeat(A)}`;let $=L[A];if(!($&&Number.parseInt($,10)>=5))return`${R}${P}.${L.slice(0,A).padEnd(A,"0")}`;let U=BigInt(L.slice(0,A).padEnd(A,"0"))+1n,E=10n**BigInt(A);if(U>=E)return`${R}${BigInt(P)+1n}.${"0".repeat(A)}`;return`${R}${P}.${U.toString().padStart(A,"0")}`}toAbbreviation(A=2){let H=this.getValue("string"),T=Number(H),P=["","K","M","B","T","Q","Qi","S"],L=Math.floor(Math.log10(Math.abs(T))/3);if(L===0||!P[L])return H;return`${(T/10**(L*3)).toFixed(A)}${P[L]}`}toCurrency(A="$",{currencyPosition:H="start",decimal:T=2,decimalSeparator:P=".",thousandSeparator:L=",",trimTrailingZeros:F=!0}={}){let R=this.toFixed(T),$=H==="end",[O="0",U=""]=R.split("."),E=O.replace(/\B(?=(\d{3})+(?!\d))/g,L),_=U&&Number.parseInt(U,10)>0,W=_?`${E}${P}${U}`:E,V=W.length<100&&F&&_?W.replace(/\.?0*$/,""):W;return $?`${V}${A}`:`${A}${V}`}formatBigIntToSafeValue(A,H){let T=H||this.decimal||a,P=Math.max(T,BN(this.decimalMultiplier));return m({bigIntDecimal:T,decimal:P,value:A})}#A(A,...H){let T=this.#H(this,...H),P=BN(this.decimalMultiplier),F=Math.max(T,P)+aH,R=C(F),$=H.reduce((U,E)=>{let _=this.getBigIntValue(E,F);return $N.match(A).with("add",()=>U+_).with("sub",()=>U-_).with("mul",()=>U*_/R).with("div",()=>{if(_===0n)throw RangeError("Division by zero");return U*R/_}).otherwise(()=>U)},this.bigIntValue*R/this.decimalMultiplier),O=m({bigIntDecimal:F,decimal:F,value:$});return new this.constructor({decimal:this.decimal,decimalMultiplier:C(F),identifier:this.toString(),value:O})}#N(A,...H){let T=this.#H(this,...H),P=this.getBigIntValue(H[0]||"0",T),L=this.getBigIntValue(this,T);return $N.match(A).with("gt",()=>L>P).with("gte",()=>L>=P).with("lt",()=>L<P).with("lte",()=>L<=P).with("eqValue",()=>L===P).otherwise(()=>!1)}#P(A){let H=xN(A)||"0";this.bigIntValue=this.#T(H)}#H(...A){let H=A.map((T)=>{return typeof T==="object"?T.decimal||BN(T.decimalMultiplier):KA(xN(T))}).filter(Boolean);return Math.max(...H,a)}#T(A,H){let T=H?C(H):this.decimalMultiplier,P=BN(T),[L="",F=""]=A.split(".");return BigInt(`${L}${F.padEnd(P,"0")}`)}}var NT=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:!1});function xN(A){let T=`${typeof A==="number"?NT.format(A):mN(A)}`.replaceAll(",",".").split(".");return T.length>1?`${T.slice(0,-1).join("")}.${T.at(-1)}`:T[0]||"0"}function KA(A){let H=A.split(".")[1]?.length||0;return Math.max(H,a)}function mN(A){return typeof A==="object"?"getValue"in A?A.getValue("string"):A.value:A}function AT(A,H){if(H===0n)throw Error("Cannot divide by zero");let T=H/2n;return A>=0n&&H>=0n||A<0n&&H<0n?(A+T)/H:(A-T)/H}function C(A){return 10n**BigInt(A)}function BN(A){return Math.log10(Number.parseFloat(A.toString()))}var y=[M.Chain.Hype,M.Chain.Near,M.Chain.Ripple,M.Chain.Solana,M.Chain.Stellar,M.Chain.Sui,M.Chain.Ton,M.Chain.Tron],fN=[M.Chain.THORChain,M.Chain.Maya],NN=new Map,zN=new Map,AN=new Map,TT=3600000;function PT(A){let H=AN.get(A);if(H?.timestamp&&Date.now()-H.timestamp>TT){AN.delete(A);return}return H}function LT(A,H){if(AN.size>1000){let T=AN.keys().next().value;if(T)AN.delete(T)}AN.set(A,{...H,timestamp:Date.now()})}class J extends k{address;chain;isGasAsset=!1;isSynthetic=!1;isTradeAsset=!1;symbol;tax;ticker;type;chainId;constructor({value:A,decimal:H,tax:T,chain:P,symbol:L,identifier:F}){super(typeof A==="object"?A:{decimal:H,value:A});let R=mA(F||`${P}.${L}`);this.type=bN(R),this.tax=T,this.chain=R.chain,this.ticker=R.ticker,this.symbol=R.symbol,this.address=R.address,this.isSynthetic=R.isSynthetic,this.isTradeAsset=R.isTradeAsset,this.isGasAsset=R.isGasAsset,this.chainId=M.getChainConfig(R.chain).chainId}toString({includeSynthProtocol:A}={}){return(this.isSynthetic||this.isTradeAsset)&&!A?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){if(this.isSynthetic)return`${this.chain}.${this.symbol.replace(/\//g,".")}`;if(this.isTradeAsset)return`${this.chain}.${this.symbol.replace(/~/g,"..")}`;let A=this.symbol.replace(/\./g,"__");return`${this.chain}.${A}`}getIconUrl(){return NN.get(this.toString())?.logoURI}eqAsset({chain:A,symbol:H}){return this.chain===A&&this.symbol===H}eq(A){return this.eqAsset(A)&&this.eqValue(A)}static fromUrl(A,H=0){let T=A.indexOf(".");if(T===-1)throw new u({errorKey:"helpers_invalid_asset_url",info:{urlAsset:A}});let P=A.slice(0,T),L=A.slice(T+1),F=QN.match({chain:P,rest:L}).when(({rest:R})=>R.includes(".."),({chain:R,rest:$})=>`${R}.${$.replace(/\.\./g,"~")}`).when(({chain:R,rest:$})=>fN.includes(R)&&$.includes("."),({chain:R,rest:$})=>`${R}.${$.replace(/\./g,"/")}`).otherwise(({chain:R,rest:$})=>`${R}.${$.replace(/__/g,".")}`);return J.from({asset:F,value:H})}static from({value:A=0,fromBaseDecimal:H,asyncTokenLookup:T,...P}){let L=A instanceof k?A.getValue("string"):A,F="address"in P&&"chain"in P,R=$T(P);if(R===null&&T&&F){let{chain:FN,address:l}=P;return RT({address:l,chain:FN,fromBaseDecimal:H,parsedValue:L})}let $=F&&!R?`${P.chain}.UNKNOWN-${P.address}`:R,{identifier:O,decimal:U}=RN($),{chain:E,isSynthetic:_,isTradeAsset:W,address:X}=mA(O),{baseDecimal:V}=M.getChainConfig(E),b=NN.get(y.includes(E)?O:O.toUpperCase());if(!b&&T&&!_&&!W)return(async()=>{let{ticker:FN}=K(O),l=await yA({address:X,chain:E,ticker:FN});return pN({decimal:l.decimals,identifier:l.identifier,value:H?HN(BigInt(L),H):L})})();let x=b?.decimal||U;f({condition:!x&&!T,id:`assetValue_static_decimal_not_found_${E}`,warning:`Couldn't find static decimal for one or more tokens on ${E} (Using default ${V} 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:LN,identifier:c,tax:S}=b||{decimal:x||V,identifier:O},MN=H?HN(BigInt(L),H):HN(L,LN);return _||W?IT(c,MN):pN({decimal:LN,identifier:c,tax:S,value:MN})}static async loadStaticAssets(A){let{loadTokenLists:H}=await import("@swapkit/tokens"),T=await H(A,{source:g.get("envs").isDev?"dev":"prod"});for(let{tokens:P}of Object.values(T))for(let L of P){let{identifier:F}=L,{chain:R,symbol:$}=K(F),{address:O}=e($,R),{baseDecimal:U}=M.getChainConfig(R),E=y.includes(R)?F:F.toUpperCase(),_="decimals"in L&&L.decimals!==void 0?L.decimals:U,W="logoURI"in L&&L.logoURI?L.logoURI:`https://storage.googleapis.com/token-list-swapkit-dev/images/${F.toLowerCase()}.png`,X={decimal:_,identifier:F,logoURI:W,tax:"tax"in L?L.tax:void 0};if(NN.set(E,X),O){let V=y.includes(R)?`${R}:${O}`:`${R}:${O.toUpperCase()}`;zN.set(V,F)}}return!0}static setStaticAssets(A){NN.clear(),zN.clear();for(let[H,T]of A.entries()){let{identifier:P}=T,{chain:L,symbol:F}=K(P),{address:R}=e(F,L),{baseDecimal:$}=M.getChainConfig(L),O=T.chain??L,U=T.address??R,E=y.includes(O)?P:P.toUpperCase(),_=T.decimals??T.decimal??$,W=T.logoURI??`https://storage.googleapis.com/token-list-swapkit-dev/images/${P.toLowerCase()}.png`,X={decimal:_,identifier:E,logoURI:W,tax:T.tax};if(NN.set(E,X),U){let V=y.includes(O)?`${O}:${U}`:`${O}:${U.toUpperCase()}`;zN.set(V,P)}}return!0}static get staticAssets(){return NN}}function FT(A){let H=J.from({chain:A});return QN.match(A).with(M.Chain.Bitcoin,M.Chain.Litecoin,M.Chain.BitcoinCash,M.Chain.Dash,()=>H.set(0.00010001)).with(M.Chain.Dogecoin,()=>H.set(1.00000001)).with(M.Chain.Avalanche,M.Chain.Ethereum,M.Chain.Arbitrum,M.Chain.BinanceSmartChain,()=>H.set(0.00000001)).with(M.Chain.THORChain,M.Chain.Maya,()=>H.set(0)).with(M.Chain.Cosmos,M.Chain.Kujira,()=>H.set(0.000001)).otherwise(()=>H.set(0.00000001))}async function yA({chain:A,address:H,ticker:T}){let L=y.includes(A)?`${A}:${H||T}`:`${A}:${H||T}`.toUpperCase(),F=PT(L);if(F)return F;if(!H){let{baseDecimal:O}=M.getChainConfig(A);return{decimals:O,identifier:`${A}.${T||"UNKNOWN"}`}}let R=await qN({address:H,chain:A}),$=`${A}.${R.ticker||T||"UNKNOWN"}-${H}`;return f({condition:!!(!R.ticker&&T),id:`async_token_lookup_failed_${A}_${H}`,warning:`Could not fetch token metadata for ${A}:${H} from chain. Using user-provided ticker (${T}) with baseDecimal (${R.decimals}).`}),R.ticker&<(L,{decimals:R.decimals,identifier:$}),{decimals:R.decimals,identifier:$}}function pN({identifier:A,decimal:H,value:T,tax:P}){return KN(A),new J({decimal:H,identifier:A,tax:P,value:HN(T,H)})}function IT(A,H=0){let T=A.includes(".")?A.split(".")?.[0]?.toUpperCase():void 0,P=T?fN.includes(T):!1,L=A.slice(0,14).includes("~")?"~":"/",[F,R]=P?A.split(".").slice(1).join().split(L):A.split(L);if(!(F&&R))throw new u({errorKey:"helpers_invalid_asset_identifier",info:{identifier:A}});return new J({decimal:8,identifier:`${T||M.Chain.THORChain}.${F}${L}${R}`,value:HN(H,8)})}async function RT({address:A,chain:H,fromBaseDecimal:T,parsedValue:P}){let{decimals:L,identifier:F}=await yA({address:A,chain:H}),R=T?HN(BigInt(P),T):P;return pN({decimal:L,identifier:F,value:R})}function HN(A,H){return typeof A==="bigint"?m({bigIntDecimal:H,decimal:H,value:A}):A}function BT(A){let H=QN.match(A).when((T)=>("chain"in T)&&T.chain!==void 0,({chain:T})=>T).otherwise((T)=>{let P=K(T.asset);return P.synth?M.Chain.THORChain:P.chain});if(!M.AllChains.includes(H.toUpperCase())){let T="asset"in A?A.asset:H;throw new u({errorKey:"helpers_invalid_asset_identifier",info:{identifier:T,message:`Unsupported chain "${H}" - use the AssetValue constructor directly`}})}}function $T(A){if(BT(A),"chain"in A){let{chain:L,address:F}=A;if(F){let R=y.includes(L)?`${L}:${F}`:`${L}:${F.toUpperCase()}`,$=zN.get(R);if($)return $;return null}return L}let{chain:H,symbol:T}=K(A.asset);return bN({chain:H,symbol:T})==="Native"?H:A.asset}function OT(A,H,T){let P=A.split("."),L=P[0]?.toUpperCase(),F=fN.includes(L),R=T?"~":"/",[$,O=""]=F?P.slice(1).join(".").split(R):A.split(R);if(!($&&O))throw new u({errorKey:"helpers_invalid_asset_identifier",info:{identifier:A}});let{ticker:U,address:E}=pA({chain:$,symbol:O}),_=`${$}${R}${O}`;return{address:E,chain:L,isGasAsset:!1,isSynthetic:H,isTradeAsset:T,symbol:_,ticker:U}}function GT(A){let H=A.indexOf("."),T=(H===-1?A:A.slice(0,H)).toUpperCase(),P=H===-1?A:A.slice(H+1),{address:L,ticker:F}=pA({chain:T,symbol:P}),R;try{R=L&&M.EVMChains.includes(T)&&yN.getAddress(L)?yN.getAddress(L):L}catch{R=L}let $=R?`${F}-${R}`:P;return{address:R,chain:T,isGasAsset:kN({chain:T,symbol:P}),isSynthetic:!1,isTradeAsset:!1,symbol:$,ticker:F}}function mA(A){let H=A.slice(0,14),T=H.includes("/"),P=H.includes("~");if(T||P)return OT(A,T,P);return GT(A)}function pA({symbol:A,chain:H}){let{ticker:T,address:P}=e(A,H);return{address:P&&!y.includes(H)?P.toLowerCase():P,ticker:T}}var MT={};Q(MT,{SwapKitNumber:()=>ON});class ON extends k{eq(A){return this.eqValue(A)}static fromBigInt(A,H){return new ON({decimal:H,value:m({bigIntDecimal:H,decimal:H,value:A})})}}function fA(A=!0){return A?"https://gateway.liquify.com/chain/thorchain_midgard":"https://midgard.mayachain.info"}function _T(A=!0){let H=fA(A);return A?`${H}/v2/thorname`:`${H}/v2/mayaname`}function YT(A){return function(T){let P=T?`?status=${T}`:"";return G.get(`${A}/v2/pools${P}`)}}function DT(A){return function(T){return G.get(`${A}/v2/pool/${T}`)}}function gT(A){return function(T,P){let L=P?`?period=${P}`:"";return G.get(`${A}/v2/pool/${T}/stats${L}`)}}function UT(A){return function(T,P){let L=new URLSearchParams;if(P?.interval)L.append("interval",P.interval);if(P?.count)L.append("count",P.count.toString());if(P?.from)L.append("from",P.from.toString());if(P?.to)L.append("to",P.to.toString());let F=L.toString()?`?${L.toString()}`:"";return G.get(`${A}/v2/history/depths/${T}${F}`)}}function XT(A){return function(){return G.get(`${A}/v2/network`)}}function ST(A){return function(){return G.get(`${A}/v2/health`)}}function nT(A){return function(){return G.get(`${A}/v2/nodes`)}}function ET(A){return function(T){return G.get(`${A}/v2/node/${T}`)}}function bT(A){return function(){return G.get(`${A}/v2/mimir/votes`)}}function xT(A){return function(){return G.get(`${A}/v2/mimir`)}}function zT(A){return function(){return G.get(`${A}/v2/constants`)}}function QT(A){return function(){return G.get(`${A}/v2/stats`)}}function wT(A){return function(T){let P=new URLSearchParams;if(T?.interval)P.append("interval",T.interval);if(T?.count)P.append("count",T.count.toString());if(T?.from)P.append("from",T.from.toString());if(T?.to)P.append("to",T.to.toString());let L=P.toString()?`?${P.toString()}`:"";return G.get(`${A}/v2/history/earnings${L}`)}}function JT(A){return function(T,P){let L=new URLSearchParams;if(P?.interval)L.append("interval",P.interval);if(P?.count)L.append("count",P.count.toString());if(P?.from)L.append("from",P.from.toString());if(P?.to)L.append("to",P.to.toString());let F=L.toString()?`?${L.toString()}`:"",R=T?`/swaps/${T}`:"/swaps";return G.get(`${A}/v2/history${R}${F}`)}}function ZT(A){return function(T){let P=new URLSearchParams;if(T?.interval)P.append("interval",T.interval);if(T?.count)P.append("count",T.count.toString());if(T?.from)P.append("from",T.from.toString());if(T?.to)P.append("to",T.to.toString());let L=P.toString()?`?${P.toString()}`:"";return G.get(`${A}/v2/history/tvl${L}`)}}function tT(A){if(!A)return"";let H=new URLSearchParams,T=(P,L)=>{if(L!==void 0)H.append(P,typeof L==="number"?L.toString():L)};return T("address",A.address),T("txid",A.txid),T("asset",A.asset),T("type",A.type),T("affiliate",A.affiliate),T("limit",A.limit),T("offset",A.offset),H.toString()?`?${H.toString()}`:""}function WT(A){return function(T){let P=tT(T);return G.get(`${A}/v2/actions${P}`)}}function jT(A){return function(T){return G.get(`${A}/v2/member/${T}`)}}function VT(A){return function(T){let P=T?`/${T}`:"";return G.get(`${A}/v2/members${P}`)}}function vT(A){return function(T,P){let L=P?`&asset=${P}`:"";return G.get(`${A}/v2/saver/${T}${L?`?${L.substring(1)}`:""}`)}}function qT(A){return function(T){return G.get(`${A}/v2/savers/${T}`)}}function kT(A){return function(T,P){let L=new URLSearchParams;if(P?.interval)L.append("interval",P.interval);if(P?.count)L.append("count",P.count.toString());if(P?.from)L.append("from",P.from.toString());if(P?.to)L.append("to",P.to.toString());let F=L.toString()?`?${L.toString()}`:"",R=T?`/savers/${T}`:"/savers";return G.get(`${A}/v2/history${R}${F}`)}}function KT(A){return function(T){return G.get(`${A}/v2/balance/${T}`)}}function mT(A){return async function(T){let P=(L)=>{if(L?.cause?.status===404)return;throw L};return await G.get(`${A}/lookup/${T}`,{onError:P,retry:{maxRetries:1}})}}function yT(A){return async function(T){let P=(L)=>{if(L?.cause?.status===404)return[];throw L};return await G.get(`${A}/rlookup/${T}`,{onError:P,retry:{maxRetries:1}})}}function pT(A){return async function(T){let P=(L)=>{if(L?.cause?.status===404)return[];throw L};return await G.get(`${A}/owner/${T}`,{onError:P,retry:{maxRetries:1}})}}function TN({asset:A,value:H}){return J.from({asset:A,fromBaseDecimal:d.getChainConfig(d.Chain.THORChain).baseDecimal,value:H})}function fT({liquidityPositionGetter:A,isThorchain:H}){return async function(P){let L=await A(P),F=H?"rune":"cacao";return L.pools.map((R)=>({[`${F}Pending`]:TN({asset:"THOR.RUNE",value:R.runePending}),[`${F}RegisteredAddress`]:R.runeAddress,[`${F}Withdrawn`]:TN({asset:"THOR.RUNE",value:R.runeWithdrawn}),[F]:TN({asset:"THOR.RUNE",value:R.runeAdded}),asset:TN({asset:R.pool,value:R.assetAdded}),assetPending:TN({asset:R.pool,value:R.assetPending}),assetRegisteredAddress:R.assetAddress,assetWithdrawn:TN({asset:R.pool,value:R.assetWithdrawn}),dateFirstAdded:R.dateFirstAdded,dateLastAdded:R.dateLastAdded,poolShare:new ON(R.liquidityUnits).div(R.pool)}))}}function oA(A){let H=A===d.Chain.THORChain,T=fA(H),P=_T(H),L=jT(T);return{getActions:WT(T),getBalance:KT(T),getConstants:zT(T),getEarningsHistory:wT(T),getHealth:ST(T),getLiquidityPosition:fT({isThorchain:H,liquidityPositionGetter:L}),getLiquidityPositionRaw:L,getMembers:VT(T),getMimir:xT(T),getMimirVotes:bT(T),getNameDetails:mT(P),getNamesByAddress:yT(P),getNamesByOwner:pT(P),getNetworkInfo:XT(T),getNode:ET(T),getNodes:nT(T),getPool:DT(T),getPoolDepthHistory:UT(T),getPoolStats:gT(T),getPools:YT(T),getSaverDetails:vT(T),getSavers:qT(T),getSaversHistory:kT(T),getStats:QT(T),getSwapHistory:JT(T),getTVLHistory:ZT(T)}}var CA=oA(d.Chain.THORChain),dA=oA(d.Chain.Maya);var MA={};Q(MA,{searchTokens:()=>WP,getTrackerDetails:()=>xP,getTokenListProviders:()=>ZP,getTokenList:()=>tP,getTokenApproval:()=>JP,getSwapTo:()=>pP,getSwapQuote:()=>zP,getRouteWithTx:()=>QP,getPrice:()=>jP,getNearDepositChannel:()=>qP,getGasRate:()=>VP,getChainflipDepositChannel:()=>vP,getChainBalance:()=>wP,SKRequestClient:()=>t});var ZN=require("@swapkit/types"),p=require("ts-pattern");var oT={};Q(oT,{signWidgetRequest:()=>oN});async function oN(A,H,T,P){let L=`${H}:${T}:${P}`,F=new TextEncoder,R=await crypto.subtle.importKey("raw",F.encode(A),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),$=await crypto.subtle.sign("HMAC",R,F.encode(L));return Array.from(new Uint8Array($)).map((O)=>O.toString(16).padStart(2,"0")).join("")}var v=require("@swapkit/types"),N=require("zod");var dN;((P)=>{P.CHEAPEST="CHEAPEST";P.FASTEST="FASTEST";P.RECOMMENDED="RECOMMENDED"})(dN||={});var GN;((O)=>{O.PSBT="PSBT";O.EVM="EVM";O.COSMOS="COSMOS";O.RADIX="RADIX";O.NEAR="NEAR";O.STELLAR="STELLAR";O.TON="TON";O.TRON="TRON"})(GN||={});var hN;((x)=>{x.approve="approve";x.claim="claim";x.deposit="deposit";x.donate="donate";x.lending="lending";x.lp_action="lp_action";x.native_contract_call="native_contract_call";x.native_send="native_send";x.stake="stake";x.streaming_swap="streaming_swap";x.swap="swap";x.thorname_action="thorname_action";x.token_contract_call="token_contract_call";x.token_transfer="token_transfer";x.unknown="unknown";x.unstake="unstake"})(hN||={});var cN;((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"})(cN||={});var lN;(($)=>{$.unknown="unknown";$.not_started="not_started";$.pending="pending";$.swapping="swapping";$.completed="completed";$.refunded="refunded";$.failed="failed"})(lN||={});var rN;((b)=>{b.not_started="not_started";b.starting="starting";b.broadcasted="broadcasted";b.mempool="mempool";b.inbound="inbound";b.outbound="outbound";b.swapping="swapping";b.completed="completed";b.refunded="refunded";b.partially_refunded="partially_refunded";b.dropped="dropped";b.reverted="reverted";b.replaced="replaced";b.retries_exceeded="retries_exceeded";b.parsing_error="parsing_error"})(rN||={});var CT=N.object({address:N.optional(N.string()),chain:N.z.enum(v.Chain).optional(),chainId:N.z.enum(v.ChainId),coingeckoId:N.optional(N.string()),decimals:N.coerce.number(),extensions:N.optional(N.z.looseObject({})),identifier:N.string(),logoURI:N.optional(N.string()),name:N.optional(N.string()),shortCode:N.optional(N.string()),symbol:N.optional(N.string()),ticker:N.string()}),dT=N.z.object({block:N.z.optional(N.z.number().describe("Block number. Required for Polkadot chain. e.g. `123456`")),chainId:N.z.optional(N.z.string().describe("ChainId for the hash. e.g. `thorchain-1`")),depositChannelId:N.z.optional(N.z.string().describe("Deposit channel ID, required for Chainflip if tx was broadcasted without wallet connection")),hash:N.z.optional(N.z.string().describe("Hash for the first transaction broadcasted by the end user. e.g. `88D1819378ECD09E5284C54937CDC1E99B52F253C007617A02DD1200710CE677`"))}).refine((A)=>A.hash&&A.chainId||A.depositChannelId,{message:"Either `hash` and `chainId` or `depositChannelId` must be provided"}),hT=N.z.object({forceUpdate:N.z.string().toLowerCase().transform((A)=>A==="true").pipe(N.z.boolean()).optional()}),cT=N.object({error:N.string(),message:N.string()}),h=N.object({address:N.optional(N.string()),chain:N.z.enum(v.Chain),decimal:N.optional(N.number()),isGasAsset:N.boolean(),isSynthetic:N.boolean(),symbol:N.string(),tax:N.optional(N.object({buy:N.number(),sell:N.number()})),ticker:N.string()}),iN=N.object({id:N.string(),market_cap:N.number(),name:N.string(),price_change_24h_usd:N.number(),price_change_percentage_24h_usd:N.number(),sparkline_in_7d:N.array(N.number()),timestamp:N.string(),total_volume:N.number()}).partial(),lT=N.object({cg:N.optional(iN),identifier:N.string(),price_usd:N.number(),provider:N.string(),timestamp:N.number()}),sN=N.array(N.object({cg:N.optional(iN),identifier:N.string(),price_usd:N.number(),provider:N.string(),timestamp:N.number()}).partial()),rT=N.object({affiliate:N.optional(N.string().describe("Affiliate thorname")),affiliateFee:N.optional(N.number().describe("Affiliate fee in basis points").refine((A)=>A===Math.floor(A)&&A>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:N.optional(N.boolean().describe("Allow smart contract as recipient")),allowSmartContractSender:N.optional(N.boolean().describe("Allow smart contract as sender")),buyAsset:N.string().describe("Asset to buy"),cfBoost:N.optional(N.boolean().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:N.optional(N.string().describe("Address to send asset to")),disableSecurityChecks:N.optional(N.boolean().describe("Disable security checks")),includeTx:N.optional(N.boolean().describe("Set to true to include an transaction object (EVM only)")),providers:N.optional(N.array(N.string().describe("List of providers to use").refine((A)=>z[A]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:N.optional(N.string().describe("Referrer address (referral program)")),sellAmount:N.string().describe("Amount of asset to sell").refine((A)=>+A>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:N.string().describe("Asset to sell"),slippage:N.optional(N.number().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:N.optional(N.string().describe("Address to send asset from"))}).refine((A)=>A.sellAsset!==A.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),iT=N.object({metadata:N.boolean(),tokens:N.array(N.object({identifier:N.string()}))}),eN=N.object({destinationAddress:N.string()}),lA=eN.extend({affiliateFees:N.array(N.object({brokerAddress:N.string(),feeBps:N.number()})).optional(),brokerCommissionBps:N.number().optional(),buyAsset:N.object({asset:N.string(),chain:N.string()}),channelMetadata:N.object({cfParameters:N.string().optional(),gasBudget:N.string().optional(),message:N.string().optional()}).optional(),dcaParameters:N.object({chunkInterval:N.number().optional(),numberOfChunks:N.number().optional()}).optional(),maxBoostFeeBps:N.number().optional(),refundParameters:N.object({minPrice:N.string().optional(),refundAddress:N.string().optional(),retryDuration:N.number().optional()}).optional(),sellAsset:N.object({asset:N.string(),chain:N.string()})}),aN=N.object({channelId:N.string(),depositAddress:N.string()}),CN=eN.extend({affiliateFees:N.object({feeBps:N.number(),nearId:N.string()}).optional(),buyAsset:N.string(),sellAmount:N.string(),sellAsset:N.string(),slippage:N.coerce.number(),sourceAddress:N.string()}),hA=N.object({amountIn:N.string(),amountInFormatted:N.string(),amountInUsd:N.string(),amountOut:N.string(),amountOutFormatted:N.string(),amountOutUsd:N.string(),deadline:N.string().optional(),minAmountIn:N.string(),minAmountOut:N.string(),timeEstimate:N.number().optional(),timeWhenInactive:N.string().optional()}),sT=hA.extend({depositAddress:N.string(),quote:hA,signature:N.string(),timestamp:N.string(),tx:N.unknown()}),NA=N.object({buyAsset:N.string(),buyAssetAmount:N.string(),buyAssetAmountMaxSlippage:N.string(),deadline:N.string().optional(),depositAddress:N.string(),depositAmount:N.string(),depositAsset:N.string(),tx:N.unknown()}),eT=N.object({evmCalldata:N.z.optional(N.z.string()),intentHash:N.z.optional(N.z.string()),logs:N.z.optional(N.z.unknown()),manifest:N.z.optional(N.z.unknown()),memo:N.z.optional(N.z.string()),spender:N.z.optional(N.z.string()),thorname:N.z.optional(N.z.string())}),aT=N.object({currentStage:N.string(),inboundConfirmation:N.number(),inboundObservation:N.number(),outboundDelay:N.number(),outboundObservation:N.number(),streamingSwap:N.number()}),NP=N.object({count:N.optional(N.number()),interval:N.optional(N.number()),quantity:N.optional(N.number()),subSwapsMap:N.optional(N.array(N.number()))}),AP=N.z.object({currentLegIndex:N.z.optional(N.z.number()),estimatedTimeToComplete:N.z.number(),estimates:N.z.optional(aT),providerDetails:N.z.optional(N.z.object({streamingDetails:N.z.optional(NP)}))}),HP=N.object({affiliate:N.optional(h),liquidity:N.optional(h),network:N.optional(h),protocol:N.optional(h),tax:N.optional(h)}),TP=N.object({affiliate:N.string(),bps:N.string(),isReferrer:N.boolean()}),PP=N.object({affiliate:N.optional(N.string()),affiliateFees:N.optional(N.array(TP)),broadcastedAt:N.optional(N.number()),explorerUrl:N.optional(N.string()),fees:N.optional(HP),images:N.optional(N.object({chain:N.optional(N.string()),from:N.optional(N.string()),provider:N.optional(N.string()),to:N.optional(N.string())})),provider:N.optional(N.z.enum(z)),providerAction:N.z.optional(N.z.enum(cN)),quoteId:N.optional(N.string()),wallet:N.optional(N.string())}),PN=N.z.object({block:N.z.number(),chainId:N.z.enum(v.ChainId),finalAddress:N.z.optional(N.z.string()),finalAsset:N.z.optional(h),finalisedAt:N.z.number(),fromAddress:N.z.string(),fromAmount:N.z.string(),fromAsset:N.z.string(),hash:N.z.string(),meta:N.z.optional(PP),payload:N.z.optional(eT),status:N.z.enum(lN),toAddress:N.z.string(),toAmount:N.z.string(),toAsset:N.z.string(),trackingStatus:N.z.optional(N.z.enum(rN)),transient:N.z.optional(AP),type:N.z.enum(hN)}),AA=PN.extend({legs:N.z.array(PN)}),LP=PN.extend({legs:N.array(PN)}),FP=PN.extend({legs:N.array(PN)}),wN=N.array(N.object({amount:N.string(),asset:N.string(),chain:N.string(),protocol:N.z.enum(z),type:N.z.enum(UN)})),JN=N.z.object({inbound:N.z.optional(N.z.number().describe("Time to receive inbound asset in seconds")),outbound:N.z.optional(N.z.number().describe("Time to receive outbound asset in seconds")),swap:N.z.optional(N.z.number().describe("Time to swap assets in seconds")),total:N.z.number().describe("Total time in seconds")}),IP=/^(?:0x[0-9a-fA-F]+|[0-9]+)$/;function rA(A){return A===""||IP.test(A)}function RP(A){return A?BigInt(A):0n}function BP(A){let H=typeof A==="bigint"?A:BigInt(A);return H>0n?`0x${H.toString(16)}`:"0x0"}var uN=N.string().refine(rA,{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"),HA=N.object({data:N.string().describe("Data to send"),from:N.string().describe("Address of the sender"),to:N.string().describe("Address of the recipient"),value:uN}),TA=N.z.object({data:N.z.string().optional(),raw_data:N.z.object({contract:N.z.any(),data:N.z.string().optional(),expiration:N.z.number(),fee_limit:N.z.number().optional(),ref_block_bytes:N.z.string(),ref_block_hash:N.z.string(),timestamp:N.z.number()}).passthrough(),raw_data_hex:N.z.string(),txID:N.z.string(),value:uN.optional(),visible:N.z.boolean()}),iA=N.array(N.union([N.string(),N.number(),N.array(N.string()),N.object({from:N.string(),value:uN}).describe("Parameters to pass to the contract method")])),$P=N.object({approvalSpender:N.optional(N.string().describe("Address of the spender to approve")),approvalToken:N.optional(N.string().describe("Address of the token to approve spending of")),contractAddress:N.string().describe("Address of the contract to interact with"),contractMethod:N.string().describe("Name of the method to call"),contractParamNames:N.array(N.string().describe("Names of the parameters to pass to the contract method")),contractParams:iA}),OP=N.object({typeUrl:N.string("/types.MsgDeposit"),value:N.object({coins:N.array(N.object({amount:N.string(),asset:N.object({chain:N.string(),symbol:N.string(),synth:N.boolean(),ticker:N.string()})})),memo:N.string(),signer:N.string()})}),GP=N.object({typeUrl:N.string("/types.MsgSend"),value:N.object({amount:N.array(N.object({amount:N.string(),denom:N.string()})),fromAddress:N.string(),toAddress:N.string()})}),uP=N.object({typeUrl:N.string(),value:GP.shape.value.or(OP.shape.value)}),MP=N.object({amount:N.array(N.object({amount:N.string(),denom:N.string()})),gas:N.string()}),PA=N.object({accountNumber:N.number(),chainId:N.z.enum(v.ChainId),fee:MP,memo:N.string(),msgs:N.array(uP),sequence:N.number()}),sA=N.z.array(N.z.object({calldata:N.z.array(N.z.string()),contractAddress:N.z.string(),entrypoint:N.z.string()})),eA=N.z.object({address:N.z.string().describe("Destination address in friendly format"),amount:N.z.string().describe("Amount in nanotons"),payload:N.z.string().optional().describe("Base64 BOC of body cell"),stateInit:N.z.string().optional().describe("Base64 BOC of state init")}),LA=N.z.object({messages:N.z.array(eA),sendMode:N.z.number().describe("TON wallet send mode for the whole transfer")}),aA=N.object({affiliate:N.string().describe("Affiliate address").optional(),affiliateFee:N.number().describe("Affiliate fee").optional(),buyAsset:N.string().describe("Asset to buy"),destinationAddress:N.string().describe("Destination address"),estimatedTime:JN.optional(),provider:N.z.enum(z),sellAsset:N.string().describe("Asset to sell"),slipPercentage:N.number().describe("Slippage as a percentage"),sourceAddress:N.string().describe("Source address")}),_P=aA.omit({destinationAddress:!0,slipPercentage:!0,sourceAddress:!0}),NH=N.object({asset:N.string().describe("Asset name"),image:N.string().describe("Asset image"),price:N.number().describe("Price in USD")}),AH=lA,FA=N.object({assets:N.optional(N.array(NH)),maxStreamingQuantity:N.number().optional(),referrer:N.string().optional(),streamingInterval:N.number().optional(),tags:N.array(N.z.enum(dN))}),IA=FA.extend({affiliate:N.optional(N.string()),affiliateFee:N.optional(N.string()),approvalAddress:N.optional(N.string().describe("Approval address for swap")),chainflip:AH.optional(),garden:CN.optional(),near:CN.optional(),priceImpact:N.optional(N.number().describe("Price impact")),referrer:N.optional(N.string()),txType:N.optional(N.z.enum(GN))}),RA=N.array(N.object({code:N.z.enum(gN),display:N.string(),tooltip:N.string().optional()})),YP=N.object({buyAmount:N.string().describe("Buy amount"),buyAmountMaxSlippage:N.string().describe("Buy amount max slippage"),buyAsset:N.string().describe("Asset to buy"),fees:N.optional(wN),provider:N.z.enum(z),sellAmount:N.string().describe("Sell amount"),sellAsset:N.string().describe("Asset to sell")}),HH=N.object({buyAsset:N.string().describe("Asset to buy"),destinationAddress:N.optional(N.string().describe("Destination address")),estimatedTime:N.optional(JN),expectedBuyAmount:N.string().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:N.string().describe("Expected Buy amount max slippage"),expiration:N.optional(N.string().describe("Expiration")),fees:wN,inboundAddress:N.optional(N.string().describe("Inbound address")),legs:N.array(YP),memo:N.optional(N.string().describe("Memo")),meta:IA,providers:N.array(N.z.enum(z)),routeId:N.string().describe("Route ID"),sellAmount:N.string().describe("Sell amount"),sellAsset:N.string().describe("Asset to sell"),sourceAddress:N.optional(N.string().describe("Source address")),targetAddress:N.optional(N.string().describe("Target address")),totalSlippageBps:N.number().describe("Total slippage in bps"),tx:N.optional(N.union([HA,PA,TA,sA,LA,N.string()])),txType:N.optional(N.z.enum(GN)),warnings:RA}),BA=N.object({error:N.optional(N.string().describe("Error message")),providerErrors:N.optional(N.array(N.object({errorCode:N.optional(N.z.enum(i)),message:N.optional(N.string()),provider:N.z.enum(z).optional()}))),quoteId:N.string().describe("Quote ID"),routes:N.array(HH)}),$A=N.z.object({chainId:N.z.enum(v.ChainId),createdAt:N.z.date(),id:N.z.number(),unit:N.z.string(),value:N.z.string()}),DP=N.z.array($A),OA=N.z.union([$A,DP]),KL=N.array(N.object({chain:N.z.enum(v.Chain),decimal:N.number(),identifier:N.string(),symbol:N.string(),ticker:N.string(),value:N.string()})),gP=N.z.union([N.z.object({amount:N.z.string(),spender:N.z.string(),tokenIdentifier:N.z.string(),userWalletAddress:N.z.string()}),N.z.object({amount:N.z.string(),chainId:N.z.enum(v.ChainId),spender:N.z.string(),tokenContractAddress:N.z.string(),userWalletAddress:N.z.string()}),N.z.object({routeId:N.z.string()})]),UP=N.z.object({approvalTransaction:N.z.optional(N.z.object({data:N.z.string(),from:N.z.string(),gasLimit:N.z.optional(N.z.string()),gasPrice:N.z.optional(N.z.string()),to:N.z.string(),value:uN})),approvedAmount:N.z.string(),isApproved:N.z.boolean()}),TH=N.z.object({data:N.z.string().describe("Encoded approval call data"),from:N.z.string().describe("User wallet address"),gasLimit:N.z.string().optional().describe("Estimated gas limit"),gasPrice:N.z.string().optional().describe("Current gas price"),to:N.z.string().describe("Token contract address"),value:uN.describe("ETH value (always '0' for approvals)")}),PH=N.z.object({tx:N.z.string(),txType:N.z.literal("STELLAR")}),LH=N.z.union([TH,PH]),cA=N.z.object({buyAmount:N.z.string().describe("Buy amount").optional(),buyAmountMaxSlippage:N.z.string().describe("Buy amount max slippage").optional(),buyAsset:N.z.string().describe("Asset to buy"),expectedBuyAmount:N.z.string().describe("Expected Buy amount").optional(),expectedBuyAmountMaxSlippage:N.z.string().describe("Expected Buy amount max slippage").optional(),fees:wN,provider:N.z.enum(z),sellAmount:N.z.string().describe("Sell amount"),sellAsset:N.z.string().describe("Asset to sell")}),FH=cA.extend({estimatedTime:N.z.optional(JN),expiration:N.z.optional(N.z.string().describe("Expiration")),legs:N.z.array(cA),providers:N.z.array(N.z.enum(z)),routeId:N.z.string().describe("Route ID"),totalSlippageBps:N.z.number().describe("Total slippage in bps"),warnings:RA}).omit({provider:!0}),IH=N.z.object({method:N.z.string(),payload:N.z.optional(N.z.unknown()),url:N.z.string()}),XP=FH.extend({meta:FA,nextActions:N.z.optional(N.z.array(IH))}),SP=N.z.object({error:N.z.optional(N.z.string().describe("Error message")),providerErrors:N.z.optional(N.z.array(N.z.object({errorCode:N.z.optional(N.z.enum(i)),message:N.z.optional(N.z.string()),provider:N.z.enum(z).optional()}))),quoteId:N.z.string().describe("Quote ID"),routes:N.z.array(XP)}),nP=N.z.object({providers:N.z.array(N.z.enum(z)).optional().describe("Optional list of providers to query for trading pairs"),sellAsset:N.z.string().describe("Asset identifier to sell (e.g., 'BTC.BTC' or 'ETH.ETH')")}),RH=N.z.object({chain:N.z.enum(v.Chain).describe("Chain the asset is on"),identifier:N.z.string().describe("Asset identifier (e.g., 'ETH.USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')"),providers:N.z.array(N.z.enum(z)).describe("Providers that support this trading pair"),symbol:N.z.string().describe("Asset symbol"),ticker:N.z.string().describe("Asset ticker")}),EP=N.z.object({buyAssets:N.z.array(RH).describe("List of assets that can be swapped to"),sellAsset:N.z.string().describe("The input sell asset identifier")}),GA=FH.extend({destinationAddress:N.z.string().describe("Destination address"),inboundAddress:N.z.optional(N.z.string().describe("Inbound address")),memo:N.z.optional(N.z.string().describe("Memo to include in the transaction")),meta:IA,sourceAddress:N.z.string().describe("Source address"),targetAddress:N.z.optional(N.z.string().describe("Target address")),tx:N.optional(N.union([HA,PA,TA,LA,N.string()])),txType:N.z.optional(N.z.enum(GN))}),BH=N.z.object({data:N.z.optional(N.z.record(N.z.string(),N.z.string().optional())),errorCode:N.z.enum(i),message:N.z.string().optional(),provider:N.z.enum(z).optional()}),bP=N.z.object({error:N.z.optional(N.z.string().describe("Error message")),providerErrors:N.z.optional(N.z.array(BH)),quoteId:N.z.string().describe("Quote ID"),routes:N.z.array(GA)}),uA=GA.extend({approvalTx:LH.optional().describe("Optional approval transaction required before swap execution"),nextActions:N.z.optional(N.z.array(IH)),swapId:N.z.string().describe("The unique swap ID for tracking")});var t=G.extend({dynamicHeader:async()=>{let A=g.get("widgetId"),H=g.get("widgetKey");if(A&&H&&typeof window<"u"){let P=Math.floor(Date.now()/1000),L=window.location.origin,F=await oN(H,A,L,P);return{Origin:L,"X-Signature":F,"X-Timestamp":P.toString(),"x-widget-id":A}}let{swapKit:T}=g.get("apiKeys");return T?{"x-api-key":T}:{}}});async function xP(A){let H=await t.post(Z("/track"),{json:A});try{let T=AA.safeParse(H);if(!T.success)throw new u("api_v2_invalid_response",T.error);return T.data}catch(T){return H}}async function zP(A){let{getQuote:H}=g.get("endpoints");if(H)return H(A);let P=g.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",L=await t.post(Z(P),{json:A});if(L.error)throw new u("api_v2_server_error",{message:L.error});try{let F=BA.safeParse(L);if(!F.success)throw new u("api_v2_invalid_response",F.error);return F.data}catch{return L}}async function QP(A){let{getRouteWithTx:H}=g.get("endpoints");if(H)return H(A);let P=g.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",L=await t.post(Z(P),{json:A});try{let F=uA.safeParse(L);if(!F.success)throw new u("api_v2_invalid_response",F.error);return F.data}catch(F){return console.error(new u("api_v2_invalid_response",F)),L}}async function wP({chain:A,address:H,scamFilter:T=!0}){let{getBalance:P}=g.get("endpoints");if(P)return P({address:H,chain:A});let L=Z(`/balance?chain=${A}&address=${H}`),F=await t.get(L),R=Array.isArray(F)?F:[];return T?yP(R):R}function JP(A){let H=p.match(A).with({routeId:p.P.string,spender:p.P.string},({routeId:T,spender:P})=>Z(`/approve?routeId=${T}&sourceAddress=${P}`)).with({assetValue:p.P.instanceOf(J),spender:p.P.string,userWallet:p.P.string},({spender:T,userWallet:P,assetValue:L})=>Z(`/approve?tokenIdentifier=${L.toString()}&userWalletAddress=${P}&spender=${T}&amount=${L.getValue("string")}`)).exhaustive();return t.get(H)}function ZP(){let A=Z("/providers");return t.get(A)}function tP(A){let H=Z(`/tokens?provider=${A}`);return t.get(H)}function WP({query:A,chain:H,page:T,limit:P}){let L=new URLSearchParams({query:A});if(H!==void 0)L.set("chain",H);if(T!==void 0)L.set("page",T.toString());if(P!==void 0)L.set("limit",P.toString());let F=Z(`/tokens/search?${L.toString()}`);return t.get(F)}async function jP(A){let H=Z("/price"),T=await t.post(H,{json:A});try{let P=sN.safeParse(T);if(!P.success)throw new u("api_v2_invalid_response",P.error);return P.data}catch(P){throw new u("api_v2_invalid_response",P)}}async function VP(){let A=Z("/gas"),H=await t.get(A);try{let T=OA.safeParse(H);if(!T.success)throw new u("api_v2_invalid_response",T.error);return Array.isArray(T)?T:[T]}catch(T){throw new u("api_v2_invalid_response",T)}}async function vP(A){let{destinationAddress:H}=A;if(!H)throw new u("chainflip_broker_invalid_params");let T=g.get("integrations").chainflip?.brokerUrl||Z("/chainflip/broker/channel"),P=await t.post(T,{json:A});try{let L=aN.safeParse(P);if(!L.success)throw new u("api_v2_invalid_response",L.error);return L.data}catch(L){throw new u("api_v2_invalid_response",L)}}async function qP(A){let{destinationAddress:H}=A;if(!H)throw new u("chainflip_broker_invalid_params");let T=Z("/near/channel"),P=await t.post(T,{json:A});try{let L=NA.safeParse(P);if(!L.success)throw new u("api_v2_invalid_response",L.error);return L.data}catch(L){throw new u("api_v2_invalid_response",L)}}function Z(A){let{isDev:H,apiUrl:T,devApiUrl:P}=g.get("envs"),{enabled:L,quoteUrl:F,swapUrl:R}=g.get("localMode");if(L&&A){let[O]=A.split("?");if(O==="/quote"||O==="/v3/quote")return`${F}${A}`;if(O==="/swap"||O==="/v3/swap")return`${R}${A}`}return`${H?P:T}${A}`}function kP(A){try{return J.from({asset:A.identifier})}catch{return}}var KP=new Set(["OP.OP"]),mP=/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/im;function yP(A){return A.filter((H)=>{let T=kP(H);if(!T)return!1;if(KP.has(T.toString().toUpperCase()))return!0;return(!ZN.EVMChains.includes(T.chain)||T.isGasAsset||!!T.address)&&!mP.test(T.ticker)})}async function pP(A){let{getSwapTo:H}=g.get("endpoints");if(H)return H(A);let T=new URLSearchParams({sellAsset:A.sellAsset});if(A.providers?.length)for(let R of A.providers)T.append("providers",R);let P=Z(`/swapTo?${T.toString()}`),L=await t.get(P);if(!Array.isArray(L))return{buyAssets:[],sellAsset:A.sellAsset};let F=[];for(let R of L)try{let $=J.from({asset:R});F.push({chain:$.chain,identifier:$.toString(),providers:[],symbol:$.symbol,ticker:$.ticker})}catch{}return{buyAssets:F,sellAsset:A.sellAsset}}var _A={};Q(_A,{getThorchainQueue:()=>CP,getTcyStakers:()=>eP,getTcyStaker:()=>sP,getTcyClaimers:()=>NL,getTcyClaimer:()=>aP,getTNSPreferredAsset:()=>lP,getTHORNodeTNSDetails:()=>OH,getRunePoolProviderInfo:()=>iP,getRunePoolInfo:()=>rP,getNodes:()=>dP,getMimirInfo:()=>hP,getLastBlock:()=>oP,getInboundAddresses:()=>cP});var $H=require("ts-pattern");function j(A){let{isStagenet:H}=g.get("envs"),T=g.get("thornodeUrls");return`${$H.match({isStagenet:H,type:A}).with({type:"mayachain"},({isStagenet:L})=>L?T.MAYA_STAGENET:T.MAYA).otherwise(({isStagenet:L})=>L?T.THOR_STAGENET:T.THOR)}/${A??"thorchain"}`}function fP(A){let H=A==="mayachain"?"mayaname":"thorname";return`${j(A)}/${H}`}function oP(A="thorchain"){return G.get(`${j(A)}/lastblock`)}function CP(A){return G.get(`${j(A)}/queue`)}function dP(A){return G.get(`${j(A)}/nodes`)}function hP(A){return G.get(`${j(A)}/mimir`)}function cP(A){return G.get(`${j(A)}/inbound_addresses`)}async function OH({type:A,name:H}){try{return await G.get(`${fP(A)}/${H}`)}catch{return{affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:H,owner:"",preferred_asset:""}}}async function lP({type:A,tns:H}){let T=await OH({name:H,type:A});if(!T.preferred_asset||T.preferred_asset===".")return;return J.from({asset:T.preferred_asset,asyncTokenLookup:!0})}function rP(A){return G.get(`${j(A)}/runepool`)}function iP({type:A,thorAddress:H}){return G.get(`${j(A)}/rune_provider/${H}`)}function sP({type:A,address:H}){return G.get(`${j(A)}/tcy_staker/${H}`)}function eP(A){return G.get(`${j(A)}/tcy_stakers`)}function aP({type:A,address:H}){return G.get(`${j(A)}/tcy_claimer/${H}`)}function NL(A){return G.get(`${j(A)}/tcy_claimers`)}var AL={...MA,mayachainMidgard:dA,thorchainMidgard:CA,thornode:_A};
|