@vleap/warps 3.0.0-beta.187 → 3.0.0-beta.188
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.cts +16 -3
- package/dist/index.d.ts +16 -3
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -7,6 +7,7 @@ declare enum WarpChainName {
|
|
|
7
7
|
Ethereum = "ethereum",
|
|
8
8
|
Base = "base",
|
|
9
9
|
Arbitrum = "arbitrum",
|
|
10
|
+
Polygon = "polygon",
|
|
10
11
|
Somnia = "somnia",
|
|
11
12
|
Fastset = "fastset",
|
|
12
13
|
Solana = "solana",
|
|
@@ -468,9 +469,9 @@ type WarpMeta = {
|
|
|
468
469
|
creator: string;
|
|
469
470
|
createdAt: string;
|
|
470
471
|
};
|
|
471
|
-
type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpLinkAction | WarpMcpAction;
|
|
472
|
+
type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpLinkAction | WarpMcpAction | WarpPromptAction;
|
|
472
473
|
type WarpActionIndex = number;
|
|
473
|
-
type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link' | 'mcp';
|
|
474
|
+
type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link' | 'mcp' | 'prompt';
|
|
474
475
|
type WarpTransferAction = {
|
|
475
476
|
type: WarpActionType;
|
|
476
477
|
label: WarpText;
|
|
@@ -559,6 +560,17 @@ type WarpMcpDestination = {
|
|
|
559
560
|
tool: string;
|
|
560
561
|
headers?: Record<string, string>;
|
|
561
562
|
};
|
|
563
|
+
type WarpPromptAction = {
|
|
564
|
+
type: WarpActionType;
|
|
565
|
+
label: WarpText;
|
|
566
|
+
description?: WarpText | null;
|
|
567
|
+
prompt: string;
|
|
568
|
+
inputs?: WarpActionInput[];
|
|
569
|
+
primary?: boolean;
|
|
570
|
+
auto?: boolean;
|
|
571
|
+
next?: string;
|
|
572
|
+
when?: string;
|
|
573
|
+
};
|
|
562
574
|
type WarpActionInputSource = 'field' | 'query' | 'user:wallet' | 'hidden';
|
|
563
575
|
type BaseWarpActionInputType = 'string' | 'uint8' | 'uint16' | 'uint32' | 'uint64' | 'uint128' | 'uint256' | 'biguint' | 'bool' | 'address' | 'hex' | string;
|
|
564
576
|
type WarpActionInputType = string;
|
|
@@ -1045,6 +1057,7 @@ declare class WarpExecutor {
|
|
|
1045
1057
|
private executeMcp;
|
|
1046
1058
|
private buildCollectResult;
|
|
1047
1059
|
private callHandler;
|
|
1060
|
+
private executePrompt;
|
|
1048
1061
|
private evaluateWhenCondition;
|
|
1049
1062
|
}
|
|
1050
1063
|
|
|
@@ -1245,4 +1258,4 @@ declare class WarpValidator {
|
|
|
1245
1258
|
private validateSchema;
|
|
1246
1259
|
}
|
|
1247
1260
|
|
|
1248
|
-
export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
|
1261
|
+
export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
package/dist/index.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ declare enum WarpChainName {
|
|
|
7
7
|
Ethereum = "ethereum",
|
|
8
8
|
Base = "base",
|
|
9
9
|
Arbitrum = "arbitrum",
|
|
10
|
+
Polygon = "polygon",
|
|
10
11
|
Somnia = "somnia",
|
|
11
12
|
Fastset = "fastset",
|
|
12
13
|
Solana = "solana",
|
|
@@ -468,9 +469,9 @@ type WarpMeta = {
|
|
|
468
469
|
creator: string;
|
|
469
470
|
createdAt: string;
|
|
470
471
|
};
|
|
471
|
-
type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpLinkAction | WarpMcpAction;
|
|
472
|
+
type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpLinkAction | WarpMcpAction | WarpPromptAction;
|
|
472
473
|
type WarpActionIndex = number;
|
|
473
|
-
type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link' | 'mcp';
|
|
474
|
+
type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link' | 'mcp' | 'prompt';
|
|
474
475
|
type WarpTransferAction = {
|
|
475
476
|
type: WarpActionType;
|
|
476
477
|
label: WarpText;
|
|
@@ -559,6 +560,17 @@ type WarpMcpDestination = {
|
|
|
559
560
|
tool: string;
|
|
560
561
|
headers?: Record<string, string>;
|
|
561
562
|
};
|
|
563
|
+
type WarpPromptAction = {
|
|
564
|
+
type: WarpActionType;
|
|
565
|
+
label: WarpText;
|
|
566
|
+
description?: WarpText | null;
|
|
567
|
+
prompt: string;
|
|
568
|
+
inputs?: WarpActionInput[];
|
|
569
|
+
primary?: boolean;
|
|
570
|
+
auto?: boolean;
|
|
571
|
+
next?: string;
|
|
572
|
+
when?: string;
|
|
573
|
+
};
|
|
562
574
|
type WarpActionInputSource = 'field' | 'query' | 'user:wallet' | 'hidden';
|
|
563
575
|
type BaseWarpActionInputType = 'string' | 'uint8' | 'uint16' | 'uint32' | 'uint64' | 'uint128' | 'uint256' | 'biguint' | 'bool' | 'address' | 'hex' | string;
|
|
564
576
|
type WarpActionInputType = string;
|
|
@@ -1045,6 +1057,7 @@ declare class WarpExecutor {
|
|
|
1045
1057
|
private executeMcp;
|
|
1046
1058
|
private buildCollectResult;
|
|
1047
1059
|
private callHandler;
|
|
1060
|
+
private executePrompt;
|
|
1048
1061
|
private evaluateWhenCondition;
|
|
1049
1062
|
}
|
|
1050
1063
|
|
|
@@ -1245,4 +1258,4 @@ declare class WarpValidator {
|
|
|
1245
1258
|
private validateSchema;
|
|
1246
1259
|
}
|
|
1247
1260
|
|
|
1248
|
-
export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
|
1261
|
+
export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var fe=Object.create;var ot=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var ye=(r,t)=>{for(var e in t)ot(r,e,{get:t[e],enumerable:!0})},jt=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of he(t))!We.call(r,i)&&i!==e&&ot(r,i,{get:()=>t[i],enumerable:!(n=ge(t,i))||n.enumerable});return r};var z=(r,t,e)=>(e=r!=null?fe(me(r)):{},jt(t||!r||!r.__esModule?ot(e,"default",{value:r,enumerable:!0}):e,r)),ve=r=>jt(ot({},"__esModule",{value:!0}),r);var yr={};ye(yr,{BrowserCryptoProvider:()=>pt,CacheTtl:()=>Ot,NodeCryptoProvider:()=>lt,WARP_LANGUAGES:()=>Re,WarpBrandBuilder:()=>$t,WarpBuilder:()=>Vt,WarpCache:()=>nt,WarpCacheKey:()=>ht,WarpChainName:()=>Dt,WarpClient:()=>Ft,WarpConfig:()=>O,WarpConstants:()=>c,WarpExecutor:()=>it,WarpFactory:()=>M,WarpIndex:()=>at,WarpInputTypes:()=>g,WarpInterpolator:()=>T,WarpLinkBuilder:()=>j,WarpLinkDetecter:()=>st,WarpLogger:()=>x,WarpProtocolVersions:()=>U,WarpSerializer:()=>w,WarpTypeRegistry:()=>Ht,WarpValidator:()=>tt,address:()=>lr,applyOutputToMessages:()=>St,asset:()=>Nt,biguint:()=>or,bool:()=>pr,buildMappedOutput:()=>Z,buildNestedPayload:()=>zt,bytesToBase64:()=>be,bytesToHex:()=>Mt,cleanWarpIdentifier:()=>X,createAuthHeaders:()=>gt,createAuthMessage:()=>ft,createCryptoProvider:()=>Te,createDefaultWalletProvider:()=>Ye,createHttpAuthHeaders:()=>Me,createSignableMessage:()=>Kt,createWarpI18nText:()=>Ne,createWarpIdentifier:()=>ut,evaluateOutputCommon:()=>Jt,evaluateWhenCondition:()=>Ct,extractCollectOutput:()=>Y,extractIdentifierInfoFromUrl:()=>G,extractQueryStringFromIdentifier:()=>It,extractQueryStringFromUrl:()=>wt,extractResolvedInputValues:()=>B,extractWarpSecrets:()=>Ee,findWarpAdapterForChain:()=>m,getCryptoProvider:()=>Wt,getEventNameFromWarp:()=>xe,getLatestProtocolIdentifier:()=>_,getNextInfo:()=>Pt,getProviderConfig:()=>De,getRandomBytes:()=>yt,getRandomHex:()=>vt,getWalletFromConfigOrFail:()=>ze,getWarpActionByIndex:()=>P,getWarpBrandLogoUrl:()=>Ce,getWarpChainAssetLogoUrl:()=>we,getWarpChainInfoLogoUrl:()=>Ie,getWarpInfoFromIdentifier:()=>R,getWarpPrimaryAction:()=>$,getWarpWalletAddress:()=>Qt,getWarpWalletAddressFromConfig:()=>S,getWarpWalletExternalId:()=>Yt,getWarpWalletExternalIdFromConfig:()=>te,getWarpWalletExternalIdFromConfigOrFail:()=>_e,getWarpWalletMnemonic:()=>Zt,getWarpWalletMnemonicFromConfig:()=>Je,getWarpWalletPrivateKey:()=>Xt,getWarpWalletPrivateKeyFromConfig:()=>Ge,handleX402Payment:()=>Bt,hasInputPrefix:()=>Fe,hex:()=>cr,initializeWalletCache:()=>Ze,isEqualWarpIdentifier:()=>$e,isWarpActionAutoExecute:()=>ct,isWarpI18nText:()=>Be,isWarpWalletReadOnly:()=>Ke,mergeNestedPayload:()=>Tt,normalizeAndValidateMnemonic:()=>Xe,normalizeMnemonic:()=>ee,option:()=>ur,parseOutputOutIndex:()=>_t,parseSignedMessage:()=>qe,replacePlaceholders:()=>F,replacePlaceholdersInWhenExpression:()=>xt,resolveWarpText:()=>Q,safeWindow:()=>mt,setCryptoProvider:()=>Se,setWarpWalletInConfig:()=>Qe,shiftBigintBy:()=>K,splitInput:()=>dt,string:()=>rr,struct:()=>fr,testCryptoAvailability:()=>Pe,toInputPayloadValue:()=>Gt,toPreviewText:()=>At,tuple:()=>dr,uint16:()=>ir,uint32:()=>ar,uint64:()=>sr,uint8:()=>nr,validateMnemonicLength:()=>re,validateSignedMessage:()=>ke,vector:()=>gr,withAdapterFallback:()=>Ae});module.exports=ve(yr);var Dt=(u=>(u.Multiversx="multiversx",u.Vibechain="vibechain",u.Sui="sui",u.Ethereum="ethereum",u.Base="base",u.Arbitrum="arbitrum",u.Somnia="somnia",u.Fastset="fastset",u.Solana="solana",u.Near="near",u))(Dt||{}),c={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>r.config.user?.wallets?.[r.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},g={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},mt=typeof window<"u"?window:{open:()=>{}};var U={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},O={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${U.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${U.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",c.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var Ae=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var xe=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=c.Alerts.TriggerEventPrefix+c.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var Ce=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},we=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},Ie=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var pt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},lt=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},L=null;function Wt(){if(L)return L;if(typeof window<"u"&&window.crypto)return L=new pt,L;if(typeof process<"u"&&process.versions?.node)return L=new lt,L;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Se(r){L=r}async function yt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Wt()).getRandomBytes(r)}function Mt(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function be(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function vt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await yt(r/2,t);return Mt(e)}async function Pe(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await yt(16),r.randomBytes=!0}catch{}return r}function Te(){return Wt()}var Ee=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${c.Vars.Env}:`)).map(t=>{let e=t.replace(`${c.Vars.Env}:`,"").trim(),[n,i]=e.split(c.ArgCompositeSeparator);return{key:n,description:i||null}});var m=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},_=r=>{if(r==="warp")return`warp:${U.Warp}`;if(r==="brand")return`brand:${U.Brand}`;if(r==="abi")return`abi:${U.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},P=(r,t)=>r?.actions[t-1],$=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(s=>s.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(s=>e.includes(s.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},ct=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=$(t);return r===e}return!0},K=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),s=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(s,"0"));if(t<0){let a=n+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},At=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},F=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>t[n]||""),xt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Ct=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var Re={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},Q=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},Be=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Ne=r=>r;var X=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,$e=(r,t)=>!r||!t?!1:X(r)===X(t),ut=(r,t,e)=>{let n=X(e);return t===c.IdentifierType.Alias?c.IdentifierAliasMarker+r+c.IdentifierParamSeparator+n:r+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+n},R=r=>{let t=decodeURIComponent(r).trim(),e=X(t),n=e.split("?")[0],i=kt(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Hash,identifier:e,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,o]=i;if(a===c.IdentifierType.Alias||a===c.IdentifierType.Hash){let p=e.includes("?")?o+e.substring(e.indexOf("?")):o;return{chain:s,type:a,identifier:p,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===c.IdentifierType.Alias||s===c.IdentifierType.Hash){let o=e.includes("?")?a+e.substring(e.indexOf("?")):a;return{chain:c.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==c.IdentifierType.Alias&&s!==c.IdentifierType.Hash){let o=e.includes("?")?a+e.substring(e.indexOf("?")):a,p=Ve(a,s)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:s,type:p,identifier:o,identifierBase:a}}}return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Alias,identifier:e,identifierBase:n}},G=r=>{let t=new URL(r),n=t.searchParams.get(c.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return R(i)},Ve=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Oe=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},kt=r=>{let t=Oe(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),s=r.substring(n+e.length),a=kt(s);return[i,...a]},wt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},It=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null};var dt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Fe=r=>{let t=new Set(Object.values(g));if(!r.includes(c.ArgParamsSeparator))return!1;let e=dt(r)[0];return t.has(e)};var St=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,s])=>{let a=Q(s,e);return[i,F(a,t)]});return Object.fromEntries(n)};var qt=z(require("qr-code-styling"),1);var j=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!G(t):!1}build(t,e,n){let i=this.config.clientUrl||O.DefaultClientUrl(this.config.env),s=m(t,this.adapters),a=e===c.IdentifierType.Alias?n:e+c.IdentifierParamSeparator+n,o=s.chainInfo.name+c.IdentifierParamSeparator+a,p=encodeURIComponent(o);return O.SuperClientUrls.includes(i)?`${i}/${p}`:`${i}?${c.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let e=R(t);if(!e)return null;let n=m(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,s="white",a="black",o="#23F7DD"){let p=m(t,this.adapters),l=this.build(p.chainInfo.name,e,n);return new qt.default({type:"svg",width:i,height:i,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var He="https://",Pt=(r,t,e,n,i)=>{let s=e.actions?.[n-1]?.next||e.next||null;if(!s)return null;if(s.startsWith(He))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let f=F(a,{...e.vars,...i});return[{identifier:f,url:bt(t,f,r)}]}let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let f=F(o,{...e.vars,...i}),v=f?`${a}?${f}`:a;return[{identifier:v,url:bt(t,v,r)}]}let l=p[0];if(!l)return[];let u=l.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let W=p.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let v=o;for(let{regex:E,field:N}of W){let C=N?Ue(f,N):f;if(C==null)return null;v=v.replace(E,C)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${a}?${v}`:a;return{identifier:A,url:bt(t,A,r)}}).filter(f=>f!==null)},bt=(r,t,e)=>{let[n,i]=t.split("?"),s=R(n)||{chain:c.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},a=m(s.chain,r);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let o=new j(e,r).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let p=new URL(o);return new URLSearchParams(i).forEach((l,u)=>p.searchParams.set(u,l)),p.toString().replace(/\/\?/,"?")},Ue=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var D=class D{static debug(...t){D.isTestEnv||console.debug(...t)}static info(...t){D.isTestEnv||console.info(...t)}static warn(...t){D.isTestEnv||console.warn(...t)}static error(...t){D.isTestEnv||console.error(...t)}};D.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=D;function zt(r,t,e){return r.startsWith(c.Position.Payload)?r.slice(c.Position.Payload.length).split(".").reduceRight((n,i,s,a)=>({[i]:s===a.length-1?{[t]:e}:n}),{}):{[t]:e}}function Tt(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=Tt(e[n],t[n]):e[n]=t[n]}),e}function Gt(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function B(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function Z(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,s=Gt(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let a=zt(n.input.position,i,s);e=Tt(e,a)}else e[i]=s}),e}var Y=async(r,t,e,n,i,s)=>{let a=[],o=[],p={};for(let[u,d]of Object.entries(r.output||{})){if(d.startsWith(c.Transform.Prefix))continue;let h=_t(d);if(h!==null&&h!==e){p[u]=null;continue}let[W,...y]=d.split("."),f=(v,A)=>A.reduce((E,N)=>E&&E[N]!==void 0?E[N]:null,v);if(W==="out"||W.startsWith("out[")){let v=y.length===0?t?.data||t:f(t,y);a.push(String(v)),o.push(v),p[u]=v}else p[u]=d}let l=Z(n,i);return{values:{string:a,native:o,mapped:l},output:await Jt(r,p,e,n,i,s)}},Jt=async(r,t,e,n,i,s)=>{if(!r.output)return t;let a={...t};return a=Le(a,r,e,n,i),a=await je(r,a,s.transform?.runner||null),a},Le=(r,t,e,n,i)=>{let s={...r},a=P(t,e)?.inputs||[];for(let[o,p]of Object.entries(s))if(typeof p=="string"&&p.startsWith("in.")){let l=p.split(".")[1],u=a.findIndex(h=>h.as===l||h.name===l),d=u!==-1?n[u]?.value:null;s[o]=d?i.stringToNative(d)[1]:null}return s},je=async(r,t,e)=>{if(!r.output)return t;let n={...t},i=Object.entries(r.output).filter(([,s])=>s.startsWith(c.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(c.Transform.Prefix.length)}));if(i.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:a}of i)try{n[s]=await e.run(a,n)}catch(o){x.error(`Transform error for output '${s}':`,o),n[s]=null}return n},_t=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var De=(r,t,e,n)=>{let i=r.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:n}};async function Kt(r,t,e,n=5){let i=await vt(64,e),s=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function ft(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Kt(r,i,e,5)}function gt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Me(r,t,e,n){let{message:i,nonce:s,expiresAt:a}=await ft(r,e,n),o=await t(i);return gt(r,o,s,a)}function ke(r){let t=new Date(r).getTime();return Date.now()<t}function qe(r){try{let t=JSON.parse(r);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var ze=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Qt=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>Qt(r.user?.wallets?.[t]||null),Xt=r=>r?typeof r=="string"?r:r.privateKey||null:null,Zt=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Yt=r=>r?typeof r=="string"?r:r.externalId||null:null,Ge=(r,t)=>Xt(r.user?.wallets?.[t]||null)?.trim()||null,Je=(r,t)=>Zt(r.user?.wallets?.[t]||null)?.trim()||null,te=(r,t)=>Yt(r.user?.wallets?.[t]||null)?.trim()||null,_e=(r,t)=>{let e=te(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Ke=r=>typeof r=="string",Qe=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},ee=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},re=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},Xe=(r,t=24)=>{let e=ee(r);return re(e,t),e};async function Ze(r){let t={address:null,publicKey:null};if(!r)return t;try{t.address=await r.getAddress()}catch{}try{t.publicKey=await r.getPublicKey()}catch{}return t}function Ye(r,t,e){return null}var Et=require("@x402/core/client"),Rt=require("@x402/core/http");async function Bt(r,t,e,n,i){let s=await tr(r,i);if(!s)return r;let a=new Headers;n&&a.set("Content-Type","application/json"),a.set("Accept","application/json"),Object.entries(s).forEach(([p,l])=>{a.set(p,l)}),x.debug("WarpExecutor: Retrying request with payment headers");let o=await fetch(t,{method:e,headers:a,body:n});return x.debug("WarpExecutor: Payment processed, new response status",{status:o.status}),o}var tr=async(r,t)=>{let e=await er(r),i=new Rt.x402HTTPClient(new Et.x402Client).getPaymentRequiredResponse(s=>r.headers.get(s),e);if(!i?.accepts?.length)return null;for(let s of t)if(s.wallet.registerX402Handlers)try{let a=new Et.x402Client,o=await s.wallet.registerX402Handlers(a),p=i.accepts.find(h=>h?.network&&o[h.network]);if(!p?.network)continue;o[p.network]();let l=new Rt.x402HTTPClient(a),u=await l.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=l.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return x.debug(`WarpExecutor: x402 payment processed with ${s.chainInfo.name} adapter using ${p.network} scheme`),d}catch{continue}return null},er=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===g.Tuple&&Array.isArray(e)){if(e.length===0)return t+c.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e.map(a=>this.getTypeAndValue(a)),i=n.map(([a])=>a),s=n.map(([,a])=>a);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===g.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,s=Object.keys(n).filter(o=>o!=="_name");if(s.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let a=s.map(o=>{let[p,l]=this.getTypeAndValue(n[o]);return`(${o}${c.ArgParamsSeparator}${p})${l}`});return`${t}(${i})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}if(t===g.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${c.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e[0],i=n.indexOf(c.ArgParamsSeparator),s=n.substring(0,i),a=e.map(p=>{let l=p.indexOf(c.ArgParamsSeparator),u=p.substring(l+1);return s.startsWith(g.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),o=s.startsWith(g.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+s+c.ArgParamsSeparator+a.join(o)}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===g.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?g.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):g.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t+c.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(c.ArgParamsSeparator),n=e[0],i=e.slice(1).join(c.ArgParamsSeparator);if(n==="null")return[n,null];if(n===g.Option){let[s,a]=i.split(c.ArgParamsSeparator);return[g.Option+c.ArgParamsSeparator+s,a||null]}if(n===g.Vector){let s=i.indexOf(c.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),p=a.startsWith(g.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(o?o.split(p):[]).map(d=>this.stringToNative(a+c.ArgParamsSeparator+d)[1]);return[g.Vector+c.ArgParamsSeparator+a,u]}else if(n.startsWith(g.Tuple)){let s=n.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),o=i.split(c.ArgCompositeSeparator).map((p,l)=>this.stringToNative(`${s[l]}${c.IdentifierParamSeparator}${p}`)[1]);return[n,o]}else if(n.startsWith(g.Struct)){let s=n.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:s[1]};return i&&i.split(c.ArgListSeparator).forEach(p=>{let l=p.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(l){let[,u,d,h]=l;o[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${h}`)[1]}}),[n,o]}else{if(n===g.String)return[n,i];if(n===g.Uint8||n===g.Uint16||n===g.Uint32)return[n,Number(i)];if(n===g.Uint64||n===g.Uint128||n===g.Uint256||n===g.Biguint)return[n,BigInt(i||0)];if(n===g.Bool)return[n,i==="true"];if(n===g.Address)return[n,i];if(n===g.Hex)return[n,i];if(n===g.Asset){let[s,a]=i.split(c.ArgCompositeSeparator),o={identifier:s,amount:BigInt(a)};return[n,o]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(n);if(s){let o=s.stringToNative(i);return[n,o]}let a=this.typeRegistry.resolveType(n);if(a!==n){let[o,p]=this.stringToNative(`${a}:${i}`);return[n,p]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(c.ArgParamsSeparator)){let[e,n]=t.split(c.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[g.Uint32,t]:typeof t=="bigint"?[g.Uint64,t]:typeof t=="boolean"?[g.Bool,t]:[typeof t,t]}};var rr=r=>new w().nativeToString(g.String,r),nr=r=>new w().nativeToString(g.Uint8,r),ir=r=>new w().nativeToString(g.Uint16,r),ar=r=>new w().nativeToString(g.Uint32,r),sr=r=>new w().nativeToString(g.Uint64,r),or=r=>new w().nativeToString(g.Biguint,r),pr=r=>new w().nativeToString(g.Bool,r),lr=r=>new w().nativeToString(g.Address,r),Nt=r=>new w().nativeToString(g.Asset,r),cr=r=>new w().nativeToString(g.Hex,r),ur=(r,t)=>{if(t===null)return g.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),s=e.substring(n+1);return g.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+s},dr=(...r)=>new w().nativeToString(g.Tuple,r),fr=r=>new w().nativeToString(g.Struct,r),gr=r=>new w().nativeToString(g.Vector,r);var ne=z(require("ajv"),1);var $t=class{constructor(t){this.pendingBrand={protocol:_("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||O.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),s=new ne.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var ie=z(require("ajv"),1);var tt=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=$(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&e.push(`${s} name '${a}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(a=>a.type==="contract"),n=t.actions.some(a=>a.type==="query");if(!e&&!n)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||O.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),s=new ie.default({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var Vt=class{constructor(t){this.config=t;this.pendingWarp={protocol:_("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return At(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new tt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
-
`))}};var et=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,mr);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,hr))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}},ae=new w,hr=(r,t)=>typeof t=="bigint"?ae.nativeToString("biguint",t):t,mr=(r,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?ae.stringToNative(t)[1]:t;var H=class H{get(t){let e=H.cache.get(t);return e?Date.now()>e.expiresAt?(H.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;H.cache.set(t,{value:e,expiresAt:i})}forget(t){H.cache.delete(t)}clear(){H.cache.clear()}};H.cache=new Map;var rt=H;var Ot={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},ht={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`},nt=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new et:t==="memory"?new rt:typeof window<"u"&&window.localStorage?new et:new rt}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var T=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);return await this.applyGlobals(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),s=(a,o)=>{i=i.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o!="string")s(a,o);else if(o.startsWith(c.Vars.Query+c.ArgParamsSeparator)){let p=o.slice(c.Vars.Query.length+1),[l,u]=p.split(c.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(l):null,W=e.queries?.[l]||null||d;W&&s(a,W)}else if(o.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let p=o.slice(c.Vars.Env.length+1),[l,u]=p.split(c.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[l];h&&s(a,h)}else o===c.Source.UserWallet&&n?s(a,n):s(a,o)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(e,n,i);return F(s,a)}applyGlobalsToText(t){if(!Object.values(c.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)||t.includes(`{{${a}:`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(c.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString())),s=this.replacePlaceholdersWithChain(s,a.Placeholder,i,a.Accessor)}),s}replacePlaceholdersWithChain(t,e,n,i){let s=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(s,(a,o)=>{let p=o.trim().toLowerCase();if(!this.adapters)return a;try{let l=m(p,this.adapters),u={config:this.config,adapter:l},d=i(u);return d!=null?d.toString():a}catch{return a}})}buildInputBag(t,e,n){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=e.stringToNative(s.value);i[a]=String(o)}),n&&n.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=e.stringToNative(s.value);if(i[`primary.${a}`]=String(o),s.input.type==="asset"&&typeof s.input.position=="object"){let p=o;p&&typeof p=="object"&&"identifier"in p&&"amount"in p&&(i[`primary.${a}.token`]=String(p.identifier),i[`primary.${a}.amount`]=String(p.amount))}}),i}};var M=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new nt(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(ht.WarpExecutable(t,e||"",n))||[];return B(i)}async createExecutable(t,e,n,i={}){let s=P(t,e);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,n),o=m(a.name,this.adapters),p=new T(this.config,o,this.adapters),l=await p.apply(t,i),u=P(l,e),{action:d,index:h}=$(l),W=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(a.name,d,W,p),f=await this.getModifiedInputs(y),v=[],A=[];h===e-1?(v=y,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(a.name,u,n,p),A=await this.getModifiedInputs(v));let E=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,N=this.getDestinationFromAction(u),C=E?this.serializer.stringToNative(E)[1]:N;if(C&&(C=p.applyInputs(C,A,this.serializer,f)),!C&&s.type!=="collect"&&s.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let k=this.getPreparedArgs(u,A);k=k.map(I=>p.applyInputs(I,A,this.serializer,f));let q=A.find(I=>I.input.position==="value")?.value||null,b="value"in u?u.value:null,V=q?.split(c.ArgParamsSeparator)[1]||b||"0",J=p.applyInputs(V,A,this.serializer,f),se=BigInt(J),oe=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),pe=[...("transfers"in u?u.transfers:[])||[],...oe||[]].map(I=>{let de=p.applyInputs(I,A,this.serializer,f);return this.serializer.stringToNative(de)[1]}),le=A.find(I=>I.input.position==="data")?.value,ce="data"in u?u.data||"":null,Ut=le||ce||null,ue=Ut?p.applyInputs(Ut,A,this.serializer,f):null,Lt={adapter:o,warp:l,chain:a,action:e,destination:C,args:k,value:se,transfers:pe,data:ue,resolvedInputs:A};return this.cache.set(ht.WarpExecutable(this.config.env,l.meta?.hash||"",e),Lt.resolvedInputs,Ot.OneWeek),Lt}async getChainInfoForWarp(t,e){if(t.chain)return m(t.chain,this.adapters).chainInfo;if(e){let i=await this.tryGetChainFromInputs(t,e);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,e){let n=t.inputs||[];return e.map((i,s)=>{let a=n[s];return!a||i.includes(c.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,e,n,i){let s=e.inputs||[],a=await Promise.all(n.map(p=>this.preprocessInput(t,p))),o=(p,l)=>{if(p.source==="query"){let u=this.url.searchParams.get(p.name);return u?this.serializer.nativeToString(p.type,u):null}else if(p.source===c.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(p.source==="hidden"){if(p.default===void 0)return null;let u=i?i.applyInputs(String(p.default),[],this.serializer):String(p.default);return this.serializer.nativeToString(p.type,u)}else return a[l]||null};return s.map((p,l)=>{let u=o(p,l),d=p.default!==void 0?i?i.applyInputs(String(p.default),[],this.serializer):String(p.default):void 0;return{input:p,value:u||(d!==void 0?this.serializer.nativeToString(p.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,s]=i.input.modifier.split(":");if(isNaN(Number(s))){let a=Number(t.find(l=>l.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let p=K(o,+a);e.push({...i,value:`${i.input.type}:${p}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=K(a,+s);e.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let s=i.input.modifier.substring(c.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let o=this.buildInputContext(t,n,i),p=await a.run(s,o);if(p==null)e.push(i);else{let l=this.serializer.nativeToString(i.input.type,p);e.push({...i,value:l})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let s=0;s<e;s++){let a=t[s];if(!a.value)continue;let o=a.input.as||a.input.name,[,p]=this.serializer.stringToNative(a.value);if(i[o]=p,a.input.type==="asset"&&typeof p=="object"&&p!==null){let l=p;"identifier"in l&&"amount"in l&&(i[`${o}.token`]=String(l.identifier),i[`${o}.amount`]=String(l.amount),i[`${o}.identifier`]=String(l.identifier))}}if(n&&n.value){let s=n.input.as||n.input.name,[,a]=this.serializer.stringToNative(n.value);if(i[s]=a,n.input.type==="asset"&&typeof a=="object"&&a!==null){let o=a;"identifier"in o&&"amount"in o&&(i[`${s}.token`]=String(o.identifier),i[`${s}.amount`]=String(o.amount),i[`${s}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=dt(e),s=m(t,this.adapters);if(n==="asset"){let[a,o,p]=i.split(c.ArgCompositeSeparator);if(p)return e;let l=await s.dataLoader.getAsset(a);if(!l)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof l.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=K(o,l.decimals);return Nt({...l,amount:u})}else return e}catch(n){throw x.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[o,p]=this.serializer.stringToNative(a),l=p;if(!l||typeof l!="object"||!("identifier"in l)||!("amount"in l))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,d=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",l.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",l.amount)})}else if(s.position.startsWith("arg:")){let o=Number(s.position.split(":")[1])-1;i.push({index:o,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;n.length<=s;)n.push(void 0);n[s]=a}),n.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(p=>p.inputs?.some(l=>l.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(p=>p.position==="chain");if(i===-1||i===void 0)return null;let s=e[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return m(a,this.adapters).chainInfo}};var it=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new M(t,e)}async execute(t,e,n={}){let i=[],s=null,a=[],o=[],{action:p,index:l}=$(t);for(let u=1;u<=t.actions.length;u++){let d=P(t,u);if(!ct(d,t))continue;let{tx:h,chain:W,immediateExecution:y,executable:f}=await this.executeAction(t,u,e,n);h&&i.push(h),W&&(s=W),y&&a.push(y),f&&u===l+1&&f.resolvedInputs&&(o=B(f.resolvedInputs))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:o}}async executeAction(t,e,n,i={}){let s=P(t,e);if(s.type==="link")return s.when&&!await this.evaluateWhenCondition(t,s,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let l=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(l):mt.open(l,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});let a=await this.factory.createExecutable(t,e,n,i);if(s.when&&!await this.evaluateWhenCondition(t,s,n,i,a.resolvedInputs,a.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(s.type==="collect"){let l=await this.executeCollect(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(l.output._DATA),result:l}),{tx:null,chain:null,immediateExecution:null,executable:a})}if(s.type==="mcp"){let l=await this.executeMcp(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(l.output._DATA),result:l}),{tx:null,chain:null,immediateExecution:l,executable:a})}let o=m(a.chain.name,this.adapters);if(s.type==="query"){let l=await o.executor.executeQuery(a);return l.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:a.chain,execution:l,tx:null})):this.handlers?.onError?.({message:JSON.stringify(l.output._DATA),result:l}),{tx:null,chain:a.chain,immediateExecution:l,executable:a}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=m(n.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,o)=>{if(!ct(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let p=e[o],l=o+1;if(!p){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,l),h={status:"error",warp:t,action:l,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${l} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,l,p);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:l,chain:n,execution:u,tx:p})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else{let a=s.find(o=>o.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s)}`,result:a}))}}async executeCollect(t,e){let n=S(this.config,t.chain.name),i=P(t.warp,t.action),s=this.factory.getSerializer(),a=Z(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,a,e);let{values:o,output:p}=await Y(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,n,"unhandled",o,p)}async doHttpRequest(t,e,n,i,s){let a=new T(this.config,m(t.chain.name,this.adapters),this.adapters),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!n)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:d,nonce:h,expiresAt:W}=await ft(n,`${t.chain.name}-adapter`),y=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:d,chain:t.chain}));if(y){let f=gt(n,y,h,W);Object.entries(f).forEach(([v,A])=>o.set(v,A))}}e.headers&&Object.entries(e.headers).forEach(([d,h])=>{let W=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(d,W)});let p=e.method||"GET",l=p==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(e.url,t.resolvedInputs,this.factory.getSerializer());x.debug("WarpExecutor: Executing HTTP collect",{url:u,method:p,headers:o,body:l});try{let h=await fetch(u,{method:p,headers:o,body:l});x.debug("Collect response status",{status:h.status}),h.status===402&&(h=await Bt(h,u,p,l,this.adapters));let W=await h.json();x.debug("Collect response content",{content:W});let{values:y,output:f}=await Y(t.warp,W,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),h.ok?"success":"error",y,f,W)}catch(d){x.error("WarpActionExecutor: Error executing collect",d);let h=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:d},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=S(this.config,t.chain.name),i=P(t.warp,t.action);if(!i.destination){let W=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}let s,a;try{s=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,a=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let y=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:y}}let o=this.factory.getSerializer(),p=new T(this.config,m(t.chain.name,this.adapters),this.adapters),l=i.destination,u=p.applyInputs(l.url,t.resolvedInputs,this.factory.getSerializer()),d=p.applyInputs(l.tool,t.resolvedInputs,this.factory.getSerializer()),h={};l.headers&&Object.entries(l.headers).forEach(([W,y])=>{let f=p.applyInputs(y,t.resolvedInputs,this.factory.getSerializer());h[W]=f}),x.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let W=new a(new URL(u),{requestInit:{headers:h}}),y=new s({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(W);let f={};t.resolvedInputs.forEach(({input:C,value:k})=>{if(k&&C.position&&typeof C.position=="string"&&C.position.startsWith("payload:")){let q=C.position.replace("payload:",""),[b,V]=o.stringToNative(k);if(b==="string")f[q]=String(V);else if(b==="bool")f[q]=!!V;else if(b==="uint8"||b==="uint16"||b==="uint32"||b==="uint64"||b==="uint128"||b==="uint256"||b==="biguint"){let J=Number(V);f[q]=(Number.isInteger(J),J)}else f[q]=V}}),e&&Object.assign(f,e);let v=await y.callTool({name:d,arguments:f});await y.close();let A;if(v.content&&v.content.length>0){let C=v.content[0];if(C.type==="text")try{A=JSON.parse(C.text)}catch{A=C.text}else C.type,A=C}else A=v;let{values:E,output:N}=await Y(t.warp,A,t.action,t.resolvedInputs,o,this.config);return this.buildCollectResult(t,n,"success",E,N,v)}catch(W){x.error("WarpExecutor: Error executing MCP",W);let y=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:W},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:y}}}buildCollectResult(t,e,n,i,s,a){let o=Pt(this.config,this.adapters,t.warp,t.action,s),p=B(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:St(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:p}}async callHandler(t){if(t)return await t()}async evaluateWhenCondition(t,e,n,i,s,a){if(!e.when)return!0;let o=a?{name:a}:await this.factory.getChainInfoForWarp(t,n),p=m(o.name,this.adapters),l=new T(this.config,p,this.adapters),{action:u}=$(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(o.name,u,d,l),W=await this.factory.getModifiedInputs(h),y;if(s)y=s;else{let A=await this.factory.getResolvedInputs(o.name,e,this.factory.getStringTypedInputs(e,n),l);y=await this.factory.getModifiedInputs(A)}let f=l.buildInputBag(y,this.factory.getSerializer(),W),v=xt(e.when,f);return Ct(v)}};var at=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw x.error("WarpIndex: Error searching for warps: ",i),i}}};var st=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!G(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),o=a.length>0,p=a.map(l=>({url:l.url,warp:l.warp}));return{match:o,output:p}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(c.HttpProtocolPrefix)?G(t):R(t);if(!i)return n;try{let{type:s,identifierBase:a}=i,o=null,p=null,l=null,u=m(i.chain,this.adapters),d=t.startsWith(c.HttpProtocolPrefix)?wt(t):It(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,e);let f=await u.registry.getInfoByHash(a,e);p=f.registryInfo,l=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(a,e);p=f.registryInfo,l=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(o&&o.meta&&(Wr(o,u.chainInfo.name,p,i.identifier),o.meta.query=d),!o)return n;let h=o.chain||u.chainInfo.name,W=m(h,this.adapters),y=await new T(this.config,W,this.adapters).apply(o);return{match:!0,url:t,warp:y,chain:h,registryInfo:p,brand:l}}catch(s){return x.error("Error detecting warp link",s),n}}},Wr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?ut(t,"alias",e.alias):ut(t,"hash",e?.hash??n))};var Ft=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new it(this.config,this.chains,t)}async detectWarp(t,e){return new st(this.config,this.chains).detect(t,e)}async executeWarp(t,e,n,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),o=s?t:null;if(!o&&a){let y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await y.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let p=this.createExecutor(n),{txs:l,chain:u,immediateExecutions:d,resolvedInputs:h}=await p.execute(o,e,{queries:i.queries});return{txs:l,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await p.evaluateOutput(o,y)},resolvedInputs:h}}async createInscriptionTransaction(t,e){return await m(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return m(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=R(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return m(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return m(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async a=>i.getAction(a,n)))).filter(a=>a!==null)}getExplorer(t){return m(t,this.chains).explorer}getOutput(t){return m(t,this.chains).output}async getRegistry(t){let e=m(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return m(t,this.chains).dataLoader}getWallet(t){return m(t,this.chains).wallet}get factory(){return new M(this.config,this.chains)}get index(){return new at(this.config)}get linkBuilder(){return new j(this.config,this.chains)}createBuilder(t){return m(t,this.chains).builder()}createAbiBuilder(t){return m(t,this.chains).abiBuilder()}createBrandBuilder(t){return m(t,this.chains).brandBuilder()}createSerializer(t){return m(t,this.chains).serializer}resolveText(t){return Q(t,this.config)}};var Ht=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
|
|
1
|
+
"use strict";var We=Object.create;var pt=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var xe=Object.getPrototypeOf,Ce=Object.prototype.hasOwnProperty;var we=(r,t)=>{for(var e in t)pt(r,e,{get:t[e],enumerable:!0})},zt=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ve(t))!Ce.call(r,i)&&i!==e&&pt(r,i,{get:()=>t[i],enumerable:!(n=Ae(t,i))||n.enumerable});return r};var k=(r,t,e)=>(e=r!=null?We(xe(r)):{},zt(t||!r||!r.__esModule?pt(e,"default",{value:r,enumerable:!0}):e,r)),Ie=r=>zt(pt({},"__esModule",{value:!0}),r);var Pr={};we(Pr,{BrowserCryptoProvider:()=>lt,CacheTtl:()=>Vt,NodeCryptoProvider:()=>ct,WARP_LANGUAGES:()=>Oe,WarpBrandBuilder:()=>Ht,WarpBuilder:()=>Ot,WarpCache:()=>nt,WarpCacheKey:()=>Wt,WarpChainName:()=>kt,WarpClient:()=>Lt,WarpConfig:()=>O,WarpConstants:()=>c,WarpExecutor:()=>at,WarpFactory:()=>M,WarpIndex:()=>st,WarpInputTypes:()=>g,WarpInterpolator:()=>T,WarpLinkBuilder:()=>L,WarpLinkDetecter:()=>ot,WarpLogger:()=>C,WarpProtocolVersions:()=>U,WarpSerializer:()=>w,WarpTypeRegistry:()=>jt,WarpValidator:()=>tt,address:()=>gr,applyOutputToMessages:()=>gt,asset:()=>$t,biguint:()=>dr,bool:()=>fr,buildMappedOutput:()=>Y,buildNestedPayload:()=>Qt,bytesToBase64:()=>Be,bytesToHex:()=>Gt,cleanWarpIdentifier:()=>X,createAuthHeaders:()=>yt,createAuthMessage:()=>mt,createCryptoProvider:()=>$e,createDefaultWalletProvider:()=>ir,createHttpAuthHeaders:()=>_e,createSignableMessage:()=>Zt,createWarpI18nText:()=>Fe,createWarpIdentifier:()=>dt,evaluateOutputCommon:()=>Xt,evaluateWhenCondition:()=>St,extractCollectOutput:()=>Z,extractIdentifierInfoFromUrl:()=>G,extractQueryStringFromIdentifier:()=>bt,extractQueryStringFromUrl:()=>Pt,extractResolvedInputValues:()=>B,extractWarpSecrets:()=>He,findWarpAdapterForChain:()=>A,getCryptoProvider:()=>vt,getEventNameFromWarp:()=>Pe,getLatestProtocolIdentifier:()=>J,getNextInfo:()=>ht,getProviderConfig:()=>Ge,getRandomBytes:()=>xt,getRandomHex:()=>Ct,getWalletFromConfigOrFail:()=>Ke,getWarpActionByIndex:()=>b,getWarpBrandLogoUrl:()=>be,getWarpChainAssetLogoUrl:()=>Te,getWarpChainInfoLogoUrl:()=>Ee,getWarpInfoFromIdentifier:()=>$,getWarpPrimaryAction:()=>N,getWarpWalletAddress:()=>te,getWarpWalletAddressFromConfig:()=>S,getWarpWalletExternalId:()=>ne,getWarpWalletExternalIdFromConfig:()=>ie,getWarpWalletExternalIdFromConfigOrFail:()=>Ze,getWarpWalletMnemonic:()=>re,getWarpWalletMnemonicFromConfig:()=>Ye,getWarpWalletPrivateKey:()=>ee,getWarpWalletPrivateKeyFromConfig:()=>Xe,handleX402Payment:()=>Nt,hasInputPrefix:()=>je,hex:()=>hr,initializeWalletCache:()=>nr,isEqualWarpIdentifier:()=>Ue,isWarpActionAutoExecute:()=>ut,isWarpI18nText:()=>Ve,isWarpWalletReadOnly:()=>tr,mergeNestedPayload:()=>Et,normalizeAndValidateMnemonic:()=>rr,normalizeMnemonic:()=>ae,option:()=>mr,parseOutputOutIndex:()=>Yt,parseSignedMessage:()=>Qe,replacePlaceholders:()=>V,replacePlaceholdersInWhenExpression:()=>It,resolveWarpText:()=>K,safeWindow:()=>At,setCryptoProvider:()=>Re,setWarpWalletInConfig:()=>er,shiftBigintBy:()=>Q,splitInput:()=>ft,string:()=>or,struct:()=>Wr,testCryptoAvailability:()=>Ne,toInputPayloadValue:()=>Kt,toPreviewText:()=>wt,tuple:()=>yr,uint16:()=>lr,uint32:()=>cr,uint64:()=>ur,uint8:()=>pr,validateMnemonicLength:()=>se,validateSignedMessage:()=>Je,vector:()=>Ar,withAdapterFallback:()=>Se});module.exports=Ie(Pr);var kt=(d=>(d.Multiversx="multiversx",d.Vibechain="vibechain",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(kt||{}),c={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>r.config.user?.wallets?.[r.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},g={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},At=typeof window<"u"?window:{open:()=>{}};var U={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},O={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${U.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${U.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",c.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var Se=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Pe=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=c.Alerts.TriggerEventPrefix+c.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var be=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Te=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},Ee=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var lt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},ct=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},D=null;function vt(){if(D)return D;if(typeof window<"u"&&window.crypto)return D=new lt,D;if(typeof process<"u"&&process.versions?.node)return D=new ct,D;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Re(r){D=r}async function xt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||vt()).getRandomBytes(r)}function Gt(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function Be(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function Ct(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await xt(r/2,t);return Gt(e)}async function Ne(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await xt(16),r.randomBytes=!0}catch{}return r}function $e(){return vt()}var He=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${c.Vars.Env}:`)).map(t=>{let e=t.replace(`${c.Vars.Env}:`,"").trim(),[n,i]=e.split(c.ArgCompositeSeparator);return{key:n,description:i||null}});var A=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},J=r=>{if(r==="warp")return`warp:${U.Warp}`;if(r==="brand")return`brand:${U.Brand}`;if(r==="abi")return`abi:${U.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},b=(r,t)=>r?.actions[t-1],N=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(s=>s.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(s=>e.includes(s.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},ut=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=N(t);return r===e}return!0},Q=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),s=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(s,"0"));if(t<0){let a=n+i;if(s>=a.length)return 0n;let p=a.slice(0,-s)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},wt=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},V=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>t[n]||""),It=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),St=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var Oe={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},K=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},Ve=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Fe=r=>r;var X=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,Ue=(r,t)=>!r||!t?!1:X(r)===X(t),dt=(r,t,e)=>{let n=X(e);return t===c.IdentifierType.Alias?c.IdentifierAliasMarker+r+c.IdentifierParamSeparator+n:r+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+n},$=r=>{let t=decodeURIComponent(r).trim(),e=X(t),n=e.split("?")[0],i=_t(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Hash,identifier:e,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,p]=i;if(a===c.IdentifierType.Alias||a===c.IdentifierType.Hash){let l=e.includes("?")?p+e.substring(e.indexOf("?")):p;return{chain:s,type:a,identifier:l,identifierBase:p}}}if(i.length===2){let[s,a]=i;if(s===c.IdentifierType.Alias||s===c.IdentifierType.Hash){let p=e.includes("?")?a+e.substring(e.indexOf("?")):a;return{chain:c.IdentifierChainDefault,type:s,identifier:p,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==c.IdentifierType.Alias&&s!==c.IdentifierType.Hash){let p=e.includes("?")?a+e.substring(e.indexOf("?")):a,l=De(a,s)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:s,type:l,identifier:p,identifierBase:a}}}return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Alias,identifier:e,identifierBase:n}},G=r=>{let t=new URL(r),n=t.searchParams.get(c.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return $(i)},De=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Le=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},_t=r=>{let t=Le(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),s=r.substring(n+e.length),a=_t(s);return[i,...a]},Pt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},bt=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null};var ft=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},je=r=>{let t=new Set(Object.values(g));if(!r.includes(c.ArgParamsSeparator))return!1;let e=ft(r)[0];return t.has(e)};var gt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,s])=>{let a=K(s,e);return[i,V(a,t)]});return Object.fromEntries(n)};var Jt=k(require("qr-code-styling"),1);var L=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!G(t):!1}build(t,e,n){let i=this.config.clientUrl||O.DefaultClientUrl(this.config.env),s=A(t,this.adapters),a=e===c.IdentifierType.Alias?n:e+c.IdentifierParamSeparator+n,p=s.chainInfo.name+c.IdentifierParamSeparator+a,l=encodeURIComponent(p);return O.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${c.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=$(t);if(!e)return null;let n=A(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,s="white",a="black",p="#23F7DD"){let l=A(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Jt.default({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Me="https://",ht=(r,t,e,n,i)=>{let s=e.actions?.[n-1]?.next||e.next||null;if(!s)return null;if(s.startsWith(Me))return[{identifier:null,url:s}];let[a,p]=s.split("?");if(!p){let f=V(a,{...e.vars,...i});return[{identifier:f,url:Tt(t,f,r)}]}let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let f=V(p,{...e.vars,...i}),y=f?`${a}?${f}`:a;return[{identifier:y,url:Tt(t,y,r)}]}let o=l[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let m=l.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let y=f.match(/\[\](\.[^}]+)?}}/),v=y&&y[1]||"";return{placeholder:f,field:v?v.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let y=p;for(let{regex:P,field:E}of m){let x=E?qe(f,E):f;if(x==null)return null;y=y.replace(P,x)}if(y.includes("{{")||y.includes("}}"))return null;let v=y?`${a}?${y}`:a;return{identifier:v,url:Tt(t,v,r)}}).filter(f=>f!==null)},Tt=(r,t,e)=>{let[n,i]=t.split("?"),s=$(n)||{chain:c.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},a=A(s.chain,r);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let p=new L(e,r).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((o,u)=>l.searchParams.set(u,o)),l.toString().replace(/\/\?/,"?")},qe=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var j=class j{static debug(...t){j.isTestEnv||console.debug(...t)}static info(...t){j.isTestEnv||console.info(...t)}static warn(...t){j.isTestEnv||console.warn(...t)}static error(...t){j.isTestEnv||console.error(...t)}};j.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=j;function Qt(r,t,e){return r.startsWith(c.Position.Payload)?r.slice(c.Position.Payload.length).split(".").reduceRight((n,i,s,a)=>({[i]:s===a.length-1?{[t]:e}:n}),{}):{[t]:e}}function Et(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=Et(e[n],t[n]):e[n]=t[n]}),e}function Kt(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function B(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function Y(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,s=Kt(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let a=Qt(n.input.position,i,s);e=Et(e,a)}else e[i]=s}),e}var Z=async(r,t,e,n,i,s)=>{let a=[],p=[],l={};for(let[u,d]of Object.entries(r.output||{})){if(d.startsWith(c.Transform.Prefix))continue;let h=Yt(d);if(h!==null&&h!==e){l[u]=null;continue}let[m,...W]=d.split("."),f=(y,v)=>v.reduce((P,E)=>P&&P[E]!==void 0?P[E]:null,y);if(m==="out"||m.startsWith("out[")){let y=W.length===0?t?.data||t:f(t,W);a.push(String(y)),p.push(y),l[u]=y}else l[u]=d}let o=Y(n,i);return{values:{string:a,native:p,mapped:o},output:await Xt(r,l,e,n,i,s)}},Xt=async(r,t,e,n,i,s)=>{if(!r.output)return t;let a={...t};return a=ze(a,r,e,n,i),a=await ke(r,a,s.transform?.runner||null),a},ze=(r,t,e,n,i)=>{let s={...r},a=b(t,e)?.inputs||[];for(let[p,l]of Object.entries(s))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],u=a.findIndex(h=>h.as===o||h.name===o),d=u!==-1?n[u]?.value:null;s[p]=d?i.stringToNative(d)[1]:null}return s},ke=async(r,t,e)=>{if(!r.output)return t;let n={...t},i=Object.entries(r.output).filter(([,s])=>s.startsWith(c.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(c.Transform.Prefix.length)}));if(i.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:a}of i)try{n[s]=await e.run(a,n)}catch(p){C.error(`Transform error for output '${s}':`,p),n[s]=null}return n},Yt=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var Ge=(r,t,e,n)=>{let i=r.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:n}};async function Zt(r,t,e,n=5){let i=await Ct(64,e),s=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function mt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Zt(r,i,e,5)}function yt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function _e(r,t,e,n){let{message:i,nonce:s,expiresAt:a}=await mt(r,e,n),p=await t(i);return yt(r,p,s,a)}function Je(r){let t=new Date(r).getTime();return Date.now()<t}function Qe(r){try{let t=JSON.parse(r);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var Ke=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},te=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>te(r.user?.wallets?.[t]||null),ee=r=>r?typeof r=="string"?r:r.privateKey||null:null,re=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ne=r=>r?typeof r=="string"?r:r.externalId||null:null,Xe=(r,t)=>ee(r.user?.wallets?.[t]||null)?.trim()||null,Ye=(r,t)=>re(r.user?.wallets?.[t]||null)?.trim()||null,ie=(r,t)=>ne(r.user?.wallets?.[t]||null)?.trim()||null,Ze=(r,t)=>{let e=ie(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},tr=r=>typeof r=="string",er=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},ae=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},se=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},rr=(r,t=24)=>{let e=ae(r);return se(e,t),e};async function nr(r){let t={address:null,publicKey:null};if(!r)return t;try{t.address=await r.getAddress()}catch{}try{t.publicKey=await r.getPublicKey()}catch{}return t}function ir(r,t,e){return null}var Rt=require("@x402/core/client"),Bt=require("@x402/core/http");async function Nt(r,t,e,n,i){let s=await ar(r,i);if(!s)return r;let a=new Headers;n&&a.set("Content-Type","application/json"),a.set("Accept","application/json"),Object.entries(s).forEach(([l,o])=>{a.set(l,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:a,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var ar=async(r,t)=>{let e=await sr(r),i=new Bt.x402HTTPClient(new Rt.x402Client).getPaymentRequiredResponse(s=>r.headers.get(s),e);if(!i?.accepts?.length)return null;for(let s of t)if(s.wallet.registerX402Handlers)try{let a=new Rt.x402Client,p=await s.wallet.registerX402Handlers(a),l=i.accepts.find(h=>h?.network&&p[h.network]);if(!l?.network)continue;p[l.network]();let o=new Bt.x402HTTPClient(a),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${s.chainInfo.name} adapter using ${l.network} scheme`),d}catch{continue}return null},sr=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===g.Tuple&&Array.isArray(e)){if(e.length===0)return t+c.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e.map(a=>this.getTypeAndValue(a)),i=n.map(([a])=>a),s=n.map(([,a])=>a);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===g.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,s=Object.keys(n).filter(p=>p!=="_name");if(s.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let a=s.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${c.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}if(t===g.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${c.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e[0],i=n.indexOf(c.ArgParamsSeparator),s=n.substring(0,i),a=e.map(l=>{let o=l.indexOf(c.ArgParamsSeparator),u=l.substring(o+1);return s.startsWith(g.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=s.startsWith(g.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+s+c.ArgParamsSeparator+a.join(p)}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===g.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?g.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):g.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t+c.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(c.ArgParamsSeparator),n=e[0],i=e.slice(1).join(c.ArgParamsSeparator);if(n==="null")return[n,null];if(n===g.Option){let[s,a]=i.split(c.ArgParamsSeparator);return[g.Option+c.ArgParamsSeparator+s,a||null]}if(n===g.Vector){let s=i.indexOf(c.ArgParamsSeparator),a=i.substring(0,s),p=i.substring(s+1),l=a.startsWith(g.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(a+c.ArgParamsSeparator+d)[1]);return[g.Vector+c.ArgParamsSeparator+a,u]}else if(n.startsWith(g.Tuple)){let s=n.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),p=i.split(c.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${s[o]}${c.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(g.Struct)){let s=n.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:s[1]};return i&&i.split(c.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${h}`)[1]}}),[n,p]}else{if(n===g.String)return[n,i];if(n===g.Uint8||n===g.Uint16||n===g.Uint32)return[n,Number(i)];if(n===g.Uint64||n===g.Uint128||n===g.Uint256||n===g.Biguint)return[n,BigInt(i||0)];if(n===g.Bool)return[n,i==="true"];if(n===g.Address)return[n,i];if(n===g.Hex)return[n,i];if(n===g.Asset){let[s,a]=i.split(c.ArgCompositeSeparator),p={identifier:s,amount:BigInt(a)};return[n,p]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(n);if(s){let p=s.stringToNative(i);return[n,p]}let a=this.typeRegistry.resolveType(n);if(a!==n){let[p,l]=this.stringToNative(`${a}:${i}`);return[n,l]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(c.ArgParamsSeparator)){let[e,n]=t.split(c.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[g.Uint32,t]:typeof t=="bigint"?[g.Uint64,t]:typeof t=="boolean"?[g.Bool,t]:[typeof t,t]}};var or=r=>new w().nativeToString(g.String,r),pr=r=>new w().nativeToString(g.Uint8,r),lr=r=>new w().nativeToString(g.Uint16,r),cr=r=>new w().nativeToString(g.Uint32,r),ur=r=>new w().nativeToString(g.Uint64,r),dr=r=>new w().nativeToString(g.Biguint,r),fr=r=>new w().nativeToString(g.Bool,r),gr=r=>new w().nativeToString(g.Address,r),$t=r=>new w().nativeToString(g.Asset,r),hr=r=>new w().nativeToString(g.Hex,r),mr=(r,t)=>{if(t===null)return g.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),s=e.substring(n+1);return g.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+s},yr=(...r)=>new w().nativeToString(g.Tuple,r),Wr=r=>new w().nativeToString(g.Struct,r),Ar=r=>new w().nativeToString(g.Vector,r);var oe=k(require("ajv"),1);var Ht=class{constructor(t){this.pendingBrand={protocol:J("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||O.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),s=new oe.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var pe=k(require("ajv"),1);var tt=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=N(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&e.push(`${s} name '${a}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(a=>a.type==="contract"),n=t.actions.some(a=>a.type==="query");if(!e&&!n)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||O.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),s=new pe.default({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var Ot=class{constructor(t){this.config=t;this.pendingWarp={protocol:J("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return wt(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new tt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
+
`))}};var et=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,xr);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,vr))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}},le=new w,vr=(r,t)=>typeof t=="bigint"?le.nativeToString("biguint",t):t,xr=(r,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?le.stringToNative(t)[1]:t;var F=class F{get(t){let e=F.cache.get(t);return e?Date.now()>e.expiresAt?(F.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;F.cache.set(t,{value:e,expiresAt:i})}forget(t){F.cache.delete(t)}clear(){F.cache.clear()}};F.cache=new Map;var rt=F;var Vt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Wt={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`},nt=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new et:t==="memory"?new rt:typeof window<"u"&&window.localStorage?new et:new rt}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var it={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Ft={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Ut=(r,t,e)=>{let n=r.find(s=>s.input.as===t||s.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},Dt=r=>{try{return JSON.parse(r)}catch{return null}},Cr=async(r,t,e,n,i,s)=>{let a=new Headers;if(a.set("Content-Type","application/json"),a.set("Accept","application/json"),s&&n){let{message:l,nonce:o,expiresAt:u}=await mt(n,`${e.chain.name}-adapter`),d=await s({message:l,chain:e.chain});d&&Object.entries(yt(n,d,o,u)).forEach(([h,m])=>a.set(h,m))}let p=Ut(e.resolvedInputs,it.Headers,i);if(p){let l=Dt(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,u])=>typeof u=="string"&&a.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{a.set(l,r.applyInputs(o,e.resolvedInputs,i))});return a},wr=(r,t,e,n,i)=>{let s=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Ft.Get){let a=Ut(e.resolvedInputs,it.Queries,i);if(a){let p=Dt(a);if(p&&typeof p=="object"){let l=new URL(s);Object.entries(p).forEach(([o,u])=>u!=null&&l.searchParams.set(o,String(u))),s=l.toString()}}}return s},Ir=(r,t,e,n,i)=>{if(r===Ft.Get)return;let s=Ut(t.resolvedInputs,it.Payload,n);if(s&&Dt(s)!==null)return s;let{[it.Payload]:a,[it.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},ce=async(r,t,e,n,i,s,a,p)=>{let l=t.method||Ft.Get,o=await Cr(r,t,e,n,s,p),u=wr(r,t,e,l,s),d=Ir(l,e,i,s,a);return{url:u,method:l,headers:o,body:d}};var T=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);return await this.applyGlobals(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),s=(a,p)=>{i=i.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([a,p])=>{if(typeof p!="string")s(a,p);else if(p.startsWith(c.Vars.Query+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Query.length+1),[o,u]=l.split(c.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,m=e.queries?.[o]||null||d;m&&s(a,m)}else if(p.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Env.length+1),[o,u]=l.split(c.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h&&s(a,h)}else p===c.Source.UserWallet&&n?s(a,n):s(a,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(e,n,i);return V(s,a)}applyGlobalsToText(t){if(!Object.values(c.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)||t.includes(`{{${a}:`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(c.Globals).forEach(a=>{let p=a.Accessor(i);p!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),p.toString())),s=this.replacePlaceholdersWithChain(s,a.Placeholder,i,a.Accessor)}),s}replacePlaceholdersWithChain(t,e,n,i){let s=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(s,(a,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return a;try{let o=A(l,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():a}catch{return a}})}buildInputBag(t,e,n){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,p]=e.stringToNative(s.value);i[a]=String(p)}),n&&n.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,p]=e.stringToNative(s.value);if(i[`primary.${a}`]=String(p),s.input.type==="asset"&&typeof s.input.position=="object"){let l=p;l&&typeof l=="object"&&"identifier"in l&&"amount"in l&&(i[`primary.${a}.token`]=String(l.identifier),i[`primary.${a}.amount`]=String(l.amount))}}),i}};var M=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new nt(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(Wt.WarpExecutable(t,e||"",n))||[];return B(i)}async createExecutable(t,e,n,i={}){let s=b(t,e);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,n),p=A(a.name,this.adapters),l=new T(this.config,p,this.adapters),o=await l.apply(t,i),u=b(o,e),{action:d,index:h}=N(o),m=this.getStringTypedInputs(d,n),W=await this.getResolvedInputs(a.name,d,m,l),f=await this.getModifiedInputs(W),y=[],v=[];h===e-1?(y=W,v=f):this.requiresPayloadInputs(u)&&(y=await this.resolveActionInputs(a.name,u,n,l),v=await this.getModifiedInputs(y));let P=v.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,E=this.getDestinationFromAction(u),x=P?this.serializer.stringToNative(P)[1]:E;if(x&&(x=l.applyInputs(x,v,this.serializer,f)),!x&&s.type!=="collect"&&s.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let q=this.getPreparedArgs(u,v);q=q.map(I=>l.applyInputs(I,v,this.serializer,f));let z=v.find(I=>I.input.position==="value")?.value||null,R="value"in u?u.value:null,H=z?.split(c.ArgParamsSeparator)[1]||R||"0",_=l.applyInputs(H,v,this.serializer,f),ue=BigInt(_),de=v.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),fe=[...("transfers"in u?u.transfers:[])||[],...de||[]].map(I=>{let ye=l.applyInputs(I,v,this.serializer,f);return this.serializer.stringToNative(ye)[1]}),ge=v.find(I=>I.input.position==="data")?.value,he="data"in u?u.data||"":null,Mt=ge||he||null,me=Mt?l.applyInputs(Mt,v,this.serializer,f):null,qt={adapter:p,warp:o,chain:a,action:e,destination:x,args:q,value:ue,transfers:fe,data:me,resolvedInputs:v};return this.cache.set(Wt.WarpExecutable(this.config.env,o.meta?.hash||"",e),qt.resolvedInputs,Vt.OneWeek),qt}async getChainInfoForWarp(t,e){if(t.chain)return A(t.chain,this.adapters).chainInfo;if(e){let i=await this.tryGetChainFromInputs(t,e);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,e){let n=t.inputs||[];return e.map((i,s)=>{let a=n[s];return!a||i.includes(c.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,e,n,i){let s=e.inputs||[],a=await Promise.all(n.map(l=>this.preprocessInput(t,l))),p=(l,o)=>{if(l.source==="query"){let u=this.url.searchParams.get(l.name);return u?this.serializer.nativeToString(l.type,u):null}else if(l.source===c.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(l.source==="hidden"){if(l.default===void 0)return null;let u=i?i.applyInputs(String(l.default),[],this.serializer):String(l.default);return this.serializer.nativeToString(l.type,u)}else return a[o]||null};return s.map((l,o)=>{let u=p(l,o),d=l.default!==void 0?i?i.applyInputs(String(l.default),[],this.serializer):String(l.default):void 0;return{input:l,value:u||(d!==void 0?this.serializer.nativeToString(l.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,s]=i.input.modifier.split(":");if(isNaN(Number(s))){let a=Number(t.find(o=>o.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=Q(p,+a);e.push({...i,value:`${i.input.type}:${l}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let p=Q(a,+s);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let s=i.input.modifier.substring(c.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=this.buildInputContext(t,n,i),l=await a.run(s,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let s=0;s<e;s++){let a=t[s];if(!a.value)continue;let p=a.input.as||a.input.name,[,l]=this.serializer.stringToNative(a.value);if(i[p]=l,a.input.type==="asset"&&typeof l=="object"&&l!==null){let o=l;"identifier"in o&&"amount"in o&&(i[`${p}.token`]=String(o.identifier),i[`${p}.amount`]=String(o.amount),i[`${p}.identifier`]=String(o.identifier))}}if(n&&n.value){let s=n.input.as||n.input.name,[,a]=this.serializer.stringToNative(n.value);if(i[s]=a,n.input.type==="asset"&&typeof a=="object"&&a!==null){let p=a;"identifier"in p&&"amount"in p&&(i[`${s}.token`]=String(p.identifier),i[`${s}.amount`]=String(p.amount),i[`${s}.identifier`]=String(p.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=ft(e),s=A(t,this.adapters);if(n==="asset"){let[a,p,l]=i.split(c.ArgCompositeSeparator);if(l)return e;let o=await s.dataLoader.getAsset(a);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=Q(p,o.decimals);return $t({...o,amount:u})}else return e}catch(n){throw C.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[p,l]=this.serializer.stringToNative(a),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,d=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(s.position.startsWith("arg:")){let p=Number(s.position.split(":")[1])-1;i.push({index:p,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;n.length<=s;)n.push(void 0);n[s]=a}),n.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let s=e[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return A(a,this.adapters).chainInfo}};var at=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new M(t,e)}async execute(t,e,n={}){let i=[],s=null,a=[],p=[],{action:l,index:o}=N(t);for(let u=1;u<=t.actions.length;u++){let d=b(t,u);if(!ut(d,t))continue;let{tx:h,chain:m,immediateExecution:W,executable:f}=await this.executeAction(t,u,e,n);h&&i.push(h),m&&(s=m),W&&a.push(W),f&&u===o+1&&f.resolvedInputs&&(p=B(f.resolvedInputs))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:p}}async executeAction(t,e,n,i={}){let s=b(t,e);if(s.type==="link")return s.when&&!await this.evaluateWhenCondition(t,s,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):At.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(s.type==="prompt"){let o=await this.executePrompt(t,s,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}let a=await this.factory.createExecutable(t,e,n,i);if(s.when&&!await this.evaluateWhenCondition(t,s,n,i,a.resolvedInputs,a.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(s.type==="collect"){let o=await this.executeCollect(a);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:a};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:a};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:a}}if(s.type==="mcp"){let o=await this.executeMcp(a);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:a};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:a};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:a}}}let p=A(a.chain.name,this.adapters);if(s.type==="query"){let o=await p.executor.executeQuery(a);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:a.chain,execution:o,tx:null}));else{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:a.chain,immediateExecution:o,executable:a}}return{tx:await p.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=A(n.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,p)=>{if(!ut(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,l);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else{let a=s.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s)}`,result:a}))}}async executeCollect(t,e){let n=S(this.config,t.chain.name),i=b(t.warp,t.action),s=this.factory.getSerializer(),a=Y(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,a,e);let{values:p,output:l}=await Z(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async doHttpRequest(t,e,n,i,s){let a=new T(this.config,A(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await ce(a,e,t,n,i,p,s,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:u,body:d});try{let m=await fetch(l,{method:o,headers:u,body:d});C.debug("Collect response status",{status:m.status}),m.status===402&&(m=await Nt(m,l,o,d,this.adapters));let W=await m.json();C.debug("Collect response content",{content:W});let{values:f,output:y}=await Z(t.warp,W,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),m.ok?"success":"error",f,y,W)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let m=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=S(this.config,t.chain.name),i=b(t.warp,t.action);if(!i.destination){let m=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let s,a;try{s=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,a=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let W=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}let p=this.factory.getSerializer(),l=new T(this.config,A(t.chain.name,this.adapters),this.adapters),o=i.destination,u=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([m,W])=>{let f=l.applyInputs(W,t.resolvedInputs,this.factory.getSerializer());h[m]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let m=new a(new URL(u),{requestInit:{headers:h}}),W=new s({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await W.connect(m);let f={};t.resolvedInputs.forEach(({input:x,value:q})=>{if(q&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let z=x.position.replace("payload:",""),[R,H]=p.stringToNative(q);if(R==="string")f[z]=String(H);else if(R==="bool")f[z]=!!H;else if(R==="uint8"||R==="uint16"||R==="uint32"||R==="uint64"||R==="uint128"||R==="uint256"||R==="biguint"){let _=Number(H);f[z]=(Number.isInteger(_),_)}else f[z]=H}}),e&&Object.assign(f,e);let y=await W.callTool({name:d,arguments:f});await W.close();let v;if(y.content&&y.content.length>0){let x=y.content[0];if(x.type==="text")try{v=JSON.parse(x.text)}catch{v=x.text}else x.type,v=x}else v=y;let{values:P,output:E}=await Z(t.warp,v,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",P,E,y)}catch(m){C.error("WarpExecutor: Error executing MCP",m);let W=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:m},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}}buildCollectResult(t,e,n,i,s,a){let p=ht(this.config,this.adapters,t.warp,t.action,s),l=B(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:a?{...s,_DATA:a}:s,messages:gt(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,s={}){try{let a=await this.factory.getChainInfoForWarp(t,i),p=A(a.name,this.adapters),l=new T(this.config,p,this.adapters),o=await l.apply(t,s),u=b(o,n),{action:d}=N(o),h=this.factory.getStringTypedInputs(d,i),m=await this.factory.getResolvedInputs(a.name,d,h,l),W=await this.factory.getModifiedInputs(m),f=W;if(e.inputs&&e.inputs.length>0){let E=this.factory.getStringTypedInputs(e,i),x=await this.factory.getResolvedInputs(a.name,e,E,l);f=await this.factory.getModifiedInputs(x)}let y=l.applyInputs(u.prompt,f,this.factory.getSerializer(),W),v=B(f),P=S(this.config,a.name);return{status:"success",warp:o,action:n,user:P,txHash:null,tx:null,next:ht(this.config,this.adapters,o,n,{prompt:y}),values:{string:[y],native:[y],mapped:{prompt:y}},output:{prompt:y},messages:gt(o,{prompt:y},this.config),destination:null,resolvedInputs:v}}catch(a){return C.error("WarpExecutor: Error executing prompt action",a),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:a},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,s,a){if(!e.when)return!0;let p=a?{name:a}:await this.factory.getChainInfoForWarp(t,n),l=A(p.name,this.adapters),o=new T(this.config,l,this.adapters),{action:u}=N(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(p.name,u,d,o),m=await this.factory.getModifiedInputs(h),W;if(s)W=s;else{let v=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o);W=await this.factory.getModifiedInputs(v)}let f=o.buildInputBag(W,this.factory.getSerializer(),m),y=It(e.when,f);return St(y)}};var st=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw C.error("WarpIndex: Error searching for warps: ",i),i}}};var ot=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!G(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),a=(await Promise.all(i)).filter(o=>o.match),p=a.length>0,l=a.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(c.HttpProtocolPrefix)?G(t):$(t);if(!i)return n;try{let{type:s,identifierBase:a}=i,p=null,l=null,o=null,u=A(i.chain,this.adapters),d=t.startsWith(c.HttpProtocolPrefix)?Pt(t):bt(i.identifier);if(s==="hash"){p=await u.builder().createFromTransactionHash(a,e);let f=await u.registry.getInfoByHash(a,e);l=f.registryInfo,o=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(a,e);l=f.registryInfo,o=f.brand,f.registryInfo&&(p=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(p&&p.meta&&(Sr(p,u.chainInfo.name,l,i.identifier),p.meta.query=d),!p)return n;let h=p.chain||u.chainInfo.name,m=A(h,this.adapters),W=await new T(this.config,m,this.adapters).apply(p);return{match:!0,url:t,warp:W,chain:h,registryInfo:l,brand:o}}catch(s){return C.error("Error detecting warp link",s),n}}},Sr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?dt(t,"alias",e.alias):dt(t,"hash",e?.hash??n))};var Lt=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new at(this.config,this.chains,t)}async detectWarp(t,e){return new ot(this.config,this.chains).detect(t,e)}async executeWarp(t,e,n,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),p=s?t:null;if(!p&&a){let W=await fetch(t);if(!W.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await W.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async W=>{await l.evaluateOutput(p,W)},resolvedInputs:h}}async createInscriptionTransaction(t,e){return await A(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return A(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=$(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return A(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return A(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async a=>i.getAction(a,n)))).filter(a=>a!==null)}getExplorer(t){return A(t,this.chains).explorer}getOutput(t){return A(t,this.chains).output}async getRegistry(t){let e=A(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return A(t,this.chains).dataLoader}getWallet(t){return A(t,this.chains).wallet}get factory(){return new M(this.config,this.chains)}get index(){return new st(this.config)}get linkBuilder(){return new L(this.config,this.chains)}createBuilder(t){return A(t,this.chains).builder()}createAbiBuilder(t){return A(t,this.chains).abiBuilder()}createBrandBuilder(t){return A(t,this.chains).brandBuilder()}createSerializer(t){return A(t,this.chains).serializer}resolveText(t){return K(t,this.config)}};var jt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Jt=(u=>(u.Multiversx="multiversx",u.Vibechain="vibechain",u.Sui="sui",u.Ethereum="ethereum",u.Base="base",u.Arbitrum="arbitrum",u.Somnia="somnia",u.Fastset="fastset",u.Solana="solana",u.Near="near",u))(Jt||{}),c={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>r.config.user?.wallets?.[r.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},g={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},Wt=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},F={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${M.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${M.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",c.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var be=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Ee=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=c.Alerts.TriggerEventPrefix+c.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var Be=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Ne=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},$e=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var st=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},ot=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},H=null;function yt(){if(H)return H;if(typeof window<"u"&&window.crypto)return H=new st,H;if(typeof process<"u"&&process.versions?.node)return H=new ot,H;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Oe(r){H=r}async function vt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||yt()).getRandomBytes(r)}function _t(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function Fe(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function At(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await vt(r/2,t);return _t(e)}async function He(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await vt(16),r.randomBytes=!0}catch{}return r}function Ue(){return yt()}var De=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${c.Vars.Env}:`)).map(t=>{let e=t.replace(`${c.Vars.Env}:`,"").trim(),[n,i]=e.split(c.ArgCompositeSeparator);return{key:n,description:i||null}});var y=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},K=r=>{if(r==="warp")return`warp:${M.Warp}`;if(r==="brand")return`brand:${M.Brand}`;if(r==="abi")return`abi:${M.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},T=(r,t)=>r?.actions[t-1],V=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(s=>s.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(s=>e.includes(s.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},pt=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=V(t);return r===e}return!0},Q=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),s=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(s,"0"));if(t<0){let a=n+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},xt=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},U=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>t[n]||""),Ct=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),wt=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var ze={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},X=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},Ge=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Je=r=>r;var Z=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,Xe=(r,t)=>!r||!t?!1:Z(r)===Z(t),lt=(r,t,e)=>{let n=Z(e);return t===c.IdentifierType.Alias?c.IdentifierAliasMarker+r+c.IdentifierParamSeparator+n:r+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+n},B=r=>{let t=decodeURIComponent(r).trim(),e=Z(t),n=e.split("?")[0],i=It(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Hash,identifier:e,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,o]=i;if(a===c.IdentifierType.Alias||a===c.IdentifierType.Hash){let p=e.includes("?")?o+e.substring(e.indexOf("?")):o;return{chain:s,type:a,identifier:p,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===c.IdentifierType.Alias||s===c.IdentifierType.Hash){let o=e.includes("?")?a+e.substring(e.indexOf("?")):a;return{chain:c.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==c.IdentifierType.Alias&&s!==c.IdentifierType.Hash){let o=e.includes("?")?a+e.substring(e.indexOf("?")):a,p=Kt(a,s)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:s,type:p,identifier:o,identifierBase:a}}}return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Alias,identifier:e,identifierBase:n}},G=r=>{let t=new URL(r),n=t.searchParams.get(c.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return B(i)},Kt=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Qt=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},It=r=>{let t=Qt(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),s=r.substring(n+e.length),a=It(s);return[i,...a]},St=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},bt=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null};var ct=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},tr=r=>{let t=new Set(Object.values(g));if(!r.includes(c.ArgParamsSeparator))return!1;let e=ct(r)[0];return t.has(e)};var Pt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,s])=>{let a=X(s,e);return[i,U(a,t)]});return Object.fromEntries(n)};import Xt from"qr-code-styling";var k=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!G(t):!1}build(t,e,n){let i=this.config.clientUrl||F.DefaultClientUrl(this.config.env),s=y(t,this.adapters),a=e===c.IdentifierType.Alias?n:e+c.IdentifierParamSeparator+n,o=s.chainInfo.name+c.IdentifierParamSeparator+a,p=encodeURIComponent(o);return F.SuperClientUrls.includes(i)?`${i}/${p}`:`${i}?${c.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let e=B(t);if(!e)return null;let n=y(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,s="white",a="black",o="#23F7DD"){let p=y(t,this.adapters),l=this.build(p.chainInfo.name,e,n);return new Xt({type:"svg",width:i,height:i,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Zt="https://",Tt=(r,t,e,n,i)=>{let s=e.actions?.[n-1]?.next||e.next||null;if(!s)return null;if(s.startsWith(Zt))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let f=U(a,{...e.vars,...i});return[{identifier:f,url:ut(t,f,r)}]}let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let f=U(o,{...e.vars,...i}),v=f?`${a}?${f}`:a;return[{identifier:v,url:ut(t,v,r)}]}let l=p[0];if(!l)return[];let u=l.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let m=p.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let v=o;for(let{regex:P,field:R}of m){let x=R?Yt(f,R):f;if(x==null)return null;v=v.replace(P,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${a}?${v}`:a;return{identifier:A,url:ut(t,A,r)}}).filter(f=>f!==null)},ut=(r,t,e)=>{let[n,i]=t.split("?"),s=B(n)||{chain:c.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},a=y(s.chain,r);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let o=new k(e,r).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let p=new URL(o);return new URLSearchParams(i).forEach((l,u)=>p.searchParams.set(u,l)),p.toString().replace(/\/\?/,"?")},Yt=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var L=class L{static debug(...t){L.isTestEnv||console.debug(...t)}static info(...t){L.isTestEnv||console.info(...t)}static warn(...t){L.isTestEnv||console.warn(...t)}static error(...t){L.isTestEnv||console.error(...t)}};L.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=L;function te(r,t,e){return r.startsWith(c.Position.Payload)?r.slice(c.Position.Payload.length).split(".").reduceRight((n,i,s,a)=>({[i]:s===a.length-1?{[t]:e}:n}),{}):{[t]:e}}function Et(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=Et(e[n],t[n]):e[n]=t[n]}),e}function ee(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function N(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function Y(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,s=ee(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let a=te(n.input.position,i,s);e=Et(e,a)}else e[i]=s}),e}var tt=async(r,t,e,n,i,s)=>{let a=[],o=[],p={};for(let[u,d]of Object.entries(r.output||{})){if(d.startsWith(c.Transform.Prefix))continue;let h=ae(d);if(h!==null&&h!==e){p[u]=null;continue}let[m,...W]=d.split("."),f=(v,A)=>A.reduce((P,R)=>P&&P[R]!==void 0?P[R]:null,v);if(m==="out"||m.startsWith("out[")){let v=W.length===0?t?.data||t:f(t,W);a.push(String(v)),o.push(v),p[u]=v}else p[u]=d}let l=Y(n,i);return{values:{string:a,native:o,mapped:l},output:await re(r,p,e,n,i,s)}},re=async(r,t,e,n,i,s)=>{if(!r.output)return t;let a={...t};return a=ne(a,r,e,n,i),a=await ie(r,a,s.transform?.runner||null),a},ne=(r,t,e,n,i)=>{let s={...r},a=T(t,e)?.inputs||[];for(let[o,p]of Object.entries(s))if(typeof p=="string"&&p.startsWith("in.")){let l=p.split(".")[1],u=a.findIndex(h=>h.as===l||h.name===l),d=u!==-1?n[u]?.value:null;s[o]=d?i.stringToNative(d)[1]:null}return s},ie=async(r,t,e)=>{if(!r.output)return t;let n={...t},i=Object.entries(r.output).filter(([,s])=>s.startsWith(c.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(c.Transform.Prefix.length)}));if(i.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:a}of i)try{n[s]=await e.run(a,n)}catch(o){C.error(`Transform error for output '${s}':`,o),n[s]=null}return n},ae=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var br=(r,t,e,n)=>{let i=r.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:n}};async function se(r,t,e,n=5){let i=await At(64,e),s=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function dt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return se(r,i,e,5)}function ft(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Rr(r,t,e,n){let{message:i,nonce:s,expiresAt:a}=await dt(r,e,n),o=await t(i);return ft(r,o,s,a)}function Br(r){let t=new Date(r).getTime();return Date.now()<t}function Nr(r){try{let t=JSON.parse(r);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var Vr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},oe=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>oe(r.user?.wallets?.[t]||null),pe=r=>r?typeof r=="string"?r:r.privateKey||null:null,le=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ce=r=>r?typeof r=="string"?r:r.externalId||null:null,Or=(r,t)=>pe(r.user?.wallets?.[t]||null)?.trim()||null,Fr=(r,t)=>le(r.user?.wallets?.[t]||null)?.trim()||null,ue=(r,t)=>ce(r.user?.wallets?.[t]||null)?.trim()||null,Hr=(r,t)=>{let e=ue(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Ur=r=>typeof r=="string",Lr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},de=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},fe=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},jr=(r,t=24)=>{let e=de(r);return fe(e,t),e};async function Mr(r){let t={address:null,publicKey:null};if(!r)return t;try{t.address=await r.getAddress()}catch{}try{t.publicKey=await r.getPublicKey()}catch{}return t}function qr(r,t,e){return null}import{x402Client as Rt}from"@x402/core/client";import{x402HTTPClient as Bt}from"@x402/core/http";async function Nt(r,t,e,n,i){let s=await ge(r,i);if(!s)return r;let a=new Headers;n&&a.set("Content-Type","application/json"),a.set("Accept","application/json"),Object.entries(s).forEach(([p,l])=>{a.set(p,l)}),C.debug("WarpExecutor: Retrying request with payment headers");let o=await fetch(t,{method:e,headers:a,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:o.status}),o}var ge=async(r,t)=>{let e=await he(r),i=new Bt(new Rt).getPaymentRequiredResponse(s=>r.headers.get(s),e);if(!i?.accepts?.length)return null;for(let s of t)if(s.wallet.registerX402Handlers)try{let a=new Rt,o=await s.wallet.registerX402Handlers(a),p=i.accepts.find(h=>h?.network&&o[h.network]);if(!p?.network)continue;o[p.network]();let l=new Bt(a),u=await l.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=l.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${s.chainInfo.name} adapter using ${p.network} scheme`),d}catch{continue}return null},he=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===g.Tuple&&Array.isArray(e)){if(e.length===0)return t+c.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e.map(a=>this.getTypeAndValue(a)),i=n.map(([a])=>a),s=n.map(([,a])=>a);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===g.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,s=Object.keys(n).filter(o=>o!=="_name");if(s.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let a=s.map(o=>{let[p,l]=this.getTypeAndValue(n[o]);return`(${o}${c.ArgParamsSeparator}${p})${l}`});return`${t}(${i})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}if(t===g.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${c.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e[0],i=n.indexOf(c.ArgParamsSeparator),s=n.substring(0,i),a=e.map(p=>{let l=p.indexOf(c.ArgParamsSeparator),u=p.substring(l+1);return s.startsWith(g.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),o=s.startsWith(g.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+s+c.ArgParamsSeparator+a.join(o)}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===g.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?g.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):g.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t+c.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(c.ArgParamsSeparator),n=e[0],i=e.slice(1).join(c.ArgParamsSeparator);if(n==="null")return[n,null];if(n===g.Option){let[s,a]=i.split(c.ArgParamsSeparator);return[g.Option+c.ArgParamsSeparator+s,a||null]}if(n===g.Vector){let s=i.indexOf(c.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),p=a.startsWith(g.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(o?o.split(p):[]).map(d=>this.stringToNative(a+c.ArgParamsSeparator+d)[1]);return[g.Vector+c.ArgParamsSeparator+a,u]}else if(n.startsWith(g.Tuple)){let s=n.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),o=i.split(c.ArgCompositeSeparator).map((p,l)=>this.stringToNative(`${s[l]}${c.IdentifierParamSeparator}${p}`)[1]);return[n,o]}else if(n.startsWith(g.Struct)){let s=n.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:s[1]};return i&&i.split(c.ArgListSeparator).forEach(p=>{let l=p.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(l){let[,u,d,h]=l;o[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${h}`)[1]}}),[n,o]}else{if(n===g.String)return[n,i];if(n===g.Uint8||n===g.Uint16||n===g.Uint32)return[n,Number(i)];if(n===g.Uint64||n===g.Uint128||n===g.Uint256||n===g.Biguint)return[n,BigInt(i||0)];if(n===g.Bool)return[n,i==="true"];if(n===g.Address)return[n,i];if(n===g.Hex)return[n,i];if(n===g.Asset){let[s,a]=i.split(c.ArgCompositeSeparator),o={identifier:s,amount:BigInt(a)};return[n,o]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(n);if(s){let o=s.stringToNative(i);return[n,o]}let a=this.typeRegistry.resolveType(n);if(a!==n){let[o,p]=this.stringToNative(`${a}:${i}`);return[n,p]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(c.ArgParamsSeparator)){let[e,n]=t.split(c.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[g.Uint32,t]:typeof t=="bigint"?[g.Uint64,t]:typeof t=="boolean"?[g.Bool,t]:[typeof t,t]}};var tn=r=>new w().nativeToString(g.String,r),en=r=>new w().nativeToString(g.Uint8,r),rn=r=>new w().nativeToString(g.Uint16,r),nn=r=>new w().nativeToString(g.Uint32,r),an=r=>new w().nativeToString(g.Uint64,r),sn=r=>new w().nativeToString(g.Biguint,r),on=r=>new w().nativeToString(g.Bool,r),pn=r=>new w().nativeToString(g.Address,r),$t=r=>new w().nativeToString(g.Asset,r),ln=r=>new w().nativeToString(g.Hex,r),cn=(r,t)=>{if(t===null)return g.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),s=e.substring(n+1);return g.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+s},un=(...r)=>new w().nativeToString(g.Tuple,r),dn=r=>new w().nativeToString(g.Struct,r),fn=r=>new w().nativeToString(g.Vector,r);import me from"ajv";var Vt=class{constructor(t){this.pendingBrand={protocol:K("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||F.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),s=new me,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import We from"ajv";var et=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=V(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&e.push(`${s} name '${a}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(a=>a.type==="contract"),n=t.actions.some(a=>a.type==="query");if(!e&&!n)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||F.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),s=new We({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var Ot=class{constructor(t){this.config=t;this.pendingWarp={protocol:K("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return xt(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new et(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
-
`))}};var J=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,ve);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,ye))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}},Ft=new w,ye=(r,t)=>typeof t=="bigint"?Ft.nativeToString("biguint",t):t,ve=(r,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?Ft.stringToNative(t)[1]:t;var O=class O{get(t){let e=O.cache.get(t);return e?Date.now()>e.expiresAt?(O.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;O.cache.set(t,{value:e,expiresAt:i})}forget(t){O.cache.delete(t)}clear(){O.cache.clear()}};O.cache=new Map;var _=O;var Ht={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},gt={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`},rt=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new J:t==="memory"?new _:typeof window<"u"&&window.localStorage?new J:new _}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var E=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);return await this.applyGlobals(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),s=(a,o)=>{i=i.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o!="string")s(a,o);else if(o.startsWith(c.Vars.Query+c.ArgParamsSeparator)){let p=o.slice(c.Vars.Query.length+1),[l,u]=p.split(c.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(l):null,m=e.queries?.[l]||null||d;m&&s(a,m)}else if(o.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let p=o.slice(c.Vars.Env.length+1),[l,u]=p.split(c.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[l];h&&s(a,h)}else o===c.Source.UserWallet&&n?s(a,n):s(a,o)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(e,n,i);return U(s,a)}applyGlobalsToText(t){if(!Object.values(c.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)||t.includes(`{{${a}:`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(c.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString())),s=this.replacePlaceholdersWithChain(s,a.Placeholder,i,a.Accessor)}),s}replacePlaceholdersWithChain(t,e,n,i){let s=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(s,(a,o)=>{let p=o.trim().toLowerCase();if(!this.adapters)return a;try{let l=y(p,this.adapters),u={config:this.config,adapter:l},d=i(u);return d!=null?d.toString():a}catch{return a}})}buildInputBag(t,e,n){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=e.stringToNative(s.value);i[a]=String(o)}),n&&n.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=e.stringToNative(s.value);if(i[`primary.${a}`]=String(o),s.input.type==="asset"&&typeof s.input.position=="object"){let p=o;p&&typeof p=="object"&&"identifier"in p&&"amount"in p&&(i[`primary.${a}.token`]=String(p.identifier),i[`primary.${a}.amount`]=String(p.amount))}}),i}};var q=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new rt(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(gt.WarpExecutable(t,e||"",n))||[];return N(i)}async createExecutable(t,e,n,i={}){let s=T(t,e);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,n),o=y(a.name,this.adapters),p=new E(this.config,o,this.adapters),l=await p.apply(t,i),u=T(l,e),{action:d,index:h}=V(l),m=this.getStringTypedInputs(d,n),W=await this.getResolvedInputs(a.name,d,m,p),f=await this.getModifiedInputs(W),v=[],A=[];h===e-1?(v=W,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(a.name,u,n,p),A=await this.getModifiedInputs(v));let P=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,R=this.getDestinationFromAction(u),x=P?this.serializer.stringToNative(P)[1]:R;if(x&&(x=p.applyInputs(x,A,this.serializer,f)),!x&&s.type!=="collect"&&s.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let j=this.getPreparedArgs(u,A);j=j.map(I=>p.applyInputs(I,A,this.serializer,f));let D=A.find(I=>I.input.position==="value")?.value||null,b="value"in u?u.value:null,$=D?.split(c.ArgParamsSeparator)[1]||b||"0",z=p.applyInputs($,A,this.serializer,f),jt=BigInt(z),Dt=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),Mt=[...("transfers"in u?u.transfers:[])||[],...Dt||[]].map(I=>{let Gt=p.applyInputs(I,A,this.serializer,f);return this.serializer.stringToNative(Gt)[1]}),kt=A.find(I=>I.input.position==="data")?.value,qt="data"in u?u.data||"":null,ht=kt||qt||null,zt=ht?p.applyInputs(ht,A,this.serializer,f):null,mt={adapter:o,warp:l,chain:a,action:e,destination:x,args:j,value:jt,transfers:Mt,data:zt,resolvedInputs:A};return this.cache.set(gt.WarpExecutable(this.config.env,l.meta?.hash||"",e),mt.resolvedInputs,Ht.OneWeek),mt}async getChainInfoForWarp(t,e){if(t.chain)return y(t.chain,this.adapters).chainInfo;if(e){let i=await this.tryGetChainFromInputs(t,e);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,e){let n=t.inputs||[];return e.map((i,s)=>{let a=n[s];return!a||i.includes(c.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,e,n,i){let s=e.inputs||[],a=await Promise.all(n.map(p=>this.preprocessInput(t,p))),o=(p,l)=>{if(p.source==="query"){let u=this.url.searchParams.get(p.name);return u?this.serializer.nativeToString(p.type,u):null}else if(p.source===c.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(p.source==="hidden"){if(p.default===void 0)return null;let u=i?i.applyInputs(String(p.default),[],this.serializer):String(p.default);return this.serializer.nativeToString(p.type,u)}else return a[l]||null};return s.map((p,l)=>{let u=o(p,l),d=p.default!==void 0?i?i.applyInputs(String(p.default),[],this.serializer):String(p.default):void 0;return{input:p,value:u||(d!==void 0?this.serializer.nativeToString(p.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,s]=i.input.modifier.split(":");if(isNaN(Number(s))){let a=Number(t.find(l=>l.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let p=Q(o,+a);e.push({...i,value:`${i.input.type}:${p}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=Q(a,+s);e.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let s=i.input.modifier.substring(c.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let o=this.buildInputContext(t,n,i),p=await a.run(s,o);if(p==null)e.push(i);else{let l=this.serializer.nativeToString(i.input.type,p);e.push({...i,value:l})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let s=0;s<e;s++){let a=t[s];if(!a.value)continue;let o=a.input.as||a.input.name,[,p]=this.serializer.stringToNative(a.value);if(i[o]=p,a.input.type==="asset"&&typeof p=="object"&&p!==null){let l=p;"identifier"in l&&"amount"in l&&(i[`${o}.token`]=String(l.identifier),i[`${o}.amount`]=String(l.amount),i[`${o}.identifier`]=String(l.identifier))}}if(n&&n.value){let s=n.input.as||n.input.name,[,a]=this.serializer.stringToNative(n.value);if(i[s]=a,n.input.type==="asset"&&typeof a=="object"&&a!==null){let o=a;"identifier"in o&&"amount"in o&&(i[`${s}.token`]=String(o.identifier),i[`${s}.amount`]=String(o.amount),i[`${s}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=ct(e),s=y(t,this.adapters);if(n==="asset"){let[a,o,p]=i.split(c.ArgCompositeSeparator);if(p)return e;let l=await s.dataLoader.getAsset(a);if(!l)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof l.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=Q(o,l.decimals);return $t({...l,amount:u})}else return e}catch(n){throw C.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[o,p]=this.serializer.stringToNative(a),l=p;if(!l||typeof l!="object"||!("identifier"in l)||!("amount"in l))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,d=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",l.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",l.amount)})}else if(s.position.startsWith("arg:")){let o=Number(s.position.split(":")[1])-1;i.push({index:o,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;n.length<=s;)n.push(void 0);n[s]=a}),n.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(p=>p.inputs?.some(l=>l.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(p=>p.position==="chain");if(i===-1||i===void 0)return null;let s=e[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return y(a,this.adapters).chainInfo}};var nt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new q(t,e)}async execute(t,e,n={}){let i=[],s=null,a=[],o=[],{action:p,index:l}=V(t);for(let u=1;u<=t.actions.length;u++){let d=T(t,u);if(!pt(d,t))continue;let{tx:h,chain:m,immediateExecution:W,executable:f}=await this.executeAction(t,u,e,n);h&&i.push(h),m&&(s=m),W&&a.push(W),f&&u===l+1&&f.resolvedInputs&&(o=N(f.resolvedInputs))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:o}}async executeAction(t,e,n,i={}){let s=T(t,e);if(s.type==="link")return s.when&&!await this.evaluateWhenCondition(t,s,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let l=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(l):Wt.open(l,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});let a=await this.factory.createExecutable(t,e,n,i);if(s.when&&!await this.evaluateWhenCondition(t,s,n,i,a.resolvedInputs,a.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(s.type==="collect"){let l=await this.executeCollect(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(l.output._DATA),result:l}),{tx:null,chain:null,immediateExecution:null,executable:a})}if(s.type==="mcp"){let l=await this.executeMcp(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(l.output._DATA),result:l}),{tx:null,chain:null,immediateExecution:l,executable:a})}let o=y(a.chain.name,this.adapters);if(s.type==="query"){let l=await o.executor.executeQuery(a);return l.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:a.chain,execution:l,tx:null})):this.handlers?.onError?.({message:JSON.stringify(l.output._DATA),result:l}),{tx:null,chain:a.chain,immediateExecution:l,executable:a}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=y(n.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,o)=>{if(!pt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let p=e[o],l=o+1;if(!p){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,l),h={status:"error",warp:t,action:l,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${l} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,l,p);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:l,chain:n,execution:u,tx:p})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else{let a=s.find(o=>o.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s)}`,result:a}))}}async executeCollect(t,e){let n=S(this.config,t.chain.name),i=T(t.warp,t.action),s=this.factory.getSerializer(),a=Y(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,a,e);let{values:o,output:p}=await tt(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,n,"unhandled",o,p)}async doHttpRequest(t,e,n,i,s){let a=new E(this.config,y(t.chain.name,this.adapters),this.adapters),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!n)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:d,nonce:h,expiresAt:m}=await dt(n,`${t.chain.name}-adapter`),W=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:d,chain:t.chain}));if(W){let f=ft(n,W,h,m);Object.entries(f).forEach(([v,A])=>o.set(v,A))}}e.headers&&Object.entries(e.headers).forEach(([d,h])=>{let m=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(d,m)});let p=e.method||"GET",l=p==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(e.url,t.resolvedInputs,this.factory.getSerializer());C.debug("WarpExecutor: Executing HTTP collect",{url:u,method:p,headers:o,body:l});try{let h=await fetch(u,{method:p,headers:o,body:l});C.debug("Collect response status",{status:h.status}),h.status===402&&(h=await Nt(h,u,p,l,this.adapters));let m=await h.json();C.debug("Collect response content",{content:m});let{values:W,output:f}=await tt(t.warp,m,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),h.ok?"success":"error",W,f,m)}catch(d){C.error("WarpActionExecutor: Error executing collect",d);let h=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:d},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=S(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let m=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let s,a;try{s=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,a=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let W=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}let o=this.factory.getSerializer(),p=new E(this.config,y(t.chain.name,this.adapters),this.adapters),l=i.destination,u=p.applyInputs(l.url,t.resolvedInputs,this.factory.getSerializer()),d=p.applyInputs(l.tool,t.resolvedInputs,this.factory.getSerializer()),h={};l.headers&&Object.entries(l.headers).forEach(([m,W])=>{let f=p.applyInputs(W,t.resolvedInputs,this.factory.getSerializer());h[m]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let m=new a(new URL(u),{requestInit:{headers:h}}),W=new s({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await W.connect(m);let f={};t.resolvedInputs.forEach(({input:x,value:j})=>{if(j&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let D=x.position.replace("payload:",""),[b,$]=o.stringToNative(j);if(b==="string")f[D]=String($);else if(b==="bool")f[D]=!!$;else if(b==="uint8"||b==="uint16"||b==="uint32"||b==="uint64"||b==="uint128"||b==="uint256"||b==="biguint"){let z=Number($);f[D]=(Number.isInteger(z),z)}else f[D]=$}}),e&&Object.assign(f,e);let v=await W.callTool({name:d,arguments:f});await W.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:P,output:R}=await tt(t.warp,A,t.action,t.resolvedInputs,o,this.config);return this.buildCollectResult(t,n,"success",P,R,v)}catch(m){C.error("WarpExecutor: Error executing MCP",m);let W=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:m},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}}buildCollectResult(t,e,n,i,s,a){let o=Tt(this.config,this.adapters,t.warp,t.action,s),p=N(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:Pt(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:p}}async callHandler(t){if(t)return await t()}async evaluateWhenCondition(t,e,n,i,s,a){if(!e.when)return!0;let o=a?{name:a}:await this.factory.getChainInfoForWarp(t,n),p=y(o.name,this.adapters),l=new E(this.config,p,this.adapters),{action:u}=V(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(o.name,u,d,l),m=await this.factory.getModifiedInputs(h),W;if(s)W=s;else{let A=await this.factory.getResolvedInputs(o.name,e,this.factory.getStringTypedInputs(e,n),l);W=await this.factory.getModifiedInputs(A)}let f=l.buildInputBag(W,this.factory.getSerializer(),m),v=Ct(e.when,f);return wt(v)}};var it=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw C.error("WarpIndex: Error searching for warps: ",i),i}}};var at=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!G(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),o=a.length>0,p=a.map(l=>({url:l.url,warp:l.warp}));return{match:o,output:p}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(c.HttpProtocolPrefix)?G(t):B(t);if(!i)return n;try{let{type:s,identifierBase:a}=i,o=null,p=null,l=null,u=y(i.chain,this.adapters),d=t.startsWith(c.HttpProtocolPrefix)?St(t):bt(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,e);let f=await u.registry.getInfoByHash(a,e);p=f.registryInfo,l=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(a,e);p=f.registryInfo,l=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(o&&o.meta&&(Ae(o,u.chainInfo.name,p,i.identifier),o.meta.query=d),!o)return n;let h=o.chain||u.chainInfo.name,m=y(h,this.adapters),W=await new E(this.config,m,this.adapters).apply(o);return{match:!0,url:t,warp:W,chain:h,registryInfo:p,brand:l}}catch(s){return C.error("Error detecting warp link",s),n}}},Ae=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?lt(t,"alias",e.alias):lt(t,"hash",e?.hash??n))};var Ut=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new nt(this.config,this.chains,t)}async detectWarp(t,e){return new at(this.config,this.chains).detect(t,e)}async executeWarp(t,e,n,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),o=s?t:null;if(!o&&a){let W=await fetch(t);if(!W.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await W.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let p=this.createExecutor(n),{txs:l,chain:u,immediateExecutions:d,resolvedInputs:h}=await p.execute(o,e,{queries:i.queries});return{txs:l,chain:u,immediateExecutions:d,evaluateOutput:async W=>{await p.evaluateOutput(o,W)},resolvedInputs:h}}async createInscriptionTransaction(t,e){return await y(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return y(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=B(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return y(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return y(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async a=>i.getAction(a,n)))).filter(a=>a!==null)}getExplorer(t){return y(t,this.chains).explorer}getOutput(t){return y(t,this.chains).output}async getRegistry(t){let e=y(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return y(t,this.chains).dataLoader}getWallet(t){return y(t,this.chains).wallet}get factory(){return new q(this.config,this.chains)}get index(){return new it(this.config)}get linkBuilder(){return new k(this.config,this.chains)}createBuilder(t){return y(t,this.chains).builder()}createAbiBuilder(t){return y(t,this.chains).abiBuilder()}createBrandBuilder(t){return y(t,this.chains).brandBuilder()}createSerializer(t){return y(t,this.chains).serializer}resolveText(t){return X(t,this.config)}};var Lt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{st as BrowserCryptoProvider,Ht as CacheTtl,ot as NodeCryptoProvider,ze as WARP_LANGUAGES,Vt as WarpBrandBuilder,Ot as WarpBuilder,rt as WarpCache,gt as WarpCacheKey,Jt as WarpChainName,Ut as WarpClient,F as WarpConfig,c as WarpConstants,nt as WarpExecutor,q as WarpFactory,it as WarpIndex,g as WarpInputTypes,E as WarpInterpolator,k as WarpLinkBuilder,at as WarpLinkDetecter,C as WarpLogger,M as WarpProtocolVersions,w as WarpSerializer,Lt as WarpTypeRegistry,et as WarpValidator,pn as address,Pt as applyOutputToMessages,$t as asset,sn as biguint,on as bool,Y as buildMappedOutput,te as buildNestedPayload,Fe as bytesToBase64,_t as bytesToHex,Z as cleanWarpIdentifier,ft as createAuthHeaders,dt as createAuthMessage,Ue as createCryptoProvider,qr as createDefaultWalletProvider,Rr as createHttpAuthHeaders,se as createSignableMessage,Je as createWarpI18nText,lt as createWarpIdentifier,re as evaluateOutputCommon,wt as evaluateWhenCondition,tt as extractCollectOutput,G as extractIdentifierInfoFromUrl,bt as extractQueryStringFromIdentifier,St as extractQueryStringFromUrl,N as extractResolvedInputValues,De as extractWarpSecrets,y as findWarpAdapterForChain,yt as getCryptoProvider,Ee as getEventNameFromWarp,K as getLatestProtocolIdentifier,Tt as getNextInfo,br as getProviderConfig,vt as getRandomBytes,At as getRandomHex,Vr as getWalletFromConfigOrFail,T as getWarpActionByIndex,Be as getWarpBrandLogoUrl,Ne as getWarpChainAssetLogoUrl,$e as getWarpChainInfoLogoUrl,B as getWarpInfoFromIdentifier,V as getWarpPrimaryAction,oe as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,ce as getWarpWalletExternalId,ue as getWarpWalletExternalIdFromConfig,Hr as getWarpWalletExternalIdFromConfigOrFail,le as getWarpWalletMnemonic,Fr as getWarpWalletMnemonicFromConfig,pe as getWarpWalletPrivateKey,Or as getWarpWalletPrivateKeyFromConfig,Nt as handleX402Payment,tr as hasInputPrefix,ln as hex,Mr as initializeWalletCache,Xe as isEqualWarpIdentifier,pt as isWarpActionAutoExecute,Ge as isWarpI18nText,Ur as isWarpWalletReadOnly,Et as mergeNestedPayload,jr as normalizeAndValidateMnemonic,de as normalizeMnemonic,cn as option,ae as parseOutputOutIndex,Nr as parseSignedMessage,U as replacePlaceholders,Ct as replacePlaceholdersInWhenExpression,X as resolveWarpText,Wt as safeWindow,Oe as setCryptoProvider,Lr as setWarpWalletInConfig,Q as shiftBigintBy,ct as splitInput,tn as string,dn as struct,He as testCryptoAvailability,ee as toInputPayloadValue,xt as toPreviewText,un as tuple,rn as uint16,nn as uint32,an as uint64,en as uint8,fe as validateMnemonicLength,Br as validateSignedMessage,fn as vector,be as withAdapterFallback};
|
|
1
|
+
var Yt=(d=>(d.Multiversx="multiversx",d.Vibechain="vibechain",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(Yt||{}),c={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>r.config.user?.wallets?.[r.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},g={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},wt=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},V={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${M.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${M.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",c.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var He=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Fe=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=c.Alerts.TriggerEventPrefix+c.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var De=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Le=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},je=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var ot=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},pt=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},F=null;function It(){if(F)return F;if(typeof window<"u"&&window.crypto)return F=new ot,F;if(typeof process<"u"&&process.versions?.node)return F=new pt,F;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function qe(r){F=r}async function St(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||It()).getRandomBytes(r)}function Zt(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function ze(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function Pt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await St(r/2,t);return Zt(e)}async function ke(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await St(16),r.randomBytes=!0}catch{}return r}function Ge(){return It()}var Qe=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${c.Vars.Env}:`)).map(t=>{let e=t.replace(`${c.Vars.Env}:`,"").trim(),[n,i]=e.split(c.ArgCompositeSeparator);return{key:n,description:i||null}});var A=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},K=r=>{if(r==="warp")return`warp:${M.Warp}`;if(r==="brand")return`brand:${M.Brand}`;if(r==="abi")return`abi:${M.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},E=(r,t)=>r?.actions[t-1],N=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(s=>s.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(s=>e.includes(s.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},lt=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=N(t);return r===e}return!0},X=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),s=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(s,"0"));if(t<0){let a=n+i;if(s>=a.length)return 0n;let p=a.slice(0,-s)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},bt=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},U=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>t[n]||""),Tt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Et=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var Ze={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},Y=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},tr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,er=r=>r;var Z=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,ar=(r,t)=>!r||!t?!1:Z(r)===Z(t),ct=(r,t,e)=>{let n=Z(e);return t===c.IdentifierType.Alias?c.IdentifierAliasMarker+r+c.IdentifierParamSeparator+n:r+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+n},$=r=>{let t=decodeURIComponent(r).trim(),e=Z(t),n=e.split("?")[0],i=Rt(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Hash,identifier:e,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,p]=i;if(a===c.IdentifierType.Alias||a===c.IdentifierType.Hash){let l=e.includes("?")?p+e.substring(e.indexOf("?")):p;return{chain:s,type:a,identifier:l,identifierBase:p}}}if(i.length===2){let[s,a]=i;if(s===c.IdentifierType.Alias||s===c.IdentifierType.Hash){let p=e.includes("?")?a+e.substring(e.indexOf("?")):a;return{chain:c.IdentifierChainDefault,type:s,identifier:p,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==c.IdentifierType.Alias&&s!==c.IdentifierType.Hash){let p=e.includes("?")?a+e.substring(e.indexOf("?")):a,l=te(a,s)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:s,type:l,identifier:p,identifierBase:a}}}return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Alias,identifier:e,identifierBase:n}},G=r=>{let t=new URL(r),n=t.searchParams.get(c.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return $(i)},te=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,ee=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Rt=r=>{let t=ee(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),s=r.substring(n+e.length),a=Rt(s);return[i,...a]},Bt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},Nt=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null};var ut=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},pr=r=>{let t=new Set(Object.values(g));if(!r.includes(c.ArgParamsSeparator))return!1;let e=ut(r)[0];return t.has(e)};var dt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,s])=>{let a=Y(s,e);return[i,U(a,t)]});return Object.fromEntries(n)};import re from"qr-code-styling";var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!G(t):!1}build(t,e,n){let i=this.config.clientUrl||V.DefaultClientUrl(this.config.env),s=A(t,this.adapters),a=e===c.IdentifierType.Alias?n:e+c.IdentifierParamSeparator+n,p=s.chainInfo.name+c.IdentifierParamSeparator+a,l=encodeURIComponent(p);return V.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${c.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=$(t);if(!e)return null;let n=A(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,s="white",a="black",p="#23F7DD"){let l=A(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new re({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var ne="https://",gt=(r,t,e,n,i)=>{let s=e.actions?.[n-1]?.next||e.next||null;if(!s)return null;if(s.startsWith(ne))return[{identifier:null,url:s}];let[a,p]=s.split("?");if(!p){let f=U(a,{...e.vars,...i});return[{identifier:f,url:ft(t,f,r)}]}let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let f=U(p,{...e.vars,...i}),y=f?`${a}?${f}`:a;return[{identifier:y,url:ft(t,y,r)}]}let o=l[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let m=l.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let y=f.match(/\[\](\.[^}]+)?}}/),v=y&&y[1]||"";return{placeholder:f,field:v?v.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let y=p;for(let{regex:P,field:b}of m){let x=b?ie(f,b):f;if(x==null)return null;y=y.replace(P,x)}if(y.includes("{{")||y.includes("}}"))return null;let v=y?`${a}?${y}`:a;return{identifier:v,url:ft(t,v,r)}}).filter(f=>f!==null)},ft=(r,t,e)=>{let[n,i]=t.split("?"),s=$(n)||{chain:c.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},a=A(s.chain,r);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let p=new q(e,r).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((o,u)=>l.searchParams.set(u,o)),l.toString().replace(/\/\?/,"?")},ie=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var D=class D{static debug(...t){D.isTestEnv||console.debug(...t)}static info(...t){D.isTestEnv||console.info(...t)}static warn(...t){D.isTestEnv||console.warn(...t)}static error(...t){D.isTestEnv||console.error(...t)}};D.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=D;function ae(r,t,e){return r.startsWith(c.Position.Payload)?r.slice(c.Position.Payload.length).split(".").reduceRight((n,i,s,a)=>({[i]:s===a.length-1?{[t]:e}:n}),{}):{[t]:e}}function $t(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=$t(e[n],t[n]):e[n]=t[n]}),e}function se(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function B(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function tt(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,s=se(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let a=ae(n.input.position,i,s);e=$t(e,a)}else e[i]=s}),e}var et=async(r,t,e,n,i,s)=>{let a=[],p=[],l={};for(let[u,d]of Object.entries(r.output||{})){if(d.startsWith(c.Transform.Prefix))continue;let h=ce(d);if(h!==null&&h!==e){l[u]=null;continue}let[m,...W]=d.split("."),f=(y,v)=>v.reduce((P,b)=>P&&P[b]!==void 0?P[b]:null,y);if(m==="out"||m.startsWith("out[")){let y=W.length===0?t?.data||t:f(t,W);a.push(String(y)),p.push(y),l[u]=y}else l[u]=d}let o=tt(n,i);return{values:{string:a,native:p,mapped:o},output:await oe(r,l,e,n,i,s)}},oe=async(r,t,e,n,i,s)=>{if(!r.output)return t;let a={...t};return a=pe(a,r,e,n,i),a=await le(r,a,s.transform?.runner||null),a},pe=(r,t,e,n,i)=>{let s={...r},a=E(t,e)?.inputs||[];for(let[p,l]of Object.entries(s))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],u=a.findIndex(h=>h.as===o||h.name===o),d=u!==-1?n[u]?.value:null;s[p]=d?i.stringToNative(d)[1]:null}return s},le=async(r,t,e)=>{if(!r.output)return t;let n={...t},i=Object.entries(r.output).filter(([,s])=>s.startsWith(c.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(c.Transform.Prefix.length)}));if(i.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:a}of i)try{n[s]=await e.run(a,n)}catch(p){C.error(`Transform error for output '${s}':`,p),n[s]=null}return n},ce=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var Hr=(r,t,e,n)=>{let i=r.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:n}};async function ue(r,t,e,n=5){let i=await Pt(64,e),s=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function ht(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return ue(r,i,e,5)}function mt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Ur(r,t,e,n){let{message:i,nonce:s,expiresAt:a}=await ht(r,e,n),p=await t(i);return mt(r,p,s,a)}function Dr(r){let t=new Date(r).getTime();return Date.now()<t}function Lr(r){try{let t=JSON.parse(r);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var Mr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},de=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>de(r.user?.wallets?.[t]||null),fe=r=>r?typeof r=="string"?r:r.privateKey||null:null,ge=r=>r?typeof r=="string"?r:r.mnemonic||null:null,he=r=>r?typeof r=="string"?r:r.externalId||null:null,qr=(r,t)=>fe(r.user?.wallets?.[t]||null)?.trim()||null,zr=(r,t)=>ge(r.user?.wallets?.[t]||null)?.trim()||null,me=(r,t)=>he(r.user?.wallets?.[t]||null)?.trim()||null,kr=(r,t)=>{let e=me(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Gr=r=>typeof r=="string",_r=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},ye=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},We=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},Jr=(r,t=24)=>{let e=ye(r);return We(e,t),e};async function Kr(r){let t={address:null,publicKey:null};if(!r)return t;try{t.address=await r.getAddress()}catch{}try{t.publicKey=await r.getPublicKey()}catch{}return t}function Yr(r,t,e){return null}import{x402Client as Ht}from"@x402/core/client";import{x402HTTPClient as Ot}from"@x402/core/http";async function Vt(r,t,e,n,i){let s=await Ae(r,i);if(!s)return r;let a=new Headers;n&&a.set("Content-Type","application/json"),a.set("Accept","application/json"),Object.entries(s).forEach(([l,o])=>{a.set(l,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:a,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var Ae=async(r,t)=>{let e=await ve(r),i=new Ot(new Ht).getPaymentRequiredResponse(s=>r.headers.get(s),e);if(!i?.accepts?.length)return null;for(let s of t)if(s.wallet.registerX402Handlers)try{let a=new Ht,p=await s.wallet.registerX402Handlers(a),l=i.accepts.find(h=>h?.network&&p[h.network]);if(!l?.network)continue;p[l.network]();let o=new Ot(a),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${s.chainInfo.name} adapter using ${l.network} scheme`),d}catch{continue}return null},ve=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===g.Tuple&&Array.isArray(e)){if(e.length===0)return t+c.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e.map(a=>this.getTypeAndValue(a)),i=n.map(([a])=>a),s=n.map(([,a])=>a);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===g.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,s=Object.keys(n).filter(p=>p!=="_name");if(s.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let a=s.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${c.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}if(t===g.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${c.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e[0],i=n.indexOf(c.ArgParamsSeparator),s=n.substring(0,i),a=e.map(l=>{let o=l.indexOf(c.ArgParamsSeparator),u=l.substring(o+1);return s.startsWith(g.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=s.startsWith(g.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+s+c.ArgParamsSeparator+a.join(p)}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===g.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?g.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):g.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t+c.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(c.ArgParamsSeparator),n=e[0],i=e.slice(1).join(c.ArgParamsSeparator);if(n==="null")return[n,null];if(n===g.Option){let[s,a]=i.split(c.ArgParamsSeparator);return[g.Option+c.ArgParamsSeparator+s,a||null]}if(n===g.Vector){let s=i.indexOf(c.ArgParamsSeparator),a=i.substring(0,s),p=i.substring(s+1),l=a.startsWith(g.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(a+c.ArgParamsSeparator+d)[1]);return[g.Vector+c.ArgParamsSeparator+a,u]}else if(n.startsWith(g.Tuple)){let s=n.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),p=i.split(c.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${s[o]}${c.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(g.Struct)){let s=n.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:s[1]};return i&&i.split(c.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${h}`)[1]}}),[n,p]}else{if(n===g.String)return[n,i];if(n===g.Uint8||n===g.Uint16||n===g.Uint32)return[n,Number(i)];if(n===g.Uint64||n===g.Uint128||n===g.Uint256||n===g.Biguint)return[n,BigInt(i||0)];if(n===g.Bool)return[n,i==="true"];if(n===g.Address)return[n,i];if(n===g.Hex)return[n,i];if(n===g.Asset){let[s,a]=i.split(c.ArgCompositeSeparator),p={identifier:s,amount:BigInt(a)};return[n,p]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(n);if(s){let p=s.stringToNative(i);return[n,p]}let a=this.typeRegistry.resolveType(n);if(a!==n){let[p,l]=this.stringToNative(`${a}:${i}`);return[n,l]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(c.ArgParamsSeparator)){let[e,n]=t.split(c.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[g.Uint32,t]:typeof t=="bigint"?[g.Uint64,t]:typeof t=="boolean"?[g.Bool,t]:[typeof t,t]}};var ln=r=>new w().nativeToString(g.String,r),cn=r=>new w().nativeToString(g.Uint8,r),un=r=>new w().nativeToString(g.Uint16,r),dn=r=>new w().nativeToString(g.Uint32,r),fn=r=>new w().nativeToString(g.Uint64,r),gn=r=>new w().nativeToString(g.Biguint,r),hn=r=>new w().nativeToString(g.Bool,r),mn=r=>new w().nativeToString(g.Address,r),Ft=r=>new w().nativeToString(g.Asset,r),yn=r=>new w().nativeToString(g.Hex,r),Wn=(r,t)=>{if(t===null)return g.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),s=e.substring(n+1);return g.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+s},An=(...r)=>new w().nativeToString(g.Tuple,r),vn=r=>new w().nativeToString(g.Struct,r),xn=r=>new w().nativeToString(g.Vector,r);import xe from"ajv";var Ut=class{constructor(t){this.pendingBrand={protocol:K("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||V.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),s=new xe,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import Ce from"ajv";var rt=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=N(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&e.push(`${s} name '${a}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(a=>a.type==="contract"),n=t.actions.some(a=>a.type==="query");if(!e&&!n)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||V.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),s=new Ce({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var Dt=class{constructor(t){this.config=t;this.pendingWarp={protocol:K("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return bt(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new rt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
+
`))}};var _=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,Ie);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,we))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}},Lt=new w,we=(r,t)=>typeof t=="bigint"?Lt.nativeToString("biguint",t):t,Ie=(r,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?Lt.stringToNative(t)[1]:t;var O=class O{get(t){let e=O.cache.get(t);return e?Date.now()>e.expiresAt?(O.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;O.cache.set(t,{value:e,expiresAt:i})}forget(t){O.cache.delete(t)}clear(){O.cache.clear()}};O.cache=new Map;var J=O;var jt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},yt={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`},nt=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new _:t==="memory"?new J:typeof window<"u"&&window.localStorage?new _:new J}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var Q={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Wt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},At=(r,t,e)=>{let n=r.find(s=>s.input.as===t||s.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},vt=r=>{try{return JSON.parse(r)}catch{return null}},Se=async(r,t,e,n,i,s)=>{let a=new Headers;if(a.set("Content-Type","application/json"),a.set("Accept","application/json"),s&&n){let{message:l,nonce:o,expiresAt:u}=await ht(n,`${e.chain.name}-adapter`),d=await s({message:l,chain:e.chain});d&&Object.entries(mt(n,d,o,u)).forEach(([h,m])=>a.set(h,m))}let p=At(e.resolvedInputs,Q.Headers,i);if(p){let l=vt(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,u])=>typeof u=="string"&&a.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{a.set(l,r.applyInputs(o,e.resolvedInputs,i))});return a},Pe=(r,t,e,n,i)=>{let s=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Wt.Get){let a=At(e.resolvedInputs,Q.Queries,i);if(a){let p=vt(a);if(p&&typeof p=="object"){let l=new URL(s);Object.entries(p).forEach(([o,u])=>u!=null&&l.searchParams.set(o,String(u))),s=l.toString()}}}return s},be=(r,t,e,n,i)=>{if(r===Wt.Get)return;let s=At(t.resolvedInputs,Q.Payload,n);if(s&&vt(s)!==null)return s;let{[Q.Payload]:a,[Q.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},Mt=async(r,t,e,n,i,s,a,p)=>{let l=t.method||Wt.Get,o=await Se(r,t,e,n,s,p),u=Pe(r,t,e,l,s),d=be(l,e,i,s,a);return{url:u,method:l,headers:o,body:d}};var R=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);return await this.applyGlobals(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),s=(a,p)=>{i=i.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([a,p])=>{if(typeof p!="string")s(a,p);else if(p.startsWith(c.Vars.Query+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Query.length+1),[o,u]=l.split(c.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,m=e.queries?.[o]||null||d;m&&s(a,m)}else if(p.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Env.length+1),[o,u]=l.split(c.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h&&s(a,h)}else p===c.Source.UserWallet&&n?s(a,n):s(a,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(e,n,i);return U(s,a)}applyGlobalsToText(t){if(!Object.values(c.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)||t.includes(`{{${a}:`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(c.Globals).forEach(a=>{let p=a.Accessor(i);p!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),p.toString())),s=this.replacePlaceholdersWithChain(s,a.Placeholder,i,a.Accessor)}),s}replacePlaceholdersWithChain(t,e,n,i){let s=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(s,(a,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return a;try{let o=A(l,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():a}catch{return a}})}buildInputBag(t,e,n){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,p]=e.stringToNative(s.value);i[a]=String(p)}),n&&n.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,p]=e.stringToNative(s.value);if(i[`primary.${a}`]=String(p),s.input.type==="asset"&&typeof s.input.position=="object"){let l=p;l&&typeof l=="object"&&"identifier"in l&&"amount"in l&&(i[`primary.${a}.token`]=String(l.identifier),i[`primary.${a}.amount`]=String(l.amount))}}),i}};var z=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new nt(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(yt.WarpExecutable(t,e||"",n))||[];return B(i)}async createExecutable(t,e,n,i={}){let s=E(t,e);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,n),p=A(a.name,this.adapters),l=new R(this.config,p,this.adapters),o=await l.apply(t,i),u=E(o,e),{action:d,index:h}=N(o),m=this.getStringTypedInputs(d,n),W=await this.getResolvedInputs(a.name,d,m,l),f=await this.getModifiedInputs(W),y=[],v=[];h===e-1?(y=W,v=f):this.requiresPayloadInputs(u)&&(y=await this.resolveActionInputs(a.name,u,n,l),v=await this.getModifiedInputs(y));let P=v.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,b=this.getDestinationFromAction(u),x=P?this.serializer.stringToNative(P)[1]:b;if(x&&(x=l.applyInputs(x,v,this.serializer,f)),!x&&s.type!=="collect"&&s.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let L=this.getPreparedArgs(u,v);L=L.map(I=>l.applyInputs(I,v,this.serializer,f));let j=v.find(I=>I.input.position==="value")?.value||null,T="value"in u?u.value:null,H=j?.split(c.ArgParamsSeparator)[1]||T||"0",k=l.applyInputs(H,v,this.serializer,f),kt=BigInt(k),Gt=v.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),_t=[...("transfers"in u?u.transfers:[])||[],...Gt||[]].map(I=>{let Xt=l.applyInputs(I,v,this.serializer,f);return this.serializer.stringToNative(Xt)[1]}),Jt=v.find(I=>I.input.position==="data")?.value,Qt="data"in u?u.data||"":null,xt=Jt||Qt||null,Kt=xt?l.applyInputs(xt,v,this.serializer,f):null,Ct={adapter:p,warp:o,chain:a,action:e,destination:x,args:L,value:kt,transfers:_t,data:Kt,resolvedInputs:v};return this.cache.set(yt.WarpExecutable(this.config.env,o.meta?.hash||"",e),Ct.resolvedInputs,jt.OneWeek),Ct}async getChainInfoForWarp(t,e){if(t.chain)return A(t.chain,this.adapters).chainInfo;if(e){let i=await this.tryGetChainFromInputs(t,e);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,e){let n=t.inputs||[];return e.map((i,s)=>{let a=n[s];return!a||i.includes(c.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,e,n,i){let s=e.inputs||[],a=await Promise.all(n.map(l=>this.preprocessInput(t,l))),p=(l,o)=>{if(l.source==="query"){let u=this.url.searchParams.get(l.name);return u?this.serializer.nativeToString(l.type,u):null}else if(l.source===c.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(l.source==="hidden"){if(l.default===void 0)return null;let u=i?i.applyInputs(String(l.default),[],this.serializer):String(l.default);return this.serializer.nativeToString(l.type,u)}else return a[o]||null};return s.map((l,o)=>{let u=p(l,o),d=l.default!==void 0?i?i.applyInputs(String(l.default),[],this.serializer):String(l.default):void 0;return{input:l,value:u||(d!==void 0?this.serializer.nativeToString(l.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,s]=i.input.modifier.split(":");if(isNaN(Number(s))){let a=Number(t.find(o=>o.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=X(p,+a);e.push({...i,value:`${i.input.type}:${l}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let p=X(a,+s);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let s=i.input.modifier.substring(c.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=this.buildInputContext(t,n,i),l=await a.run(s,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let s=0;s<e;s++){let a=t[s];if(!a.value)continue;let p=a.input.as||a.input.name,[,l]=this.serializer.stringToNative(a.value);if(i[p]=l,a.input.type==="asset"&&typeof l=="object"&&l!==null){let o=l;"identifier"in o&&"amount"in o&&(i[`${p}.token`]=String(o.identifier),i[`${p}.amount`]=String(o.amount),i[`${p}.identifier`]=String(o.identifier))}}if(n&&n.value){let s=n.input.as||n.input.name,[,a]=this.serializer.stringToNative(n.value);if(i[s]=a,n.input.type==="asset"&&typeof a=="object"&&a!==null){let p=a;"identifier"in p&&"amount"in p&&(i[`${s}.token`]=String(p.identifier),i[`${s}.amount`]=String(p.amount),i[`${s}.identifier`]=String(p.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=ut(e),s=A(t,this.adapters);if(n==="asset"){let[a,p,l]=i.split(c.ArgCompositeSeparator);if(l)return e;let o=await s.dataLoader.getAsset(a);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=X(p,o.decimals);return Ft({...o,amount:u})}else return e}catch(n){throw C.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[p,l]=this.serializer.stringToNative(a),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,d=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(s.position.startsWith("arg:")){let p=Number(s.position.split(":")[1])-1;i.push({index:p,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;n.length<=s;)n.push(void 0);n[s]=a}),n.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let s=e[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return A(a,this.adapters).chainInfo}};var it=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new z(t,e)}async execute(t,e,n={}){let i=[],s=null,a=[],p=[],{action:l,index:o}=N(t);for(let u=1;u<=t.actions.length;u++){let d=E(t,u);if(!lt(d,t))continue;let{tx:h,chain:m,immediateExecution:W,executable:f}=await this.executeAction(t,u,e,n);h&&i.push(h),m&&(s=m),W&&a.push(W),f&&u===o+1&&f.resolvedInputs&&(p=B(f.resolvedInputs))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:p}}async executeAction(t,e,n,i={}){let s=E(t,e);if(s.type==="link")return s.when&&!await this.evaluateWhenCondition(t,s,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):wt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(s.type==="prompt"){let o=await this.executePrompt(t,s,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}let a=await this.factory.createExecutable(t,e,n,i);if(s.when&&!await this.evaluateWhenCondition(t,s,n,i,a.resolvedInputs,a.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(s.type==="collect"){let o=await this.executeCollect(a);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:a};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:a};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:a}}if(s.type==="mcp"){let o=await this.executeMcp(a);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:a};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:a};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:a}}}let p=A(a.chain.name,this.adapters);if(s.type==="query"){let o=await p.executor.executeQuery(a);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:a.chain,execution:o,tx:null}));else{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:a.chain,immediateExecution:o,executable:a}}return{tx:await p.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=A(n.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,p)=>{if(!lt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,l);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else{let a=s.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s)}`,result:a}))}}async executeCollect(t,e){let n=S(this.config,t.chain.name),i=E(t.warp,t.action),s=this.factory.getSerializer(),a=tt(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,a,e);let{values:p,output:l}=await et(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async doHttpRequest(t,e,n,i,s){let a=new R(this.config,A(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await Mt(a,e,t,n,i,p,s,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:u,body:d});try{let m=await fetch(l,{method:o,headers:u,body:d});C.debug("Collect response status",{status:m.status}),m.status===402&&(m=await Vt(m,l,o,d,this.adapters));let W=await m.json();C.debug("Collect response content",{content:W});let{values:f,output:y}=await et(t.warp,W,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),m.ok?"success":"error",f,y,W)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let m=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=S(this.config,t.chain.name),i=E(t.warp,t.action);if(!i.destination){let m=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let s,a;try{s=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,a=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let W=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}let p=this.factory.getSerializer(),l=new R(this.config,A(t.chain.name,this.adapters),this.adapters),o=i.destination,u=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([m,W])=>{let f=l.applyInputs(W,t.resolvedInputs,this.factory.getSerializer());h[m]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let m=new a(new URL(u),{requestInit:{headers:h}}),W=new s({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await W.connect(m);let f={};t.resolvedInputs.forEach(({input:x,value:L})=>{if(L&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let j=x.position.replace("payload:",""),[T,H]=p.stringToNative(L);if(T==="string")f[j]=String(H);else if(T==="bool")f[j]=!!H;else if(T==="uint8"||T==="uint16"||T==="uint32"||T==="uint64"||T==="uint128"||T==="uint256"||T==="biguint"){let k=Number(H);f[j]=(Number.isInteger(k),k)}else f[j]=H}}),e&&Object.assign(f,e);let y=await W.callTool({name:d,arguments:f});await W.close();let v;if(y.content&&y.content.length>0){let x=y.content[0];if(x.type==="text")try{v=JSON.parse(x.text)}catch{v=x.text}else x.type,v=x}else v=y;let{values:P,output:b}=await et(t.warp,v,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",P,b,y)}catch(m){C.error("WarpExecutor: Error executing MCP",m);let W=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:m},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}}buildCollectResult(t,e,n,i,s,a){let p=gt(this.config,this.adapters,t.warp,t.action,s),l=B(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:a?{...s,_DATA:a}:s,messages:dt(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,s={}){try{let a=await this.factory.getChainInfoForWarp(t,i),p=A(a.name,this.adapters),l=new R(this.config,p,this.adapters),o=await l.apply(t,s),u=E(o,n),{action:d}=N(o),h=this.factory.getStringTypedInputs(d,i),m=await this.factory.getResolvedInputs(a.name,d,h,l),W=await this.factory.getModifiedInputs(m),f=W;if(e.inputs&&e.inputs.length>0){let b=this.factory.getStringTypedInputs(e,i),x=await this.factory.getResolvedInputs(a.name,e,b,l);f=await this.factory.getModifiedInputs(x)}let y=l.applyInputs(u.prompt,f,this.factory.getSerializer(),W),v=B(f),P=S(this.config,a.name);return{status:"success",warp:o,action:n,user:P,txHash:null,tx:null,next:gt(this.config,this.adapters,o,n,{prompt:y}),values:{string:[y],native:[y],mapped:{prompt:y}},output:{prompt:y},messages:dt(o,{prompt:y},this.config),destination:null,resolvedInputs:v}}catch(a){return C.error("WarpExecutor: Error executing prompt action",a),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:a},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,s,a){if(!e.when)return!0;let p=a?{name:a}:await this.factory.getChainInfoForWarp(t,n),l=A(p.name,this.adapters),o=new R(this.config,l,this.adapters),{action:u}=N(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(p.name,u,d,o),m=await this.factory.getModifiedInputs(h),W;if(s)W=s;else{let v=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o);W=await this.factory.getModifiedInputs(v)}let f=o.buildInputBag(W,this.factory.getSerializer(),m),y=Tt(e.when,f);return Et(y)}};var at=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw C.error("WarpIndex: Error searching for warps: ",i),i}}};var st=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!G(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),a=(await Promise.all(i)).filter(o=>o.match),p=a.length>0,l=a.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(c.HttpProtocolPrefix)?G(t):$(t);if(!i)return n;try{let{type:s,identifierBase:a}=i,p=null,l=null,o=null,u=A(i.chain,this.adapters),d=t.startsWith(c.HttpProtocolPrefix)?Bt(t):Nt(i.identifier);if(s==="hash"){p=await u.builder().createFromTransactionHash(a,e);let f=await u.registry.getInfoByHash(a,e);l=f.registryInfo,o=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(a,e);l=f.registryInfo,o=f.brand,f.registryInfo&&(p=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(p&&p.meta&&(Te(p,u.chainInfo.name,l,i.identifier),p.meta.query=d),!p)return n;let h=p.chain||u.chainInfo.name,m=A(h,this.adapters),W=await new R(this.config,m,this.adapters).apply(p);return{match:!0,url:t,warp:W,chain:h,registryInfo:l,brand:o}}catch(s){return C.error("Error detecting warp link",s),n}}},Te=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?ct(t,"alias",e.alias):ct(t,"hash",e?.hash??n))};var qt=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new it(this.config,this.chains,t)}async detectWarp(t,e){return new st(this.config,this.chains).detect(t,e)}async executeWarp(t,e,n,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),p=s?t:null;if(!p&&a){let W=await fetch(t);if(!W.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await W.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async W=>{await l.evaluateOutput(p,W)},resolvedInputs:h}}async createInscriptionTransaction(t,e){return await A(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return A(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=$(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return A(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return A(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async a=>i.getAction(a,n)))).filter(a=>a!==null)}getExplorer(t){return A(t,this.chains).explorer}getOutput(t){return A(t,this.chains).output}async getRegistry(t){let e=A(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return A(t,this.chains).dataLoader}getWallet(t){return A(t,this.chains).wallet}get factory(){return new z(this.config,this.chains)}get index(){return new at(this.config)}get linkBuilder(){return new q(this.config,this.chains)}createBuilder(t){return A(t,this.chains).builder()}createAbiBuilder(t){return A(t,this.chains).abiBuilder()}createBrandBuilder(t){return A(t,this.chains).brandBuilder()}createSerializer(t){return A(t,this.chains).serializer}resolveText(t){return Y(t,this.config)}};var zt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{ot as BrowserCryptoProvider,jt as CacheTtl,pt as NodeCryptoProvider,Ze as WARP_LANGUAGES,Ut as WarpBrandBuilder,Dt as WarpBuilder,nt as WarpCache,yt as WarpCacheKey,Yt as WarpChainName,qt as WarpClient,V as WarpConfig,c as WarpConstants,it as WarpExecutor,z as WarpFactory,at as WarpIndex,g as WarpInputTypes,R as WarpInterpolator,q as WarpLinkBuilder,st as WarpLinkDetecter,C as WarpLogger,M as WarpProtocolVersions,w as WarpSerializer,zt as WarpTypeRegistry,rt as WarpValidator,mn as address,dt as applyOutputToMessages,Ft as asset,gn as biguint,hn as bool,tt as buildMappedOutput,ae as buildNestedPayload,ze as bytesToBase64,Zt as bytesToHex,Z as cleanWarpIdentifier,mt as createAuthHeaders,ht as createAuthMessage,Ge as createCryptoProvider,Yr as createDefaultWalletProvider,Ur as createHttpAuthHeaders,ue as createSignableMessage,er as createWarpI18nText,ct as createWarpIdentifier,oe as evaluateOutputCommon,Et as evaluateWhenCondition,et as extractCollectOutput,G as extractIdentifierInfoFromUrl,Nt as extractQueryStringFromIdentifier,Bt as extractQueryStringFromUrl,B as extractResolvedInputValues,Qe as extractWarpSecrets,A as findWarpAdapterForChain,It as getCryptoProvider,Fe as getEventNameFromWarp,K as getLatestProtocolIdentifier,gt as getNextInfo,Hr as getProviderConfig,St as getRandomBytes,Pt as getRandomHex,Mr as getWalletFromConfigOrFail,E as getWarpActionByIndex,De as getWarpBrandLogoUrl,Le as getWarpChainAssetLogoUrl,je as getWarpChainInfoLogoUrl,$ as getWarpInfoFromIdentifier,N as getWarpPrimaryAction,de as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,he as getWarpWalletExternalId,me as getWarpWalletExternalIdFromConfig,kr as getWarpWalletExternalIdFromConfigOrFail,ge as getWarpWalletMnemonic,zr as getWarpWalletMnemonicFromConfig,fe as getWarpWalletPrivateKey,qr as getWarpWalletPrivateKeyFromConfig,Vt as handleX402Payment,pr as hasInputPrefix,yn as hex,Kr as initializeWalletCache,ar as isEqualWarpIdentifier,lt as isWarpActionAutoExecute,tr as isWarpI18nText,Gr as isWarpWalletReadOnly,$t as mergeNestedPayload,Jr as normalizeAndValidateMnemonic,ye as normalizeMnemonic,Wn as option,ce as parseOutputOutIndex,Lr as parseSignedMessage,U as replacePlaceholders,Tt as replacePlaceholdersInWhenExpression,Y as resolveWarpText,wt as safeWindow,qe as setCryptoProvider,_r as setWarpWalletInConfig,X as shiftBigintBy,ut as splitInput,ln as string,vn as struct,ke as testCryptoAvailability,se as toInputPayloadValue,bt as toPreviewText,An as tuple,un as uint16,dn as uint32,fn as uint64,cn as uint8,We as validateMnemonicLength,Dr as validateSignedMessage,xn as vector,He as withAdapterFallback};
|