@joai/warps 4.13.0 → 4.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.cts +15 -3
- package/dist/index.d.ts +15 -3
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -523,9 +523,9 @@ type WarpMeta = {
|
|
|
523
523
|
creator: string;
|
|
524
524
|
createdAt: string;
|
|
525
525
|
};
|
|
526
|
-
type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpComputeAction | WarpLinkAction | WarpMcpAction | WarpPromptAction | WarpStateAction | WarpMountAction | WarpUnmountAction;
|
|
526
|
+
type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpComputeAction | WarpLinkAction | WarpMcpAction | WarpPromptAction | WarpStateAction | WarpMountAction | WarpUnmountAction | WarpLoopAction;
|
|
527
527
|
type WarpActionIndex = number;
|
|
528
|
-
type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'compute' | 'link' | 'mcp' | 'prompt' | 'state' | 'mount' | 'unmount';
|
|
528
|
+
type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'compute' | 'link' | 'mcp' | 'prompt' | 'state' | 'mount' | 'unmount' | 'loop';
|
|
529
529
|
type WarpTrigger = {
|
|
530
530
|
type: 'message';
|
|
531
531
|
pattern: string;
|
|
@@ -571,6 +571,18 @@ type WarpUnmountAction = {
|
|
|
571
571
|
next?: WarpNextConfig;
|
|
572
572
|
when?: string;
|
|
573
573
|
};
|
|
574
|
+
type WarpLoopAction = {
|
|
575
|
+
type: 'loop';
|
|
576
|
+
label: WarpText;
|
|
577
|
+
description?: WarpText | null;
|
|
578
|
+
inputs?: WarpActionInput[];
|
|
579
|
+
primary?: boolean;
|
|
580
|
+
auto?: boolean;
|
|
581
|
+
next?: WarpNextConfig;
|
|
582
|
+
when?: string;
|
|
583
|
+
delay?: number;
|
|
584
|
+
maxIterations?: number;
|
|
585
|
+
};
|
|
574
586
|
type WarpTransferAction = {
|
|
575
587
|
type: WarpActionType;
|
|
576
588
|
label: WarpText;
|
|
@@ -1465,4 +1477,4 @@ declare function resolveInputs(trigger: WebhookTrigger, payload: unknown): Recor
|
|
|
1465
1477
|
*/
|
|
1466
1478
|
declare function resolvePath(obj: unknown, path: string): unknown;
|
|
1467
1479
|
|
|
1468
|
-
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, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, MultiversxWalletChainNames, 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, WarpAssets, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheAdapter, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetNftMetadata, type WarpChainAssetType, type WarpChainAssetValue, WarpChainDisplayNames, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainLogos, WarpChainName, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, type WarpComputeAction, 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 WarpMountAction, type WarpNativeValue, type WarpNextConfig, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getChainDisplayName, getChainLogo, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getMppFetch, getNextInfo, getNextInfoForStatus, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, matchesTrigger, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveInputs, resolveNextString, resolvePath, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
|
1480
|
+
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, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, MultiversxWalletChainNames, 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, WarpAssets, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheAdapter, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetNftMetadata, type WarpChainAssetType, type WarpChainAssetValue, WarpChainDisplayNames, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainLogos, WarpChainName, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, type WarpComputeAction, 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 WarpLoopAction, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpMountAction, type WarpNativeValue, type WarpNextConfig, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getChainDisplayName, getChainLogo, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getMppFetch, getNextInfo, getNextInfoForStatus, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, matchesTrigger, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveInputs, resolveNextString, resolvePath, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
package/dist/index.d.ts
CHANGED
|
@@ -523,9 +523,9 @@ type WarpMeta = {
|
|
|
523
523
|
creator: string;
|
|
524
524
|
createdAt: string;
|
|
525
525
|
};
|
|
526
|
-
type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpComputeAction | WarpLinkAction | WarpMcpAction | WarpPromptAction | WarpStateAction | WarpMountAction | WarpUnmountAction;
|
|
526
|
+
type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpComputeAction | WarpLinkAction | WarpMcpAction | WarpPromptAction | WarpStateAction | WarpMountAction | WarpUnmountAction | WarpLoopAction;
|
|
527
527
|
type WarpActionIndex = number;
|
|
528
|
-
type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'compute' | 'link' | 'mcp' | 'prompt' | 'state' | 'mount' | 'unmount';
|
|
528
|
+
type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'compute' | 'link' | 'mcp' | 'prompt' | 'state' | 'mount' | 'unmount' | 'loop';
|
|
529
529
|
type WarpTrigger = {
|
|
530
530
|
type: 'message';
|
|
531
531
|
pattern: string;
|
|
@@ -571,6 +571,18 @@ type WarpUnmountAction = {
|
|
|
571
571
|
next?: WarpNextConfig;
|
|
572
572
|
when?: string;
|
|
573
573
|
};
|
|
574
|
+
type WarpLoopAction = {
|
|
575
|
+
type: 'loop';
|
|
576
|
+
label: WarpText;
|
|
577
|
+
description?: WarpText | null;
|
|
578
|
+
inputs?: WarpActionInput[];
|
|
579
|
+
primary?: boolean;
|
|
580
|
+
auto?: boolean;
|
|
581
|
+
next?: WarpNextConfig;
|
|
582
|
+
when?: string;
|
|
583
|
+
delay?: number;
|
|
584
|
+
maxIterations?: number;
|
|
585
|
+
};
|
|
574
586
|
type WarpTransferAction = {
|
|
575
587
|
type: WarpActionType;
|
|
576
588
|
label: WarpText;
|
|
@@ -1465,4 +1477,4 @@ declare function resolveInputs(trigger: WebhookTrigger, payload: unknown): Recor
|
|
|
1465
1477
|
*/
|
|
1466
1478
|
declare function resolvePath(obj: unknown, path: string): unknown;
|
|
1467
1479
|
|
|
1468
|
-
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, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, MultiversxWalletChainNames, 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, WarpAssets, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheAdapter, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetNftMetadata, type WarpChainAssetType, type WarpChainAssetValue, WarpChainDisplayNames, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainLogos, WarpChainName, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, type WarpComputeAction, 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 WarpMountAction, type WarpNativeValue, type WarpNextConfig, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getChainDisplayName, getChainLogo, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getMppFetch, getNextInfo, getNextInfoForStatus, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, matchesTrigger, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveInputs, resolveNextString, resolvePath, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
|
1480
|
+
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, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, MultiversxWalletChainNames, 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, WarpAssets, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheAdapter, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetNftMetadata, type WarpChainAssetType, type WarpChainAssetValue, WarpChainDisplayNames, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainLogos, WarpChainName, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, type WarpComputeAction, 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 WarpLoopAction, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpMountAction, type WarpNativeValue, type WarpNextConfig, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getChainDisplayName, getChainLogo, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getMppFetch, getNextInfo, getNextInfoForStatus, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, matchesTrigger, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveInputs, resolveNextString, resolvePath, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, 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 Ke=Object.create;var vt=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var Ye=Object.getPrototypeOf,tr=Object.prototype.hasOwnProperty;var er=(r,t)=>{for(var e in t)vt(r,e,{get:t[e],enumerable:!0})},ge=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ze(t))!tr.call(r,i)&&i!==e&&vt(r,i,{get:()=>t[i],enumerable:!(n=Xe(t,i))||n.enumerable});return r};var Q=(r,t,e)=>(e=r!=null?Ke(Ye(r)):{},ge(t||!r||!r.__esModule?vt(e,"default",{value:r,enumerable:!0}):e,r)),rr=r=>ge(vt({},"__esModule",{value:!0}),r);var xn={};er(xn,{BrowserCryptoProvider:()=>xt,CLOUD_WALLET_PROVIDERS:()=>gr,CacheTtl:()=>ie,EvmWalletChainNames:()=>ur,MultiversxWalletChainNames:()=>dr,NodeCryptoProvider:()=>At,WARP_LANGUAGES:()=>br,WarpAssets:()=>S,WarpBrandBuilder:()=>te,WarpBuilder:()=>ee,WarpCache:()=>gt,WarpCacheKey:()=>ft,WarpChainDisplayNames:()=>Ae,WarpChainLogos:()=>we,WarpChainName:()=>xe,WarpChainResolver:()=>et,WarpClient:()=>pe,WarpCompositeResolver:()=>rt,WarpConfig:()=>D,WarpConstants:()=>c,WarpExecutor:()=>mt,WarpFactory:()=>J,WarpIndex:()=>yt,WarpInputTypes:()=>m,WarpInterpolator:()=>B,WarpLinkBuilder:()=>z,WarpLinkDetecter:()=>Wt,WarpLogger:()=>x,WarpPlatformName:()=>Ft,WarpPlatforms:()=>Ot,WarpProtocolVersions:()=>j,WarpSerializer:()=>w,WarpTypeRegistry:()=>le,WarpValidator:()=>ct,address:()=>sn,applyOutputToMessages:()=>Pt,asset:()=>Yt,biguint:()=>nn,bool:()=>an,buildGeneratedFallbackWarpIdentifier:()=>Le,buildGeneratedSourceWarpIdentifier:()=>Gr,buildInputsContext:()=>lt,buildMappedOutput:()=>_,buildNestedPayload:()=>Te,bytesToBase64:()=>Ar,bytesToHex:()=>Ie,checkWarpAssetBalance:()=>Xr,cleanWarpIdentifier:()=>K,createAuthHeaders:()=>Tt,createAuthMessage:()=>bt,createCryptoProvider:()=>Ir,createDefaultWalletProvider:()=>Kr,createHttpAuthHeaders:()=>kr,createSignableMessage:()=>$e,createWarpI18nText:()=>Er,createWarpIdentifier:()=>It,doesWarpRequireWallet:()=>Pr,evaluateOutputCommon:()=>Qt,evaluateWhenCondition:()=>jt,extractCollectOutput:()=>Z,extractIdentifierInfoFromUrl:()=>X,extractPromptOutput:()=>Kt,extractQueryStringFromIdentifier:()=>zt,extractQueryStringFromUrl:()=>qt,extractResolvedInputValues:()=>V,extractWarpSecrets:()=>Sr,findWarpAdapterForChain:()=>v,getChainDisplayName:()=>hr,getChainLogo:()=>mr,getCryptoProvider:()=>Ht,getEventNameFromWarp:()=>yr,getGeneratedSourceWarpName:()=>Fe,getLatestProtocolIdentifier:()=>nt,getMppFetch:()=>Zt,getNextInfo:()=>ot,getNextInfoForStatus:()=>pt,getProviderConfig:()=>Dr,getRandomBytes:()=>Ut,getRandomHex:()=>Dt,getRequiredAssetIds:()=>He,getWalletFromConfigOrFail:()=>nr,getWarpActionByIndex:()=>T,getWarpBrandLogoUrl:()=>Wr,getWarpChainAssetLogoUrl:()=>vr,getWarpChainInfoLogoUrl:()=>Cr,getWarpIdentifierWithQuery:()=>Fr,getWarpInfoFromIdentifier:()=>O,getWarpPrimaryAction:()=>R,getWarpWalletAddress:()=>fe,getWarpWalletAddressFromConfig:()=>P,getWarpWalletExternalId:()=>ye,getWarpWalletExternalIdFromConfig:()=>We,getWarpWalletExternalIdFromConfigOrFail:()=>sr,getWarpWalletMnemonic:()=>me,getWarpWalletMnemonicFromConfig:()=>ar,getWarpWalletPrivateKey:()=>he,getWarpWalletPrivateKeyFromConfig:()=>ir,hasInputPrefix:()=>Or,hex:()=>on,initializeWalletCache:()=>Qr,isEqualWarpIdentifier:()=>Rr,isGeneratedSourcePrivateIdentifier:()=>Jr,isPlatformValue:()=>Be,isWarpActionAutoExecute:()=>wt,isWarpI18nText:()=>Tr,isWarpWalletReadOnly:()=>or,matchesTrigger:()=>vn,mergeNestedPayload:()=>Jt,normalizeAndValidateMnemonic:()=>cr,normalizeMnemonic:()=>ve,option:()=>pn,parseOutputOutIndex:()=>Ne,parseSignedMessage:()=>jr,parseWarpQueryStringToObject:()=>Gt,removeWarpChainPrefix:()=>$r,removeWarpWalletFromConfig:()=>lr,replacePlaceholders:()=>H,replacePlaceholdersInWhenExpression:()=>Mt,resolveInputs:()=>Cn,resolveNextString:()=>_t,resolvePath:()=>ce,resolvePlatformValue:()=>Xt,resolveWarpText:()=>at,safeWindow:()=>Vt,setCryptoProvider:()=>xr,setWarpWalletInConfig:()=>pr,shiftBigintBy:()=>it,splitInput:()=>St,stampGeneratedWarpMeta:()=>_r,string:()=>Zr,struct:()=>cn,testCryptoAvailability:()=>wr,toInputPayloadValue:()=>Ee,toPreviewText:()=>kt,tuple:()=>ln,uint16:()=>tn,uint32:()=>en,uint64:()=>rn,uint8:()=>Yr,validateMnemonicLength:()=>Ce,validateSignedMessage:()=>Mr,vector:()=>un,withAdapterFallback:()=>fr});module.exports=rr(xn);var et=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var rt=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var nr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},fe=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>fe(r.user?.wallets?.[t]||null),he=r=>r?typeof r=="string"?r:r.privateKey||null:null,me=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ye=r=>r?typeof r=="string"?r:r.externalId||null:null,ir=(r,t)=>he(r.user?.wallets?.[t]||null)?.trim()||null,ar=(r,t)=>me(r.user?.wallets?.[t]||null)?.trim()||null,We=(r,t)=>ye(r.user?.wallets?.[t]||null)?.trim()||null,sr=(r,t)=>{let e=We(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},or=r=>typeof r=="string",pr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},lr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},ve=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Ce=(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`)},cr=(r,t=24)=>{let e=ve(r);return Ce(e,t),e};var xe=(g=>(g.Multiversx="multiversx",g.Claws="claws",g.Sui="sui",g.Ethereum="ethereum",g.Base="base",g.Arbitrum="arbitrum",g.Polygon="polygon",g.Somnia="somnia",g.Tempo="tempo",g.Fastset="fastset",g.Solana="solana",g.Near="near",g))(xe||{}),Ft=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Ft||{}),Ot=Object.values(Ft),ur=["ethereum","base","arbitrum","polygon","somnia","tempo"],dr=["multiversx","claws"],gr=["coinbase","privy","gaupa"],c={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(r.config,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"}},m={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"},Vt=typeof window<"u"?window:{open:()=>{}};var j={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},D={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${j.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${j.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 fr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Ct="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",S={baseUrl:Ct,chainLogo:r=>`${Ct}/chains/logos/${r}`,tokenLogo:r=>`${Ct}/tokens/logos/${r}`,walletLogo:r=>`${Ct}/wallets/logos/${r}`},Ae={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},hr=r=>Ae[r]??r.charAt(0).toUpperCase()+r.slice(1),we={ethereum:{light:S.chainLogo("ethereum-white.svg"),dark:S.chainLogo("ethereum-black.svg")},base:{light:S.chainLogo("base-white.svg"),dark:S.chainLogo("base-black.svg")},arbitrum:S.chainLogo("arbitrum.svg"),polygon:S.chainLogo("polygon.svg"),somnia:S.chainLogo("somnia.png"),tempo:{light:S.chainLogo("tempo-white.svg"),dark:S.chainLogo("tempo-black.svg")},multiversx:S.chainLogo("multiversx.svg"),claws:S.chainLogo("claws.png"),sui:S.chainLogo("sui.svg"),solana:S.chainLogo("solana.svg"),near:{light:S.chainLogo("near-white.svg"),dark:S.chainLogo("near-black.svg")},fastset:{light:S.chainLogo("fastset-white.svg"),dark:S.chainLogo("fastset-black.svg")}},mr=(r,t="dark")=>{let e=we[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var yr=(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 Lt=(r,t)=>r[t]??r.default??Object.values(r)[0],Wr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:Lt(r.logo,e)},vr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Lt(r.logoUrl,e)},Cr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Lt(r.logoUrl,e)};var xt=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}},At=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"}`)}}},q=null;function Ht(){if(q)return q;if(typeof window<"u"&&window.crypto)return q=new xt,q;if(typeof process<"u"&&process.versions?.node)return q=new At,q;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function xr(r){q=r}async function Ut(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Ht()).getRandomBytes(r)}function Ie(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 Ar(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 Dt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Ut(r/2,t);return Ie(e)}async function wr(){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 Ut(16),r.randomBytes=!0}catch{}return r}function Ir(){return Ht()}var Sr=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 v=(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},nt=r=>{if(r==="warp")return`warp:${j.Warp}`;if(r==="brand")return`brand:${j.Brand}`;if(r==="abi")return`abi:${j.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},T=(r,t)=>r?.actions[t-1],R=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","compute","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},wt=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=R(t);return r===e}return!0},it=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},kt=(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},H=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),Mt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Pr=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===c.Source.UserWallet||n.default===`{{${c.Globals.UserWallet.Placeholder}}}`||n.default===`{{${c.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},jt=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 br={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"},at=(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 K=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,Rr=(r,t)=>!r||!t?!1:K(r)===K(t),It=(r,t,e)=>{let n=K(e);if(t===c.IdentifierType.Alias)return c.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+n},O=(r,t)=>{let e=t||c.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=K(n),a=i.split("?")[0],s=Se(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:c.IdentifierType.Hash,identifier:i,identifierBase:a};if(s.length===2&&/^[a-zA-Z0-9]{62}$/.test(s[0])&&/^[a-zA-Z0-9]{2}$/.test(s[1]))return null;if(s.length===3){let[p,l,o]=s;if(l===c.IdentifierType.Alias||l===c.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:l,identifier:u,identifierBase:o}}}if(s.length===2){let[p,l]=s;if(p===c.IdentifierType.Alias||p===c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l;return{chain:e,type:p,identifier:o,identifierBase:l}}}if(s.length===2){let[p,l]=s;if(p!==c.IdentifierType.Alias&&p!==c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l,u=Nr(l,p)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:l}}}return{chain:e,type:c.IdentifierType.Alias,identifier:i,identifierBase:a}},X=(r,t)=>{let e=new URL(r),i=e.searchParams.get(c.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return O(a,t)},Nr=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Br=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Se=r=>{let t=Br(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Se(a);return[i,...s]},qt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},zt=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},Gt=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},$r=(r,t)=>{let e=O(r,t);return(e?e.identifierBase:K(r)).trim()},Fr=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var St=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Or=r=>{let t=new Set(Object.values(m));if(!r.includes(c.ArgParamsSeparator))return!1;let e=St(r)[0];return t.has(e)};var Pt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=at(a,e);return[i,H(s,t)]});return Object.fromEntries(n)};var Pe=Q(require("qr-code-styling"),1);var z=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!X(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||D.DefaultClientUrl(this.config.env),a=v(t,this.adapters),s=e===c.IdentifierType.Alias?n:e+c.IdentifierParamSeparator+n,p=a.chainInfo.name+c.IdentifierParamSeparator+s,l=encodeURIComponent(p);return D.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${c.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=O(t,this.config.defaultChain);if(!e)return null;let n=v(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=v(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Pe.default({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},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 be="https://",_t=(r,t)=>r?typeof r=="string"?t==="success"?r:null:r[t]||null:null,ot=(r,t,e,n,i)=>{let a=T(e,n)?.next||e.next||null,s=_t(a,"success");if(!s)return null;if(s.startsWith(be))return[{identifier:null,url:s}];let[p,l]=s.split("?");if(!l){let C=H(p,{...e.vars,...i});return[{identifier:C,url:st(t,C,r)}]}let o=l.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let C=H(l,{...e.vars,...i}),W=C?`${p}?${C}`:p;return[{identifier:W,url:st(t,W,r)}]}let u=o[0];if(!u)return[];let d=u.match(/{{([^[]+)\[\]/),g=d?d[1]:null;if(!g||i[g]===void 0)return[];let f=Array.isArray(i[g])?i[g]:[i[g]];if(f.length===0)return[];let h=o.filter(C=>C.includes(`{{${g}[]`)).map(C=>{let W=C.match(/\[\](\.[^}]+)?}}/),I=W&&W[1]||"";return{placeholder:C,field:I?I.slice(1):"",regex:new RegExp(C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(C=>{let W=l;for(let{regex:k,field:A}of h){let $=A?Vr(C,A):C;if($==null)return null;W=W.replace(k,$)}if(W.includes("{{")||W.includes("}}"))return null;let I=W?`${p}?${W}`:p;return{identifier:I,url:st(t,I,r)}}).filter(C=>C!==null)},pt=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=T(e,n)?.next||e.next||null,l=_t(p,s);if(!l)return null;if(l.startsWith(be))return[{identifier:null,url:l}];let[o,u]=l.split("?");if(!u){let f=H(o,{...e.vars,...i});return[{identifier:f,url:st(t,f,r)}]}let d=H(u,{...e.vars,...i}),g=d?`${o}?${d}`:o;return[{identifier:g,url:st(t,g,r)}]},st=(r,t,e)=>{let[n,i]=t.split("?"),a=O(n,e.defaultChain)||{chain:c.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=v(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let p=new z(e,r).build(s.chainInfo.name,a.type,a.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(/\/\?/,"?")},Vr=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var G=class G{static debug(...t){G.isTestEnv||console.debug(...t)}static info(...t){G.isTestEnv||console.info(...t)}static warn(...t){G.isTestEnv||console.warn(...t)}static error(...t){G.isTestEnv||console.error(...t)}};G.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=G;function Te(r,t,e){return r.startsWith(c.Position.Payload)?r.slice(c.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Jt(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]=Jt(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 V(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function _(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=Ee(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let s=Te(n.input.position,i,a);e=Jt(e,s)}else e[i]=a}),e}function lt(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let u=o;if("identifier"in u&&"amount"in u){let d=String(u.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(u.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var Re=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(c.Transform.Prefix))continue;let l=Ne(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...u]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},Z=async(r,t,e,n,i,a)=>{let s=(d,g)=>g.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:u}=Re(r,e,p);return{values:{string:l,native:o,mapped:_(n,i)},output:await Qt(r,u,t,e,n,i,a)}},Qt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Lr(p,r,n,i,a),p=await Hr(r,p,e,i,a,s.transform?.runner||null),p},Lr=(r,t,e,n,i)=>{let a={...r},s=T(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],u=s.findIndex(g=>g.as===o||g.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Hr=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(c.Transform.Prefix)).map(([o,u])=>({key:o,code:u.substring(c.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:Ur(e),inputs:lt(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,l),l[o]=s[o]}catch(d){x.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},Ur=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},Kt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=Re(r,e,s),u=await Qt(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:l,mapped:_(n,i)},output:u}},Ne=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 Be=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Ot.some(t=>t in r),Xt=(r,t)=>{if(!Be(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var Dr=(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 $e(r,t,e,n=5){let i=await Dt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function bt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return $e(r,i,e,5)}function Tt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function kr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await bt(r,e,n),p=await t(i);return Tt(r,p,a,s)}function Mr(r){let t=new Date(r).getTime();return Date.now()<t}function jr(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 Fe=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",qr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Oe=(r,t=24)=>{let e=qr(r);return e?e.slice(0,t):"action"},Ve=r=>{let t=3735928559^r.length,e=1103547991^r.length;for(let a=0;a<r.length;a++){let s=r.charCodeAt(a);t=Math.imul(t^s,2654435761),e=Math.imul(e^s,1597334677)}t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909);let n=(e>>>0).toString(16).padStart(8,"0"),i=(t>>>0).toString(16).padStart(8,"0");return`${n}${i}`.slice(0,12)},zr=r=>{let t=(r||"").trim();if(!t)return"";try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"").toLowerCase()||"/";return`${e.origin.toLowerCase()}${n}`}catch{return t.toLowerCase()}},Gr=(r,t,e)=>{let n=Oe((e||t||"").trim()||"action"),i=`${r.type}|${zr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Ve(i);return`private_src_${n}_${a}`},Le=r=>{let t=Fe(r),e=Oe(t),n=Ve(t.trim().toLowerCase());return`private_gen_${e}_${n}`},_r=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Le(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},Jr=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Qr(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 Kr(r,t,e){return null}var He=(r,t)=>{let e=null;try{e=R(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},Xr=async(r,t,e,n)=>{try{let i=v(e,n),a=He(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};var Et=require("mppx/client");async function Zt(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return x.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),Et.Mppx.create({methods:[(0,Et.tempo)({account:e})],polyfill:!1}).fetch}return fetch}var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===m.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(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===m.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,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${c.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}if(t===m.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),a=n.substring(0,i),s=e.map(l=>{let o=l.indexOf(c.ArgParamsSeparator),u=l.substring(o+1);return a.startsWith(m.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=a.startsWith(m.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+a+c.ArgParamsSeparator+s.join(p)}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):m.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===m.Option){let[a,s]=i.split(c.ArgParamsSeparator);return[m.Option+c.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(c.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(m.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(s+c.ArgParamsSeparator+d)[1]);return[m.Vector+c.ArgParamsSeparator+s,u]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),p=i.split(c.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${c.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(c.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,g]=o;p[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${g}`)[1]}}),[n,p]}else{if(n===m.String)return[n,i];if(n===m.Uint8||n===m.Uint16||n===m.Uint32)return[n,Number(i)];if(n===m.Uint64||n===m.Uint128||n===m.Uint256||n===m.Biguint)return[n,BigInt(i||0)];if(n===m.Bool)return[n,i==="true"];if(n===m.Address)return[n,i];if(n===m.Hex)return[n,i];if(n===m.Asset){let[a,s]=i.split(c.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${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"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var Zr=r=>new w().nativeToString(m.String,r),Yr=r=>new w().nativeToString(m.Uint8,r),tn=r=>new w().nativeToString(m.Uint16,r),en=r=>new w().nativeToString(m.Uint32,r),rn=r=>new w().nativeToString(m.Uint64,r),nn=r=>new w().nativeToString(m.Biguint,r),an=r=>new w().nativeToString(m.Bool,r),sn=r=>new w().nativeToString(m.Address,r),Yt=r=>new w().nativeToString(m.Asset,r),on=r=>new w().nativeToString(m.Hex,r),pn=(r,t)=>{if(t===null)return m.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+a},ln=(...r)=>new w().nativeToString(m.Tuple,r),cn=r=>new w().nativeToString(m.Struct,r),un=r=>new w().nativeToString(m.Vector,r);var Ue=Q(require("ajv"),1);var te=class{constructor(t){this.pendingBrand={protocol:nt("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||D.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new Ue.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var De=Q(require("ajv"),1);var ct=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}=R(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,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||D.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new De.default({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ee=class{constructor(t){this.config=t;this.pendingWarp={protocol:nt("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 kt(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 ct(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
-
`))}};var b=require("fs"),tt=require("path");var re="$bigint:",Rt=(r,t)=>typeof t=="bigint"?re+t.toString():t,Y=(r,t)=>typeof t=="string"&&t.startsWith(re)?BigInt(t.slice(re.length)):t;var Nt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,tt.resolve)(n):(0,tt.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,b.existsSync)(this.cacheDir)||(0,b.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,tt.join)(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!(0,b.existsSync)(e))return null;let n=(0,b.readFileSync)(e,"utf-8"),i=JSON.parse(n,Y);return i.expiresAt!==null&&Date.now()>i.expiresAt?((0,b.unlinkSync)(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);(0,b.writeFileSync)(a,JSON.stringify(i,Rt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);(0,b.existsSync)(e)&&(0,b.unlinkSync)(e)}catch{}}async keys(t){try{let e=(0,b.readdirSync)(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{(0,b.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,b.unlinkSync)((0,tt.join)(this.cacheDir,e))})}catch{}}};var ut=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,Y);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,Rt))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var U=class U{constructor(t,e){}async get(t){let e=U.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(U.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;U.cache.set(t,{value:e,expiresAt:i})}async delete(t){U.cache.delete(t)}async keys(t){let e=Array.from(U.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){U.cache.clear()}};U.cache=new Map;var dt=U;var ke=require("fs"),ne=require("path");var Bt=class{constructor(t,e){let n=e?.path?(0,ne.resolve)(e.path):(0,ne.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,ke.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,Y)))}catch(e){return x.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var ie={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},ft={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}`,AccountNfts:(r,t,e,n,i)=>`account-nfts:${r}:${t}:${e}:${n}:${i}`},gt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new ut(t,e):e?.type==="memory"?new dt(t,e):e?.type==="static"?new Bt(t,e):e?.type==="filesystem"?new Nt(t,e):typeof window<"u"&&window.localStorage?new ut(t,e):new dt(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var ht={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},ae={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},se=(r,t,e)=>{let n=r.find(a=>a.input.as===t||a.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},oe=r=>{try{return JSON.parse(r)}catch{return null}},dn=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:u}=await bt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(Tt(n,d,o,u)).forEach(([g,f])=>s.set(g,f))}let p=se(e.resolvedInputs,ht.Headers,i);if(p){let l=oe(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},gn=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===ae.Get){let s=se(e.resolvedInputs,ht.Queries,i);if(s){let p=oe(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&l.searchParams.set(o,String(u))),a=l.toString()}}}return a},fn=(r,t,e,n,i)=>{if(r===ae.Get)return;let a=se(t.resolvedInputs,ht.Payload,n);if(a&&oe(a)!==null)return a;let{[ht.Payload]:s,[ht.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},Me=async(r,t,e,n,i,a,s,p)=>{let l=t.method||ae.Get,o=await dn(r,t,e,n,a,p),u=gn(r,t,e,l,a),d=fn(l,e,i,a,s);return{url:u,method:l,headers:o,body:d}};var B=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e),i=await this.applyGlobals(n);return e.envs?this.applyEnvs(i,e.envs):i}applyEnvs(t,e){if(!e||Object.keys(e).length===0)return t;let n=JSON.stringify(t);for(let[i,a]of Object.entries(e)){if(a==null)continue;let s=JSON.stringify(String(a)).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${hn(i)}\\}\\}`,"g"),s)}return JSON.parse(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=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,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,f=e.queries?.[o]??null??d;f!=null&&a(s,f)}else if(p.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Env.length+1),[o,u]=l.split(c.ArgCompositeSeparator),g={...this.config.vars,...e.envs}?.[o];g!=null&&a(s,g)}else p===c.Source.UserWallet&&n?a(s,n):a(s,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 a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.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 a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.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 a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return H(a,s)}applyGlobalsToText(t){if(!Object.values(c.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(c.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=v(l,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let l=p;l&&typeof l=="object"&&"identifier"in l&&"amount"in l&&(i[`primary.${s}.token`]=String(l.identifier),i[`primary.${s}.amount`]=String(l.amount))}}),i}},hn=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var mn=["collect","compute","mcp","state","mount","unmount"],J=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 gt(t.env,t.cache)}getSerializer(){return this.serializer}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(ft.WarpExecutable(t,e||"",n))||[];return V(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(ft.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=T(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=v(s.name,this.adapters),l=new B(this.config,p,this.adapters),o=await l.apply(t,i),u=T(o,e),{action:d,index:g}=R(o),f=this.getStringTypedInputs(d,n),h=await this.getResolvedInputs(s.name,d,f,l,i.queries),y=await this.getModifiedInputs(h),C=[],W=[];g===e-1?(C=h,W=y):this.requiresPayloadInputs(u)&&(C=await this.resolveActionInputs(s.name,u,n,l,i.queries),W=await this.getModifiedInputs(C));let I=W.find(E=>E.input.position==="receiver"||E.input.position==="destination")?.value,k=this.getDestinationFromAction(u),A=I?this.serializer.stringToNative(I)[1]:k;if(A&&(A=l.applyInputs(A,W,this.serializer,y)),!A&&!mn.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let $=this.getPreparedArgs(u,W);$=$.map(E=>l.applyInputs(E,W,this.serializer,y));let L=W.find(E=>E.input.position==="value")?.value||null,N="value"in u?u.value:null,F=L?.split(c.ArgParamsSeparator)[1]||N||"0",M=l.applyInputs(F,W,this.serializer,y),je=BigInt(M),qe=W.filter(E=>E.input.position==="transfer"&&E.value).map(E=>E.value),ze=[...("transfers"in u?u.transfers:[])||[],...qe||[]].map(E=>{let $t=l.applyInputs(E,W,this.serializer,y),Qe=$t.startsWith(`asset${c.ArgParamsSeparator}`)?$t:`asset${c.ArgParamsSeparator}${$t}`;return this.serializer.stringToNative(Qe)[1]}),Ge=W.find(E=>E.input.position==="data")?.value,_e="data"in u?u.data||"":null,ue=Ge||_e||null,Je=ue?l.applyInputs(ue,W,this.serializer,y):null,de={adapter:p,warp:o,chain:s,action:e,destination:A,args:$,value:je,transfers:ze,data:Je,resolvedInputs:W};return await this.cache.set(ft.WarpExecutable(this.config.env,o.meta?.hash||"",e),de.resolvedInputs,ie.OneWeek),de}async getChainInfoForWarp(t,e){if(t.chain)return v(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,a)=>{let s=n[a];return!s||i.includes(c.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(u=>i.applyInputs(u,[],this.serializer)),l=await Promise.all(p.map(u=>this.preprocessInput(t,u))),o=(u,d)=>{if(u.source===c.Source.UserWallet){let C=P(this.config,t);return C?this.serializer.nativeToString("address",C):null}if(u.source==="hidden"){if(u.default===void 0)return null;let C=i?i.applyInputs(String(u.default),[],this.serializer):String(u.default);return this.serializer.nativeToString(u.type,C)}if(l[d])return l[d];let g=u.as||u.name,f=a?.[g],h=this.url.searchParams.get(g),y=f||h;return y?this.serializer.nativeToString(u.type,String(y)):null};return s.map((u,d)=>{let g=o(u,d),f=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:g||(f!==void 0?this.serializer.nativeToString(u.type,f):null)}})}async resolveInputsFromQuery(t,e,n){let i=T(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=v(a.name,this.adapters),p=new B(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],p,n)}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i,a){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i,a)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=it(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=it(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let a=i.input.modifier.substring(c.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=lt(t,this.serializer,n,i),l=await s.run(a,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}async preprocessInput(t,e){try{let[n,i]=St(e),a=v(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(c.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=it(p,o.decimals);return Yt({...o,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:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.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(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==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 a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return v(s,this.adapters).chainInfo}};var mt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new J(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:g}=R(t);for(let f=1;f<=t.actions.length;f++){let h=T(t,f);if(!wt(h,t))continue;let{tx:y,chain:C,immediateExecution:W,executable:I}=await this.executeAction(t,f,e,u);y&&i.push(y),C&&(a=C),W&&s.push(W),I&&f===g+1&&I.resolvedInputs&&(p=V(I.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let f=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(f))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=T(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Vt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,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 s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);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:s};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:s};{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:s}}if(a.type==="compute"){let o=await this.executeCompute(s);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:s};{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:s}}if(a.type==="state"||a.type==="mount"||a.type==="unmount")return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="mcp"){let o=await this.executeMcp(s);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:s};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:s};{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:s}}}let p=v(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.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:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=v(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!wt(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let f=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(u.length===0){let f=t.meta?.query;f&&Object.keys(f).length>0&&(u=await this.factory.resolveInputsFromQuery(t,o,f))}let d=await i.output.getActionExecution(t,o,l.tx,u),g=yn(u,d.output);return d.next=pt(this.config,this.adapters,t,o,g,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(d.values),result:d})),d}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action),a=this.factory.getSerializer(),s=_(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,s,e);let{values:p,output:l}=await Z(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async executeCompute(t){let e=P(this.config,t.chain.name),n=this.factory.getSerializer(),i=_(t.resolvedInputs,n),{values:a,output:s}=await Z(t.warp,i,t.action,t.resolvedInputs,n,this.config);return this.buildCollectResult(t,e,"success",a,s)}async doHttpRequest(t,e,n,i,a){let s=new B(this.config,v(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await Me(s,e,t,n,i,p,a,async g=>await this.callHandler(()=>this.handlers?.onSignRequest?.(g)));x.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:u,body:d});try{let g={method:o,headers:u,body:d},h=await(await Zt(this.adapters))(l,g);x.debug("Collect response status",{status:h.status});let y=await h.json();x.debug("Collect response content",{content:y});let{values:C,output:W}=await Z(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),h.ok?"success":"error",C,W,y)}catch(g){x.error("WarpActionExecutor: Error executing collect",g);let f=V(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:g},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let f=V(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:f}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let h=V(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:h}}let p=this.factory.getSerializer(),l=new B(this.config,v(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()),g={};o.headers&&Object.entries(o.headers).forEach(([f,h])=>{let y=l.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());g[f]=y}),x.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:g});try{let f=new s(new URL(u),{requestInit:{headers:g}}),h=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await h.connect(f);let y={};t.resolvedInputs.forEach(({input:A,value:$})=>{if($&&A.position&&typeof A.position=="string"&&A.position.startsWith("payload:")){let L=A.position.replace("payload:",""),[N,F]=p.stringToNative($);if(N==="string")y[L]=String(F);else if(N==="bool")y[L]=!!F;else if(N==="uint8"||N==="uint16"||N==="uint32"||N==="uint64"||N==="uint128"||N==="uint256"||N==="biguint"){let M=Number(F);y[L]=(Number.isInteger(M),M)}else y[L]=F}}),e&&Object.assign(y,e);let C=await h.callTool({name:d,arguments:y});await h.close();let W;if(C.content&&C.content.length>0){let A=C.content[0];if(A.type==="text")try{W=JSON.parse(A.text)}catch{W=A.text}else A.type,W=A}else W=C;let{values:I,output:k}=await Z(t.warp,W,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",I,k,C)}catch(f){x.error("WarpExecutor: Error executing MCP",f);let h=V(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:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}buildCollectResult(t,e,n,i,a,s){let p=pt(this.config,this.adapters,t.warp,t.action,a,n),l=V(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:Pt(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=v(s.name,this.adapters),l=new B(this.config,p,this.adapters),o=await l.apply(t,a),u=T(o,n),{action:d}=R(o),g=this.factory.getStringTypedInputs(d,i),f=await this.factory.getResolvedInputs(s.name,d,g,l,a.queries),h=await this.factory.getModifiedInputs(f),y=h;if(e.inputs&&e.inputs.length>0){let F=this.factory.getStringTypedInputs(e,i),M=await this.factory.getResolvedInputs(s.name,e,F,l,a.queries);y=await this.factory.getModifiedInputs(M)}let C=Xt(u.prompt,this.config.platform),W=l.applyInputs(C,y,this.factory.getSerializer(),h),I=V(y),k=P(this.config,s.name),A=this.factory.getSerializer(),{values:$,output:L}=await Kt(o,W,n,y,A,this.config),N=y.find(F=>F.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:k,txHash:null,tx:null,next:ot(this.config,this.adapters,o,n,L),values:$,output:L,messages:Pt(o,L,this.config),destination:N,resolvedInputs:I}}catch(s){return x.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:pt(this.config,this.adapters,t,n,{},"error"),values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=v(p.name,this.adapters),o=new B(this.config,l,this.adapters),{action:u}=R(t),d=this.factory.getStringTypedInputs(u,n),g=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),f=await this.factory.getModifiedInputs(g),h;if(a)h=a;else{let I=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);h=await this.factory.getModifiedInputs(I)}let y=o.buildInputBag(h,this.factory.getSerializer(),f),C={...i.envs??{},...y},W=Mt(e.when,C);return jt(W)}},yn=(r,t)=>{let e=Object.fromEntries((r??[]).flatMap(i=>{let a=i.input.as||i.input.name;return a?[[a,i.value]]:[]})),n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!=null));return{...e,...n}};var yt=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 Wt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!X(t,this.config.defaultChain):!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)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.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)?X(t,this.config.defaultChain):O(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,u=t.startsWith(c.HttpProtocolPrefix)?qt(t):zt(i.identifier);if(this.resolver){let h=null;if(a==="hash")h=await this.resolver.getByHash(s,e);else if(a==="alias"){let y=`${i.chain}:${s}`;h=await this.resolver.getByAlias(y,e)||await this.resolver.getByAlias(s,e)}h&&(p=h.warp,l=h.registryInfo,o=h.brand)}else{let h=v(i.chain,this.adapters);if(a==="hash"){p=await h.builder().createFromTransactionHash(s,e);let y=await h.registry.getInfoByHash(s,e);l=y.registryInfo,o=y.brand}else if(a==="alias"){let y=await h.registry.getInfoByAlias(s,e);l=y.registryInfo,o=y.brand,y.registryInfo&&(p=await h.builder().createFromTransactionHash(y.registryInfo.hash,e))}}if(p&&p.meta&&(Wn(p,i.chain,l,i.identifier),p.meta.query=u?Gt(u):null),!p)return n;let d=p.chain||i.chain,g=this.adapters.find(h=>h.chainInfo.name.toLowerCase()===d.toLowerCase()),f=g?await new B(this.config,g,this.adapters).apply(p):p;return{match:!0,url:t,warp:f,chain:d,registryInfo:l,brand:o}}catch(a){return x.error("Error detecting warp link",a),n}}},Wn=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?It(null,"alias",e.alias):It(t,"hash",e?.hash??n))};var pe=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new et(e));return new rt(t)}getConfig(){return this.config}getResolver(){return this.resolver}createExecutor(t){return new mt(this.config,this.chains,t)}async detectWarp(t,e){return new Wt(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let h=await fetch(t);if(!h.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await h.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:g}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async h=>{await l.evaluateOutput(p,h)},resolvedInputs:g}}async createInscriptionTransaction(t,e){return await v(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return v(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=O(t,this.config.defaultChain);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return v(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return v(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return v(t,this.chains).explorer}getOutput(t){return v(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??R(e).index+1,p=await v(t,this.chains).output.getActionExecution(e,a,n);return p.next=ot(this.config,this.chains,e,a,p.output),p}async getRegistry(t){let e=v(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return v(t,this.chains).dataLoader}getWallet(t){return v(t,this.chains).wallet}get factory(){return new J(this.config,this.chains)}get index(){return new yt(this.config)}get linkBuilder(){return new z(this.config,this.chains)}createBuilder(t){return v(t,this.chains).builder()}createAbiBuilder(t){return v(t,this.chains).abiBuilder()}createBrandBuilder(t){return v(t,this.chains).brandBuilder()}createSerializer(t){return v(t,this.chains).serializer}resolveText(t){return at(t,this.config)}};var le=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()]))}};function vn(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(ce(t,n)!==i)return!1;return!0}function Cn(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?ce(t,i):i;return e}function ce(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}0&&(module.exports={BrowserCryptoProvider,CLOUD_WALLET_PROVIDERS,CacheTtl,EvmWalletChainNames,MultiversxWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpAssets,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainDisplayNames,WarpChainLogos,WarpChainName,WarpChainResolver,WarpClient,WarpCompositeResolver,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpPlatformName,WarpPlatforms,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildGeneratedFallbackWarpIdentifier,buildGeneratedSourceWarpIdentifier,buildInputsContext,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,checkWarpAssetBalance,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,doesWarpRequireWallet,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getChainDisplayName,getChainLogo,getCryptoProvider,getEventNameFromWarp,getGeneratedSourceWarpName,getLatestProtocolIdentifier,getMppFetch,getNextInfo,getNextInfoForStatus,getProviderConfig,getRandomBytes,getRandomHex,getRequiredAssetIds,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpIdentifierWithQuery,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isPlatformValue,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,matchesTrigger,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,removeWarpWalletFromConfig,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveInputs,resolveNextString,resolvePath,resolvePlatformValue,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,stampGeneratedWarpMeta,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
|
|
1
|
+
"use strict";var Xe=Object.create;var vt=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var tr=Object.getPrototypeOf,er=Object.prototype.hasOwnProperty;var rr=(r,t)=>{for(var e in t)vt(r,e,{get:t[e],enumerable:!0})},ge=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ye(t))!er.call(r,i)&&i!==e&&vt(r,i,{get:()=>t[i],enumerable:!(n=Ze(t,i))||n.enumerable});return r};var Q=(r,t,e)=>(e=r!=null?Xe(tr(r)):{},ge(t||!r||!r.__esModule?vt(e,"default",{value:r,enumerable:!0}):e,r)),nr=r=>ge(vt({},"__esModule",{value:!0}),r);var An={};rr(An,{BrowserCryptoProvider:()=>xt,CLOUD_WALLET_PROVIDERS:()=>fr,CacheTtl:()=>ie,EvmWalletChainNames:()=>dr,MultiversxWalletChainNames:()=>gr,NodeCryptoProvider:()=>At,WARP_LANGUAGES:()=>Tr,WarpAssets:()=>S,WarpBrandBuilder:()=>te,WarpBuilder:()=>ee,WarpCache:()=>gt,WarpCacheKey:()=>ft,WarpChainDisplayNames:()=>Ae,WarpChainLogos:()=>we,WarpChainName:()=>xe,WarpChainResolver:()=>et,WarpClient:()=>pe,WarpCompositeResolver:()=>rt,WarpConfig:()=>D,WarpConstants:()=>c,WarpExecutor:()=>mt,WarpFactory:()=>J,WarpIndex:()=>yt,WarpInputTypes:()=>m,WarpInterpolator:()=>B,WarpLinkBuilder:()=>z,WarpLinkDetecter:()=>Wt,WarpLogger:()=>x,WarpPlatformName:()=>Ft,WarpPlatforms:()=>Ot,WarpProtocolVersions:()=>j,WarpSerializer:()=>w,WarpTypeRegistry:()=>le,WarpValidator:()=>ct,address:()=>on,applyOutputToMessages:()=>Pt,asset:()=>Yt,biguint:()=>an,bool:()=>sn,buildGeneratedFallbackWarpIdentifier:()=>Le,buildGeneratedSourceWarpIdentifier:()=>_r,buildInputsContext:()=>lt,buildMappedOutput:()=>_,buildNestedPayload:()=>Te,bytesToBase64:()=>wr,bytesToHex:()=>Ie,checkWarpAssetBalance:()=>Zr,cleanWarpIdentifier:()=>K,createAuthHeaders:()=>Tt,createAuthMessage:()=>bt,createCryptoProvider:()=>Sr,createDefaultWalletProvider:()=>Xr,createHttpAuthHeaders:()=>Mr,createSignableMessage:()=>$e,createWarpI18nText:()=>Rr,createWarpIdentifier:()=>It,doesWarpRequireWallet:()=>br,evaluateOutputCommon:()=>Qt,evaluateWhenCondition:()=>jt,extractCollectOutput:()=>Z,extractIdentifierInfoFromUrl:()=>X,extractPromptOutput:()=>Kt,extractQueryStringFromIdentifier:()=>zt,extractQueryStringFromUrl:()=>qt,extractResolvedInputValues:()=>V,extractWarpSecrets:()=>Pr,findWarpAdapterForChain:()=>v,getChainDisplayName:()=>mr,getChainLogo:()=>yr,getCryptoProvider:()=>Ht,getEventNameFromWarp:()=>Wr,getGeneratedSourceWarpName:()=>Fe,getLatestProtocolIdentifier:()=>nt,getMppFetch:()=>Zt,getNextInfo:()=>ot,getNextInfoForStatus:()=>pt,getProviderConfig:()=>kr,getRandomBytes:()=>Ut,getRandomHex:()=>Dt,getRequiredAssetIds:()=>He,getWalletFromConfigOrFail:()=>ir,getWarpActionByIndex:()=>T,getWarpBrandLogoUrl:()=>vr,getWarpChainAssetLogoUrl:()=>Cr,getWarpChainInfoLogoUrl:()=>xr,getWarpIdentifierWithQuery:()=>Or,getWarpInfoFromIdentifier:()=>O,getWarpPrimaryAction:()=>R,getWarpWalletAddress:()=>fe,getWarpWalletAddressFromConfig:()=>P,getWarpWalletExternalId:()=>ye,getWarpWalletExternalIdFromConfig:()=>We,getWarpWalletExternalIdFromConfigOrFail:()=>or,getWarpWalletMnemonic:()=>me,getWarpWalletMnemonicFromConfig:()=>sr,getWarpWalletPrivateKey:()=>he,getWarpWalletPrivateKeyFromConfig:()=>ar,hasInputPrefix:()=>Vr,hex:()=>pn,initializeWalletCache:()=>Kr,isEqualWarpIdentifier:()=>Nr,isGeneratedSourcePrivateIdentifier:()=>Qr,isPlatformValue:()=>Be,isWarpActionAutoExecute:()=>wt,isWarpI18nText:()=>Er,isWarpWalletReadOnly:()=>pr,matchesTrigger:()=>Cn,mergeNestedPayload:()=>Jt,normalizeAndValidateMnemonic:()=>ur,normalizeMnemonic:()=>ve,option:()=>ln,parseOutputOutIndex:()=>Ne,parseSignedMessage:()=>qr,parseWarpQueryStringToObject:()=>Gt,removeWarpChainPrefix:()=>Fr,removeWarpWalletFromConfig:()=>cr,replacePlaceholders:()=>H,replacePlaceholdersInWhenExpression:()=>Mt,resolveInputs:()=>xn,resolveNextString:()=>_t,resolvePath:()=>ce,resolvePlatformValue:()=>Xt,resolveWarpText:()=>at,safeWindow:()=>Vt,setCryptoProvider:()=>Ar,setWarpWalletInConfig:()=>lr,shiftBigintBy:()=>it,splitInput:()=>St,stampGeneratedWarpMeta:()=>Jr,string:()=>Yr,struct:()=>un,testCryptoAvailability:()=>Ir,toInputPayloadValue:()=>Ee,toPreviewText:()=>kt,tuple:()=>cn,uint16:()=>en,uint32:()=>rn,uint64:()=>nn,uint8:()=>tn,validateMnemonicLength:()=>Ce,validateSignedMessage:()=>jr,vector:()=>dn,withAdapterFallback:()=>hr});module.exports=nr(An);var et=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var rt=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var ir=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},fe=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>fe(r.user?.wallets?.[t]||null),he=r=>r?typeof r=="string"?r:r.privateKey||null:null,me=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ye=r=>r?typeof r=="string"?r:r.externalId||null:null,ar=(r,t)=>he(r.user?.wallets?.[t]||null)?.trim()||null,sr=(r,t)=>me(r.user?.wallets?.[t]||null)?.trim()||null,We=(r,t)=>ye(r.user?.wallets?.[t]||null)?.trim()||null,or=(r,t)=>{let e=We(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},pr=r=>typeof r=="string",lr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},cr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},ve=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Ce=(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`)},ur=(r,t=24)=>{let e=ve(r);return Ce(e,t),e};var xe=(g=>(g.Multiversx="multiversx",g.Claws="claws",g.Sui="sui",g.Ethereum="ethereum",g.Base="base",g.Arbitrum="arbitrum",g.Polygon="polygon",g.Somnia="somnia",g.Tempo="tempo",g.Fastset="fastset",g.Solana="solana",g.Near="near",g))(xe||{}),Ft=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Ft||{}),Ot=Object.values(Ft),dr=["ethereum","base","arbitrum","polygon","somnia","tempo"],gr=["multiversx","claws"],fr=["coinbase","privy","gaupa"],c={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(r.config,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"}},m={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"},Vt=typeof window<"u"?window:{open:()=>{}};var j={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},D={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${j.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${j.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 hr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Ct="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",S={baseUrl:Ct,chainLogo:r=>`${Ct}/chains/logos/${r}`,tokenLogo:r=>`${Ct}/tokens/logos/${r}`,walletLogo:r=>`${Ct}/wallets/logos/${r}`},Ae={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},mr=r=>Ae[r]??r.charAt(0).toUpperCase()+r.slice(1),we={ethereum:{light:S.chainLogo("ethereum-white.svg"),dark:S.chainLogo("ethereum-black.svg")},base:{light:S.chainLogo("base-white.svg"),dark:S.chainLogo("base-black.svg")},arbitrum:S.chainLogo("arbitrum.svg"),polygon:S.chainLogo("polygon.svg"),somnia:S.chainLogo("somnia.png"),tempo:{light:S.chainLogo("tempo-white.svg"),dark:S.chainLogo("tempo-black.svg")},multiversx:S.chainLogo("multiversx.svg"),claws:S.chainLogo("claws.png"),sui:S.chainLogo("sui.svg"),solana:S.chainLogo("solana.svg"),near:{light:S.chainLogo("near-white.svg"),dark:S.chainLogo("near-black.svg")},fastset:{light:S.chainLogo("fastset-white.svg"),dark:S.chainLogo("fastset-black.svg")}},yr=(r,t="dark")=>{let e=we[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var Wr=(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 Lt=(r,t)=>r[t]??r.default??Object.values(r)[0],vr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:Lt(r.logo,e)},Cr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Lt(r.logoUrl,e)},xr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Lt(r.logoUrl,e)};var xt=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}},At=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"}`)}}},q=null;function Ht(){if(q)return q;if(typeof window<"u"&&window.crypto)return q=new xt,q;if(typeof process<"u"&&process.versions?.node)return q=new At,q;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Ar(r){q=r}async function Ut(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Ht()).getRandomBytes(r)}function Ie(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 wr(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 Dt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Ut(r/2,t);return Ie(e)}async function Ir(){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 Ut(16),r.randomBytes=!0}catch{}return r}function Sr(){return Ht()}var Pr=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 v=(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},nt=r=>{if(r==="warp")return`warp:${j.Warp}`;if(r==="brand")return`brand:${j.Brand}`;if(r==="abi")return`abi:${j.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},T=(r,t)=>r?.actions[t-1],R=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","compute","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},wt=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=R(t);return r===e}return!0},it=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},kt=(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},H=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),Mt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),br=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===c.Source.UserWallet||n.default===`{{${c.Globals.UserWallet.Placeholder}}}`||n.default===`{{${c.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},jt=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 Tr={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"},at=(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""},Er=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Rr=r=>r;var K=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,Nr=(r,t)=>!r||!t?!1:K(r)===K(t),It=(r,t,e)=>{let n=K(e);if(t===c.IdentifierType.Alias)return c.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+n},O=(r,t)=>{let e=t||c.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=K(n),a=i.split("?")[0],s=Se(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:c.IdentifierType.Hash,identifier:i,identifierBase:a};if(s.length===2&&/^[a-zA-Z0-9]{62}$/.test(s[0])&&/^[a-zA-Z0-9]{2}$/.test(s[1]))return null;if(s.length===3){let[p,l,o]=s;if(l===c.IdentifierType.Alias||l===c.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:l,identifier:u,identifierBase:o}}}if(s.length===2){let[p,l]=s;if(p===c.IdentifierType.Alias||p===c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l;return{chain:e,type:p,identifier:o,identifierBase:l}}}if(s.length===2){let[p,l]=s;if(p!==c.IdentifierType.Alias&&p!==c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l,u=Br(l,p)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:l}}}return{chain:e,type:c.IdentifierType.Alias,identifier:i,identifierBase:a}},X=(r,t)=>{let e=new URL(r),i=e.searchParams.get(c.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return O(a,t)},Br=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,$r=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Se=r=>{let t=$r(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Se(a);return[i,...s]},qt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},zt=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},Gt=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},Fr=(r,t)=>{let e=O(r,t);return(e?e.identifierBase:K(r)).trim()},Or=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var St=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Vr=r=>{let t=new Set(Object.values(m));if(!r.includes(c.ArgParamsSeparator))return!1;let e=St(r)[0];return t.has(e)};var Pt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=at(a,e);return[i,H(s,t)]});return Object.fromEntries(n)};var Pe=Q(require("qr-code-styling"),1);var z=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!X(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||D.DefaultClientUrl(this.config.env),a=v(t,this.adapters),s=e===c.IdentifierType.Alias?n:e+c.IdentifierParamSeparator+n,p=a.chainInfo.name+c.IdentifierParamSeparator+s,l=encodeURIComponent(p);return D.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${c.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=O(t,this.config.defaultChain);if(!e)return null;let n=v(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=v(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Pe.default({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},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 be="https://",_t=(r,t)=>r?typeof r=="string"?t==="success"?r:null:r[t]||null:null,ot=(r,t,e,n,i)=>{let a=T(e,n)?.next||e.next||null,s=_t(a,"success");if(!s)return null;if(s.startsWith(be))return[{identifier:null,url:s}];let[p,l]=s.split("?");if(!l){let C=H(p,{...e.vars,...i});return[{identifier:C,url:st(t,C,r)}]}let o=l.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let C=H(l,{...e.vars,...i}),W=C?`${p}?${C}`:p;return[{identifier:W,url:st(t,W,r)}]}let u=o[0];if(!u)return[];let d=u.match(/{{([^[]+)\[\]/),g=d?d[1]:null;if(!g||i[g]===void 0)return[];let f=Array.isArray(i[g])?i[g]:[i[g]];if(f.length===0)return[];let h=o.filter(C=>C.includes(`{{${g}[]`)).map(C=>{let W=C.match(/\[\](\.[^}]+)?}}/),I=W&&W[1]||"";return{placeholder:C,field:I?I.slice(1):"",regex:new RegExp(C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(C=>{let W=l;for(let{regex:k,field:A}of h){let $=A?Lr(C,A):C;if($==null)return null;W=W.replace(k,$)}if(W.includes("{{")||W.includes("}}"))return null;let I=W?`${p}?${W}`:p;return{identifier:I,url:st(t,I,r)}}).filter(C=>C!==null)},pt=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=T(e,n)?.next||e.next||null,l=_t(p,s);if(!l)return null;if(l.startsWith(be))return[{identifier:null,url:l}];let[o,u]=l.split("?");if(!u){let f=H(o,{...e.vars,...i});return[{identifier:f,url:st(t,f,r)}]}let d=H(u,{...e.vars,...i}),g=d?`${o}?${d}`:o;return[{identifier:g,url:st(t,g,r)}]},st=(r,t,e)=>{let[n,i]=t.split("?"),a=O(n,e.defaultChain)||{chain:c.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=v(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let p=new z(e,r).build(s.chainInfo.name,a.type,a.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(/\/\?/,"?")},Lr=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var G=class G{static debug(...t){G.isTestEnv||console.debug(...t)}static info(...t){G.isTestEnv||console.info(...t)}static warn(...t){G.isTestEnv||console.warn(...t)}static error(...t){G.isTestEnv||console.error(...t)}};G.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=G;function Te(r,t,e){return r.startsWith(c.Position.Payload)?r.slice(c.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Jt(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]=Jt(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 V(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function _(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=Ee(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let s=Te(n.input.position,i,a);e=Jt(e,s)}else e[i]=a}),e}function lt(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let u=o;if("identifier"in u&&"amount"in u){let d=String(u.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(u.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var Re=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(c.Transform.Prefix))continue;let l=Ne(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...u]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},Z=async(r,t,e,n,i,a)=>{let s=(d,g)=>g.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:u}=Re(r,e,p);return{values:{string:l,native:o,mapped:_(n,i)},output:await Qt(r,u,t,e,n,i,a)}},Qt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Hr(p,r,n,i,a),p=await Ur(r,p,e,i,a,s.transform?.runner||null),p},Hr=(r,t,e,n,i)=>{let a={...r},s=T(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],u=s.findIndex(g=>g.as===o||g.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Ur=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(c.Transform.Prefix)).map(([o,u])=>({key:o,code:u.substring(c.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:Dr(e),inputs:lt(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,l),l[o]=s[o]}catch(d){x.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},Dr=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},Kt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=Re(r,e,s),u=await Qt(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:l,mapped:_(n,i)},output:u}},Ne=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 Be=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Ot.some(t=>t in r),Xt=(r,t)=>{if(!Be(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var kr=(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 $e(r,t,e,n=5){let i=await Dt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function bt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return $e(r,i,e,5)}function Tt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Mr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await bt(r,e,n),p=await t(i);return Tt(r,p,a,s)}function jr(r){let t=new Date(r).getTime();return Date.now()<t}function qr(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 Fe=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",zr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Oe=(r,t=24)=>{let e=zr(r);return e?e.slice(0,t):"action"},Ve=r=>{let t=3735928559^r.length,e=1103547991^r.length;for(let a=0;a<r.length;a++){let s=r.charCodeAt(a);t=Math.imul(t^s,2654435761),e=Math.imul(e^s,1597334677)}t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909);let n=(e>>>0).toString(16).padStart(8,"0"),i=(t>>>0).toString(16).padStart(8,"0");return`${n}${i}`.slice(0,12)},Gr=r=>{let t=(r||"").trim();if(!t)return"";try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"").toLowerCase()||"/";return`${e.origin.toLowerCase()}${n}`}catch{return t.toLowerCase()}},_r=(r,t,e)=>{let n=Oe((e||t||"").trim()||"action"),i=`${r.type}|${Gr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Ve(i);return`private_src_${n}_${a}`},Le=r=>{let t=Fe(r),e=Oe(t),n=Ve(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Jr=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Le(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},Qr=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));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 Xr(r,t,e){return null}var He=(r,t)=>{let e=null;try{e=R(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},Zr=async(r,t,e,n)=>{try{let i=v(e,n),a=He(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};var Et=require("mppx/client");async function Zt(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return x.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),Et.Mppx.create({methods:[(0,Et.tempo)({account:e})],polyfill:!1}).fetch}return fetch}var Ue={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=Ue[t]??t,t===m.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(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===m.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,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${c.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}if(t===m.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),a=n.substring(0,i),s=e.map(l=>{let o=l.indexOf(c.ArgParamsSeparator),u=l.substring(o+1);return a.startsWith(m.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=a.startsWith(m.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+a+c.ArgParamsSeparator+s.join(p)}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):m.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=Ue[e[0]]??e[0],i=e.slice(1).join(c.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(c.ArgParamsSeparator);return[m.Option+c.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(c.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(m.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(s+c.ArgParamsSeparator+d)[1]);return[m.Vector+c.ArgParamsSeparator+s,u]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),p=i.split(c.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${c.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(c.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,g]=o;p[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${g}`)[1]}}),[n,p]}else{if(n===m.String)return[n,i];if(n===m.Uint8||n===m.Uint16||n===m.Uint32)return[n,Number(i)];if(n===m.Uint64||n===m.Uint128||n===m.Uint256||n===m.Biguint)return[n,BigInt(i||0)];if(n===m.Bool)return[n,i==="true"];if(n===m.Address)return[n,i];if(n===m.Hex)return[n,i];if(n===m.Asset){let[a,s]=i.split(c.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${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"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var Yr=r=>new w().nativeToString(m.String,r),tn=r=>new w().nativeToString(m.Uint8,r),en=r=>new w().nativeToString(m.Uint16,r),rn=r=>new w().nativeToString(m.Uint32,r),nn=r=>new w().nativeToString(m.Uint64,r),an=r=>new w().nativeToString(m.Biguint,r),sn=r=>new w().nativeToString(m.Bool,r),on=r=>new w().nativeToString(m.Address,r),Yt=r=>new w().nativeToString(m.Asset,r),pn=r=>new w().nativeToString(m.Hex,r),ln=(r,t)=>{if(t===null)return m.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+a},cn=(...r)=>new w().nativeToString(m.Tuple,r),un=r=>new w().nativeToString(m.Struct,r),dn=r=>new w().nativeToString(m.Vector,r);var De=Q(require("ajv"),1);var te=class{constructor(t){this.pendingBrand={protocol:nt("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||D.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new De.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var ke=Q(require("ajv"),1);var ct=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}=R(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,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||D.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new ke.default({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ee=class{constructor(t){this.config=t;this.pendingWarp={protocol:nt("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 kt(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 ct(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
+
`))}};var b=require("fs"),tt=require("path");var re="$bigint:",Rt=(r,t)=>typeof t=="bigint"?re+t.toString():t,Y=(r,t)=>typeof t=="string"&&t.startsWith(re)?BigInt(t.slice(re.length)):t;var Nt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,tt.resolve)(n):(0,tt.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,b.existsSync)(this.cacheDir)||(0,b.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,tt.join)(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!(0,b.existsSync)(e))return null;let n=(0,b.readFileSync)(e,"utf-8"),i=JSON.parse(n,Y);return i.expiresAt!==null&&Date.now()>i.expiresAt?((0,b.unlinkSync)(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);(0,b.writeFileSync)(a,JSON.stringify(i,Rt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);(0,b.existsSync)(e)&&(0,b.unlinkSync)(e)}catch{}}async keys(t){try{let e=(0,b.readdirSync)(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{(0,b.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,b.unlinkSync)((0,tt.join)(this.cacheDir,e))})}catch{}}};var ut=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,Y);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,Rt))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var U=class U{constructor(t,e){}async get(t){let e=U.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(U.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;U.cache.set(t,{value:e,expiresAt:i})}async delete(t){U.cache.delete(t)}async keys(t){let e=Array.from(U.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){U.cache.clear()}};U.cache=new Map;var dt=U;var Me=require("fs"),ne=require("path");var Bt=class{constructor(t,e){let n=e?.path?(0,ne.resolve)(e.path):(0,ne.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,Me.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,Y)))}catch(e){return x.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var ie={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},ft={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}`,AccountNfts:(r,t,e,n,i)=>`account-nfts:${r}:${t}:${e}:${n}:${i}`},gt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new ut(t,e):e?.type==="memory"?new dt(t,e):e?.type==="static"?new Bt(t,e):e?.type==="filesystem"?new Nt(t,e):typeof window<"u"&&window.localStorage?new ut(t,e):new dt(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var ht={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},ae={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},se=(r,t,e)=>{let n=r.find(a=>a.input.as===t||a.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},oe=r=>{try{return JSON.parse(r)}catch{return null}},gn=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:u}=await bt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(Tt(n,d,o,u)).forEach(([g,f])=>s.set(g,f))}let p=se(e.resolvedInputs,ht.Headers,i);if(p){let l=oe(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},fn=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===ae.Get){let s=se(e.resolvedInputs,ht.Queries,i);if(s){let p=oe(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&l.searchParams.set(o,String(u))),a=l.toString()}}}return a},hn=(r,t,e,n,i)=>{if(r===ae.Get)return;let a=se(t.resolvedInputs,ht.Payload,n);if(a&&oe(a)!==null)return a;let{[ht.Payload]:s,[ht.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},je=async(r,t,e,n,i,a,s,p)=>{let l=t.method||ae.Get,o=await gn(r,t,e,n,a,p),u=fn(r,t,e,l,a),d=hn(l,e,i,a,s);return{url:u,method:l,headers:o,body:d}};var B=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e),i=await this.applyGlobals(n);return e.envs?this.applyEnvs(i,e.envs):i}applyEnvs(t,e){if(!e||Object.keys(e).length===0)return t;let n=JSON.stringify(t);for(let[i,a]of Object.entries(e)){if(a==null)continue;let s=JSON.stringify(String(a)).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${mn(i)}\\}\\}`,"g"),s)}return JSON.parse(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=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,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,f=e.queries?.[o]??null??d;f!=null&&a(s,f)}else if(p.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Env.length+1),[o,u]=l.split(c.ArgCompositeSeparator),g={...this.config.vars,...e.envs}?.[o];g!=null&&a(s,g)}else p===c.Source.UserWallet&&n?a(s,n):a(s,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 a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.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 a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.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 a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return H(a,s)}applyGlobalsToText(t){if(!Object.values(c.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(c.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=v(l,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let l=p;l&&typeof l=="object"&&"identifier"in l&&"amount"in l&&(i[`primary.${s}.token`]=String(l.identifier),i[`primary.${s}.amount`]=String(l.amount))}}),i}},mn=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var yn=["collect","compute","mcp","state","mount","unmount"],J=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 gt(t.env,t.cache)}getSerializer(){return this.serializer}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(ft.WarpExecutable(t,e||"",n))||[];return V(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(ft.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=T(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=v(s.name,this.adapters),l=new B(this.config,p,this.adapters),o=await l.apply(t,i),u=T(o,e),{action:d,index:g}=R(o),f=this.getStringTypedInputs(d,n),h=await this.getResolvedInputs(s.name,d,f,l,i.queries),y=await this.getModifiedInputs(h),C=[],W=[];g===e-1?(C=h,W=y):this.requiresPayloadInputs(u)&&(C=await this.resolveActionInputs(s.name,u,n,l,i.queries),W=await this.getModifiedInputs(C));let I=W.find(E=>E.input.position==="receiver"||E.input.position==="destination")?.value,k=this.getDestinationFromAction(u),A=I?this.serializer.stringToNative(I)[1]:k;if(A&&(A=l.applyInputs(A,W,this.serializer,y)),!A&&!yn.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let $=this.getPreparedArgs(u,W);$=$.map(E=>l.applyInputs(E,W,this.serializer,y));let L=W.find(E=>E.input.position==="value")?.value||null,N="value"in u?u.value:null,F=L?.split(c.ArgParamsSeparator)[1]||N||"0",M=l.applyInputs(F,W,this.serializer,y),qe=BigInt(M),ze=W.filter(E=>E.input.position==="transfer"&&E.value).map(E=>E.value),Ge=[...("transfers"in u?u.transfers:[])||[],...ze||[]].map(E=>{let $t=l.applyInputs(E,W,this.serializer,y),Ke=$t.startsWith(`asset${c.ArgParamsSeparator}`)?$t:`asset${c.ArgParamsSeparator}${$t}`;return this.serializer.stringToNative(Ke)[1]}),_e=W.find(E=>E.input.position==="data")?.value,Je="data"in u?u.data||"":null,ue=_e||Je||null,Qe=ue?l.applyInputs(ue,W,this.serializer,y):null,de={adapter:p,warp:o,chain:s,action:e,destination:A,args:$,value:qe,transfers:Ge,data:Qe,resolvedInputs:W};return await this.cache.set(ft.WarpExecutable(this.config.env,o.meta?.hash||"",e),de.resolvedInputs,ie.OneWeek),de}async getChainInfoForWarp(t,e){if(t.chain)return v(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,a)=>{let s=n[a];return!s||i.includes(c.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(u=>i.applyInputs(u,[],this.serializer)),l=await Promise.all(p.map(u=>this.preprocessInput(t,u))),o=(u,d)=>{if(u.source===c.Source.UserWallet){let C=P(this.config,t);return C?this.serializer.nativeToString("address",C):null}if(u.source==="hidden"){if(u.default===void 0)return null;let C=i?i.applyInputs(String(u.default),[],this.serializer):String(u.default);return this.serializer.nativeToString(u.type,C)}if(l[d])return l[d];let g=u.as||u.name,f=a?.[g],h=this.url.searchParams.get(g),y=f||h;return y?this.serializer.nativeToString(u.type,String(y)):null};return s.map((u,d)=>{let g=o(u,d),f=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:g||(f!==void 0?this.serializer.nativeToString(u.type,f):null)}})}async resolveInputsFromQuery(t,e,n){let i=T(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=v(a.name,this.adapters),p=new B(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],p,n)}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i,a){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i,a)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=it(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=it(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let a=i.input.modifier.substring(c.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=lt(t,this.serializer,n,i),l=await s.run(a,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}async preprocessInput(t,e){try{let[n,i]=St(e),a=v(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(c.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=it(p,o.decimals);return Yt({...o,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:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.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(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==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 a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return v(s,this.adapters).chainInfo}};var mt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new J(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:g}=R(t);for(let f=1;f<=t.actions.length;f++){let h=T(t,f);if(!wt(h,t))continue;let{tx:y,chain:C,immediateExecution:W,executable:I}=await this.executeAction(t,f,e,u);y&&i.push(y),C&&(a=C),W&&s.push(W),I&&f===g+1&&I.resolvedInputs&&(p=V(I.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let f=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(f))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=T(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Vt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,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 s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);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:s};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:s};{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:s}}if(a.type==="compute"){let o=await this.executeCompute(s);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:s};{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:s}}if(a.type==="state"||a.type==="mount"||a.type==="unmount")return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="mcp"){let o=await this.executeMcp(s);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:s};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:s};{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:s}}}let p=v(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.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:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=v(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!wt(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let f=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(u.length===0){let f=t.meta?.query;f&&Object.keys(f).length>0&&(u=await this.factory.resolveInputsFromQuery(t,o,f))}let d=await i.output.getActionExecution(t,o,l.tx,u),g=Wn(u,d.output);return d.next=pt(this.config,this.adapters,t,o,g,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(d.values),result:d})),d}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action),a=this.factory.getSerializer(),s=_(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,s,e);let{values:p,output:l}=await Z(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async executeCompute(t){let e=P(this.config,t.chain.name),n=this.factory.getSerializer(),i=_(t.resolvedInputs,n),{values:a,output:s}=await Z(t.warp,i,t.action,t.resolvedInputs,n,this.config);return this.buildCollectResult(t,e,"success",a,s)}async doHttpRequest(t,e,n,i,a){let s=new B(this.config,v(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await je(s,e,t,n,i,p,a,async g=>await this.callHandler(()=>this.handlers?.onSignRequest?.(g)));x.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:u,body:d});try{let g={method:o,headers:u,body:d},h=await(await Zt(this.adapters))(l,g);x.debug("Collect response status",{status:h.status});let y=await h.json();x.debug("Collect response content",{content:y});let{values:C,output:W}=await Z(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),h.ok?"success":"error",C,W,y)}catch(g){x.error("WarpActionExecutor: Error executing collect",g);let f=V(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:g},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let f=V(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:f}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let h=V(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:h}}let p=this.factory.getSerializer(),l=new B(this.config,v(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()),g={};o.headers&&Object.entries(o.headers).forEach(([f,h])=>{let y=l.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());g[f]=y}),x.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:g});try{let f=new s(new URL(u),{requestInit:{headers:g}}),h=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await h.connect(f);let y={};t.resolvedInputs.forEach(({input:A,value:$})=>{if($&&A.position&&typeof A.position=="string"&&A.position.startsWith("payload:")){let L=A.position.replace("payload:",""),[N,F]=p.stringToNative($);if(N==="string")y[L]=String(F);else if(N==="bool")y[L]=!!F;else if(N==="uint8"||N==="uint16"||N==="uint32"||N==="uint64"||N==="uint128"||N==="uint256"||N==="biguint"){let M=Number(F);y[L]=(Number.isInteger(M),M)}else y[L]=F}}),e&&Object.assign(y,e);let C=await h.callTool({name:d,arguments:y});await h.close();let W;if(C.content&&C.content.length>0){let A=C.content[0];if(A.type==="text")try{W=JSON.parse(A.text)}catch{W=A.text}else A.type,W=A}else W=C;let{values:I,output:k}=await Z(t.warp,W,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",I,k,C)}catch(f){x.error("WarpExecutor: Error executing MCP",f);let h=V(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:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}buildCollectResult(t,e,n,i,a,s){let p=pt(this.config,this.adapters,t.warp,t.action,a,n),l=V(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:Pt(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=v(s.name,this.adapters),l=new B(this.config,p,this.adapters),o=await l.apply(t,a),u=T(o,n),{action:d}=R(o),g=this.factory.getStringTypedInputs(d,i),f=await this.factory.getResolvedInputs(s.name,d,g,l,a.queries),h=await this.factory.getModifiedInputs(f),y=h;if(e.inputs&&e.inputs.length>0){let F=this.factory.getStringTypedInputs(e,i),M=await this.factory.getResolvedInputs(s.name,e,F,l,a.queries);y=await this.factory.getModifiedInputs(M)}let C=Xt(u.prompt,this.config.platform),W=l.applyInputs(C,y,this.factory.getSerializer(),h),I=V(y),k=P(this.config,s.name),A=this.factory.getSerializer(),{values:$,output:L}=await Kt(o,W,n,y,A,this.config),N=y.find(F=>F.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:k,txHash:null,tx:null,next:ot(this.config,this.adapters,o,n,L),values:$,output:L,messages:Pt(o,L,this.config),destination:N,resolvedInputs:I}}catch(s){return x.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:pt(this.config,this.adapters,t,n,{},"error"),values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=v(p.name,this.adapters),o=new B(this.config,l,this.adapters),{action:u}=R(t),d=this.factory.getStringTypedInputs(u,n),g=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),f=await this.factory.getModifiedInputs(g),h;if(a)h=a;else{let I=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);h=await this.factory.getModifiedInputs(I)}let y=o.buildInputBag(h,this.factory.getSerializer(),f),C={...i.envs??{},...y},W=Mt(e.when,C);return jt(W)}},Wn=(r,t)=>{let e=Object.fromEntries((r??[]).flatMap(i=>{let a=i.input.as||i.input.name;return a?[[a,i.value]]:[]})),n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!=null));return{...e,...n}};var yt=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 Wt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!X(t,this.config.defaultChain):!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)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.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)?X(t,this.config.defaultChain):O(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,u=t.startsWith(c.HttpProtocolPrefix)?qt(t):zt(i.identifier);if(this.resolver){let h=null;if(a==="hash")h=await this.resolver.getByHash(s,e);else if(a==="alias"){let y=`${i.chain}:${s}`;h=await this.resolver.getByAlias(y,e)||await this.resolver.getByAlias(s,e)}h&&(p=h.warp,l=h.registryInfo,o=h.brand)}else{let h=v(i.chain,this.adapters);if(a==="hash"){p=await h.builder().createFromTransactionHash(s,e);let y=await h.registry.getInfoByHash(s,e);l=y.registryInfo,o=y.brand}else if(a==="alias"){let y=await h.registry.getInfoByAlias(s,e);l=y.registryInfo,o=y.brand,y.registryInfo&&(p=await h.builder().createFromTransactionHash(y.registryInfo.hash,e))}}if(p&&p.meta&&(vn(p,i.chain,l,i.identifier),p.meta.query=u?Gt(u):null),!p)return n;let d=p.chain||i.chain,g=this.adapters.find(h=>h.chainInfo.name.toLowerCase()===d.toLowerCase()),f=g?await new B(this.config,g,this.adapters).apply(p):p;return{match:!0,url:t,warp:f,chain:d,registryInfo:l,brand:o}}catch(a){return x.error("Error detecting warp link",a),n}}},vn=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?It(null,"alias",e.alias):It(t,"hash",e?.hash??n))};var pe=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new et(e));return new rt(t)}getConfig(){return this.config}getResolver(){return this.resolver}createExecutor(t){return new mt(this.config,this.chains,t)}async detectWarp(t,e){return new Wt(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let h=await fetch(t);if(!h.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await h.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:g}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async h=>{await l.evaluateOutput(p,h)},resolvedInputs:g}}async createInscriptionTransaction(t,e){return await v(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return v(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=O(t,this.config.defaultChain);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return v(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return v(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return v(t,this.chains).explorer}getOutput(t){return v(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??R(e).index+1,p=await v(t,this.chains).output.getActionExecution(e,a,n);return p.next=ot(this.config,this.chains,e,a,p.output),p}async getRegistry(t){let e=v(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return v(t,this.chains).dataLoader}getWallet(t){return v(t,this.chains).wallet}get factory(){return new J(this.config,this.chains)}get index(){return new yt(this.config)}get linkBuilder(){return new z(this.config,this.chains)}createBuilder(t){return v(t,this.chains).builder()}createAbiBuilder(t){return v(t,this.chains).abiBuilder()}createBrandBuilder(t){return v(t,this.chains).brandBuilder()}createSerializer(t){return v(t,this.chains).serializer}resolveText(t){return at(t,this.config)}};var le=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()]))}};function Cn(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(ce(t,n)!==i)return!1;return!0}function xn(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?ce(t,i):i;return e}function ce(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}0&&(module.exports={BrowserCryptoProvider,CLOUD_WALLET_PROVIDERS,CacheTtl,EvmWalletChainNames,MultiversxWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpAssets,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainDisplayNames,WarpChainLogos,WarpChainName,WarpChainResolver,WarpClient,WarpCompositeResolver,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpPlatformName,WarpPlatforms,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildGeneratedFallbackWarpIdentifier,buildGeneratedSourceWarpIdentifier,buildInputsContext,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,checkWarpAssetBalance,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,doesWarpRequireWallet,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getChainDisplayName,getChainLogo,getCryptoProvider,getEventNameFromWarp,getGeneratedSourceWarpName,getLatestProtocolIdentifier,getMppFetch,getNextInfo,getNextInfoForStatus,getProviderConfig,getRandomBytes,getRandomHex,getRequiredAssetIds,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpIdentifierWithQuery,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isPlatformValue,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,matchesTrigger,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,removeWarpWalletFromConfig,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveInputs,resolveNextString,resolvePath,resolvePlatformValue,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,stampGeneratedWarpMeta,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 rt=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var nt=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var vr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Pe=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>Pe(r.user?.wallets?.[t]||null),be=r=>r?typeof r=="string"?r:r.privateKey||null:null,Te=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Ee=r=>r?typeof r=="string"?r:r.externalId||null:null,Cr=(r,t)=>be(r.user?.wallets?.[t]||null)?.trim()||null,xr=(r,t)=>Te(r.user?.wallets?.[t]||null)?.trim()||null,Re=(r,t)=>Ee(r.user?.wallets?.[t]||null)?.trim()||null,Ar=(r,t)=>{let e=Re(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},wr=r=>typeof r=="string",Ir=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},Sr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},Ne=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Be=(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`)},Pr=(r,t=24)=>{let e=Ne(r);return Be(e,t),e};var $e=(g=>(g.Multiversx="multiversx",g.Claws="claws",g.Sui="sui",g.Ethereum="ethereum",g.Base="base",g.Arbitrum="arbitrum",g.Polygon="polygon",g.Somnia="somnia",g.Tempo="tempo",g.Fastset="fastset",g.Solana="solana",g.Near="near",g))($e||{}),Ht=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Ht||{}),Ut=Object.values(Ht),Er=["ethereum","base","arbitrum","polygon","somnia","tempo"],Rr=["multiversx","claws"],Nr=["coinbase","privy","gaupa"],c={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(r.config,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"}},m={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"},Dt=typeof window<"u"?window:{open:()=>{}};var q={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},k={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${q.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${q.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 Or=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var it="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",S={baseUrl:it,chainLogo:r=>`${it}/chains/logos/${r}`,tokenLogo:r=>`${it}/tokens/logos/${r}`,walletLogo:r=>`${it}/wallets/logos/${r}`},Fe={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},Lr=r=>Fe[r]??r.charAt(0).toUpperCase()+r.slice(1),Oe={ethereum:{light:S.chainLogo("ethereum-white.svg"),dark:S.chainLogo("ethereum-black.svg")},base:{light:S.chainLogo("base-white.svg"),dark:S.chainLogo("base-black.svg")},arbitrum:S.chainLogo("arbitrum.svg"),polygon:S.chainLogo("polygon.svg"),somnia:S.chainLogo("somnia.png"),tempo:{light:S.chainLogo("tempo-white.svg"),dark:S.chainLogo("tempo-black.svg")},multiversx:S.chainLogo("multiversx.svg"),claws:S.chainLogo("claws.png"),sui:S.chainLogo("sui.svg"),solana:S.chainLogo("solana.svg"),near:{light:S.chainLogo("near-white.svg"),dark:S.chainLogo("near-black.svg")},fastset:{light:S.chainLogo("fastset-white.svg"),dark:S.chainLogo("fastset-black.svg")}},Hr=(r,t="dark")=>{let e=Oe[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var kr=(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 xt=(r,t)=>r[t]??r.default??Object.values(r)[0],jr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:xt(r.logo,e)},qr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return xt(r.logoUrl,e)},zr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return xt(r.logoUrl,e)};var At=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}},wt=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"}`)}}},M=null;function kt(){if(M)return M;if(typeof window<"u"&&window.crypto)return M=new At,M;if(typeof process<"u"&&process.versions?.node)return M=new wt,M;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function _r(r){M=r}async function Mt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||kt()).getRandomBytes(r)}function Ve(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 Jr(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 jt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Mt(r/2,t);return Ve(e)}async function Qr(){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 Mt(16),r.randomBytes=!0}catch{}return r}function Kr(){return kt()}var Yr=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 C=(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},at=r=>{if(r==="warp")return`warp:${q.Warp}`;if(r==="brand")return`brand:${q.Brand}`;if(r==="abi")return`abi:${q.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},T=(r,t)=>r?.actions[t-1],R=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","compute","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},It=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=R(t);return r===e}return!0},st=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},qt=(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},L=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),zt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),an=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===c.Source.UserWallet||n.default===`{{${c.Globals.UserWallet.Placeholder}}}`||n.default===`{{${c.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},Gt=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 on={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"},ot=(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""},pn=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,ln=r=>r;var Q=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,gn=(r,t)=>!r||!t?!1:Q(r)===Q(t),St=(r,t,e)=>{let n=Q(e);if(t===c.IdentifierType.Alias)return c.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+n},O=(r,t)=>{let e=t||c.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=Q(n),a=i.split("?")[0],s=_t(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:c.IdentifierType.Hash,identifier:i,identifierBase:a};if(s.length===2&&/^[a-zA-Z0-9]{62}$/.test(s[0])&&/^[a-zA-Z0-9]{2}$/.test(s[1]))return null;if(s.length===3){let[p,l,o]=s;if(l===c.IdentifierType.Alias||l===c.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:l,identifier:u,identifierBase:o}}}if(s.length===2){let[p,l]=s;if(p===c.IdentifierType.Alias||p===c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l;return{chain:e,type:p,identifier:o,identifierBase:l}}}if(s.length===2){let[p,l]=s;if(p!==c.IdentifierType.Alias&&p!==c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l,u=Le(l,p)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:l}}}return{chain:e,type:c.IdentifierType.Alias,identifier:i,identifierBase:a}},K=(r,t)=>{let e=new URL(r),i=e.searchParams.get(c.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return O(a,t)},Le=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,He=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},_t=r=>{let t=He(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=_t(a);return[i,...s]},Jt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},Qt=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},Kt=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},fn=(r,t)=>{let e=O(r,t);return(e?e.identifierBase:Q(r)).trim()},hn=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var Pt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Wn=r=>{let t=new Set(Object.values(m));if(!r.includes(c.ArgParamsSeparator))return!1;let e=Pt(r)[0];return t.has(e)};var bt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=ot(a,e);return[i,L(s,t)]});return Object.fromEntries(n)};import Ue from"qr-code-styling";var z=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!K(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||k.DefaultClientUrl(this.config.env),a=C(t,this.adapters),s=e===c.IdentifierType.Alias?n:e+c.IdentifierParamSeparator+n,p=a.chainInfo.name+c.IdentifierParamSeparator+s,l=encodeURIComponent(p);return k.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${c.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=O(t,this.config.defaultChain);if(!e)return null;let n=C(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=C(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Ue({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},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 Xt="https://",Zt=(r,t)=>r?typeof r=="string"?t==="success"?r:null:r[t]||null:null,pt=(r,t,e,n,i)=>{let a=T(e,n)?.next||e.next||null,s=Zt(a,"success");if(!s)return null;if(s.startsWith(Xt))return[{identifier:null,url:s}];let[p,l]=s.split("?");if(!l){let v=L(p,{...e.vars,...i});return[{identifier:v,url:X(t,v,r)}]}let o=l.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let v=L(l,{...e.vars,...i}),W=v?`${p}?${v}`:p;return[{identifier:W,url:X(t,W,r)}]}let u=o[0];if(!u)return[];let d=u.match(/{{([^[]+)\[\]/),g=d?d[1]:null;if(!g||i[g]===void 0)return[];let f=Array.isArray(i[g])?i[g]:[i[g]];if(f.length===0)return[];let h=o.filter(v=>v.includes(`{{${g}[]`)).map(v=>{let W=v.match(/\[\](\.[^}]+)?}}/),w=W&&W[1]||"";return{placeholder:v,field:w?w.slice(1):"",regex:new RegExp(v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(v=>{let W=l;for(let{regex:U,field:x}of h){let N=x?De(v,x):v;if(N==null)return null;W=W.replace(U,N)}if(W.includes("{{")||W.includes("}}"))return null;let w=W?`${p}?${W}`:p;return{identifier:w,url:X(t,w,r)}}).filter(v=>v!==null)},lt=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=T(e,n)?.next||e.next||null,l=Zt(p,s);if(!l)return null;if(l.startsWith(Xt))return[{identifier:null,url:l}];let[o,u]=l.split("?");if(!u){let f=L(o,{...e.vars,...i});return[{identifier:f,url:X(t,f,r)}]}let d=L(u,{...e.vars,...i}),g=d?`${o}?${d}`:o;return[{identifier:g,url:X(t,g,r)}]},X=(r,t,e)=>{let[n,i]=t.split("?"),a=O(n,e.defaultChain)||{chain:c.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=C(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let p=new z(e,r).build(s.chainInfo.name,a.type,a.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(/\/\?/,"?")},De=(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 A=j;function ke(r,t,e){return r.startsWith(c.Position.Payload)?r.slice(c.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Yt(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]=Yt(e[n],t[n]):e[n]=t[n]}),e}function Me(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 V(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function G(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=Me(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let s=ke(n.input.position,i,a);e=Yt(e,s)}else e[i]=a}),e}function ct(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let u=o;if("identifier"in u&&"amount"in u){let d=String(u.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(u.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var te=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(c.Transform.Prefix))continue;let l=Ge(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...u]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},Z=async(r,t,e,n,i,a)=>{let s=(d,g)=>g.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:u}=te(r,e,p);return{values:{string:l,native:o,mapped:G(n,i)},output:await ee(r,u,t,e,n,i,a)}},ee=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=je(p,r,n,i,a),p=await qe(r,p,e,i,a,s.transform?.runner||null),p},je=(r,t,e,n,i)=>{let a={...r},s=T(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],u=s.findIndex(g=>g.as===o||g.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},qe=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(c.Transform.Prefix)).map(([o,u])=>({key:o,code:u.substring(c.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:ze(e),inputs:ct(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,l),l[o]=s[o]}catch(d){A.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},ze=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},re=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=te(r,e,s),u=await ee(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:l,mapped:G(n,i)},output:u}},Ge=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 _e=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Ut.some(t=>t in r),ne=(r,t)=>{if(!_e(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var _n=(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 Je(r,t,e,n=5){let i=await jt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function Tt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Je(r,i,e,5)}function Et(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Xn(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Tt(r,e,n),p=await t(i);return Et(r,p,a,s)}function Zn(r){let t=new Date(r).getTime();return Date.now()<t}function Yn(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 Qe=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Ke=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),ie=(r,t=24)=>{let e=Ke(r);return e?e.slice(0,t):"action"},ae=r=>{let t=3735928559^r.length,e=1103547991^r.length;for(let a=0;a<r.length;a++){let s=r.charCodeAt(a);t=Math.imul(t^s,2654435761),e=Math.imul(e^s,1597334677)}t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909);let n=(e>>>0).toString(16).padStart(8,"0"),i=(t>>>0).toString(16).padStart(8,"0");return`${n}${i}`.slice(0,12)},Xe=r=>{let t=(r||"").trim();if(!t)return"";try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"").toLowerCase()||"/";return`${e.origin.toLowerCase()}${n}`}catch{return t.toLowerCase()}},ei=(r,t,e)=>{let n=ie((e||t||"").trim()||"action"),i=`${r.type}|${Xe(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=ae(i);return`private_src_${n}_${a}`},Ze=r=>{let t=Qe(r),e=ie(t),n=ae(t.trim().toLowerCase());return`private_gen_${e}_${n}`},ri=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ze(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},ni=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function ai(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 oi(r,t,e){return null}var Ye=(r,t)=>{let e=null;try{e=R(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},ci=async(r,t,e,n)=>{try{let i=C(e,n),a=Ye(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};import{Mppx as tr,tempo as er}from"mppx/client";async function se(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return A.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),tr.create({methods:[er({account:e})],polyfill:!1}).fetch}return fetch}var I=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===m.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(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===m.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,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${c.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}if(t===m.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),a=n.substring(0,i),s=e.map(l=>{let o=l.indexOf(c.ArgParamsSeparator),u=l.substring(o+1);return a.startsWith(m.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=a.startsWith(m.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+a+c.ArgParamsSeparator+s.join(p)}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):m.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===m.Option){let[a,s]=i.split(c.ArgParamsSeparator);return[m.Option+c.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(c.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(m.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(s+c.ArgParamsSeparator+d)[1]);return[m.Vector+c.ArgParamsSeparator+s,u]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),p=i.split(c.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${c.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(c.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,g]=o;p[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${g}`)[1]}}),[n,p]}else{if(n===m.String)return[n,i];if(n===m.Uint8||n===m.Uint16||n===m.Uint32)return[n,Number(i)];if(n===m.Uint64||n===m.Uint128||n===m.Uint256||n===m.Biguint)return[n,BigInt(i||0)];if(n===m.Bool)return[n,i==="true"];if(n===m.Address)return[n,i];if(n===m.Hex)return[n,i];if(n===m.Asset){let[a,s]=i.split(c.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${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"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var vi=r=>new I().nativeToString(m.String,r),Ci=r=>new I().nativeToString(m.Uint8,r),xi=r=>new I().nativeToString(m.Uint16,r),Ai=r=>new I().nativeToString(m.Uint32,r),wi=r=>new I().nativeToString(m.Uint64,r),Ii=r=>new I().nativeToString(m.Biguint,r),Si=r=>new I().nativeToString(m.Bool,r),Pi=r=>new I().nativeToString(m.Address,r),oe=r=>new I().nativeToString(m.Asset,r),bi=r=>new I().nativeToString(m.Hex,r),Ti=(r,t)=>{if(t===null)return m.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+a},Ei=(...r)=>new I().nativeToString(m.Tuple,r),Ri=r=>new I().nativeToString(m.Struct,r),Ni=r=>new I().nativeToString(m.Vector,r);import rr from"ajv";var pe=class{constructor(t){this.pendingBrand={protocol:at("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||k.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new rr,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import nr from"ajv";var ut=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}=R(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,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||k.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new nr({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var le=class{constructor(t){this.config=t;this.pendingWarp={protocol:at("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 qt(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 ut(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
-
`))}};import{existsSync as Nt,mkdirSync as ir,readdirSync as ce,readFileSync as ar,unlinkSync as Bt,writeFileSync as sr}from"fs";import{join as ue,resolve as de}from"path";var Rt="$bigint:",dt=(r,t)=>typeof t=="bigint"?Rt+t.toString():t,_=(r,t)=>typeof t=="string"&&t.startsWith(Rt)?BigInt(t.slice(Rt.length)):t;var gt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?de(n):de(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){Nt(this.cacheDir)||ir(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return ue(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!Nt(e))return null;let n=ar(e,"utf-8"),i=JSON.parse(n,_);return i.expiresAt!==null&&Date.now()>i.expiresAt?(Bt(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);sr(a,JSON.stringify(i,dt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);Nt(e)&&Bt(e)}catch{}}async keys(t){try{let e=ce(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{ce(this.cacheDir).forEach(e=>{e.endsWith(".json")&&Bt(ue(this.cacheDir,e))})}catch{}}};var Y=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,_);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,dt))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var H=class H{constructor(t,e){}async get(t){let e=H.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(H.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;H.cache.set(t,{value:e,expiresAt:i})}async delete(t){H.cache.delete(t)}async keys(t){let e=Array.from(H.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){H.cache.clear()}};H.cache=new Map;var tt=H;import{readFileSync as or}from"fs";import{resolve as ge}from"path";var ft=class{constructor(t,e){let n=e?.path?ge(e.path):ge(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=or(t,"utf-8");return new Map(Object.entries(JSON.parse(e,_)))}catch(e){return A.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var fe={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},mt={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}`,AccountNfts:(r,t,e,n,i)=>`account-nfts:${r}:${t}:${e}:${n}:${i}`},ht=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new Y(t,e):e?.type==="memory"?new tt(t,e):e?.type==="static"?new ft(t,e):e?.type==="filesystem"?new gt(t,e):typeof window<"u"&&window.localStorage?new Y(t,e):new tt(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var et={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},$t={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Ft=(r,t,e)=>{let n=r.find(a=>a.input.as===t||a.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},Ot=r=>{try{return JSON.parse(r)}catch{return null}},pr=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:u}=await Tt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(Et(n,d,o,u)).forEach(([g,f])=>s.set(g,f))}let p=Ft(e.resolvedInputs,et.Headers,i);if(p){let l=Ot(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},lr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===$t.Get){let s=Ft(e.resolvedInputs,et.Queries,i);if(s){let p=Ot(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&l.searchParams.set(o,String(u))),a=l.toString()}}}return a},cr=(r,t,e,n,i)=>{if(r===$t.Get)return;let a=Ft(t.resolvedInputs,et.Payload,n);if(a&&Ot(a)!==null)return a;let{[et.Payload]:s,[et.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},he=async(r,t,e,n,i,a,s,p)=>{let l=t.method||$t.Get,o=await pr(r,t,e,n,a,p),u=lr(r,t,e,l,a),d=cr(l,e,i,a,s);return{url:u,method:l,headers:o,body:d}};var $=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e),i=await this.applyGlobals(n);return e.envs?this.applyEnvs(i,e.envs):i}applyEnvs(t,e){if(!e||Object.keys(e).length===0)return t;let n=JSON.stringify(t);for(let[i,a]of Object.entries(e)){if(a==null)continue;let s=JSON.stringify(String(a)).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${ur(i)}\\}\\}`,"g"),s)}return JSON.parse(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=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,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,f=e.queries?.[o]??null??d;f!=null&&a(s,f)}else if(p.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Env.length+1),[o,u]=l.split(c.ArgCompositeSeparator),g={...this.config.vars,...e.envs}?.[o];g!=null&&a(s,g)}else p===c.Source.UserWallet&&n?a(s,n):a(s,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 a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.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 a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.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 a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return L(a,s)}applyGlobalsToText(t){if(!Object.values(c.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(c.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=C(l,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let l=p;l&&typeof l=="object"&&"identifier"in l&&"amount"in l&&(i[`primary.${s}.token`]=String(l.identifier),i[`primary.${s}.amount`]=String(l.amount))}}),i}},ur=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var dr=["collect","compute","mcp","state","mount","unmount"],J=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 I,this.cache=new ht(t.env,t.cache)}getSerializer(){return this.serializer}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(mt.WarpExecutable(t,e||"",n))||[];return V(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(mt.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=T(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=C(s.name,this.adapters),l=new $(this.config,p,this.adapters),o=await l.apply(t,i),u=T(o,e),{action:d,index:g}=R(o),f=this.getStringTypedInputs(d,n),h=await this.getResolvedInputs(s.name,d,f,l,i.queries),y=await this.getModifiedInputs(h),v=[],W=[];g===e-1?(v=h,W=y):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,l,i.queries),W=await this.getModifiedInputs(v));let w=W.find(b=>b.input.position==="receiver"||b.input.position==="destination")?.value,U=this.getDestinationFromAction(u),x=w?this.serializer.stringToNative(w)[1]:U;if(x&&(x=l.applyInputs(x,W,this.serializer,y)),!x&&!dr.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let N=this.getPreparedArgs(u,W);N=N.map(b=>l.applyInputs(b,W,this.serializer,y));let F=W.find(b=>b.input.position==="value")?.value||null,E="value"in u?u.value:null,B=F?.split(c.ArgParamsSeparator)[1]||E||"0",D=l.applyInputs(B,W,this.serializer,y),ve=BigInt(D),Ce=W.filter(b=>b.input.position==="transfer"&&b.value).map(b=>b.value),xe=[...("transfers"in u?u.transfers:[])||[],...Ce||[]].map(b=>{let Ct=l.applyInputs(b,W,this.serializer,y),Se=Ct.startsWith(`asset${c.ArgParamsSeparator}`)?Ct:`asset${c.ArgParamsSeparator}${Ct}`;return this.serializer.stringToNative(Se)[1]}),Ae=W.find(b=>b.input.position==="data")?.value,we="data"in u?u.data||"":null,Vt=Ae||we||null,Ie=Vt?l.applyInputs(Vt,W,this.serializer,y):null,Lt={adapter:p,warp:o,chain:s,action:e,destination:x,args:N,value:ve,transfers:xe,data:Ie,resolvedInputs:W};return await this.cache.set(mt.WarpExecutable(this.config.env,o.meta?.hash||"",e),Lt.resolvedInputs,fe.OneWeek),Lt}async getChainInfoForWarp(t,e){if(t.chain)return C(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,a)=>{let s=n[a];return!s||i.includes(c.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(u=>i.applyInputs(u,[],this.serializer)),l=await Promise.all(p.map(u=>this.preprocessInput(t,u))),o=(u,d)=>{if(u.source===c.Source.UserWallet){let v=P(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(u.source==="hidden"){if(u.default===void 0)return null;let v=i?i.applyInputs(String(u.default),[],this.serializer):String(u.default);return this.serializer.nativeToString(u.type,v)}if(l[d])return l[d];let g=u.as||u.name,f=a?.[g],h=this.url.searchParams.get(g),y=f||h;return y?this.serializer.nativeToString(u.type,String(y)):null};return s.map((u,d)=>{let g=o(u,d),f=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:g||(f!==void 0?this.serializer.nativeToString(u.type,f):null)}})}async resolveInputsFromQuery(t,e,n){let i=T(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=C(a.name,this.adapters),p=new $(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],p,n)}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i,a){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i,a)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=st(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=st(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let a=i.input.modifier.substring(c.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=ct(t,this.serializer,n,i),l=await s.run(a,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}async preprocessInput(t,e){try{let[n,i]=Pt(e),a=C(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(c.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=st(p,o.decimals);return oe({...o,amount:u})}else return e}catch(n){throw A.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:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.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(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==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 a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return C(s,this.adapters).chainInfo}};var yt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new J(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:g}=R(t);for(let f=1;f<=t.actions.length;f++){let h=T(t,f);if(!It(h,t))continue;let{tx:y,chain:v,immediateExecution:W,executable:w}=await this.executeAction(t,f,e,u);y&&i.push(y),v&&(a=v),W&&s.push(W),w&&f===g+1&&w.resolvedInputs&&(p=V(w.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let f=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(f))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=T(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Dt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,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 s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);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:s};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:s};{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:s}}if(a.type==="compute"){let o=await this.executeCompute(s);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:s};{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:s}}if(a.type==="state"||a.type==="mount"||a.type==="unmount")return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="mcp"){let o=await this.executeMcp(s);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:s};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:s};{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:s}}}let p=C(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.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:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=C(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!It(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let f=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(u.length===0){let f=t.meta?.query;f&&Object.keys(f).length>0&&(u=await this.factory.resolveInputsFromQuery(t,o,f))}let d=await i.output.getActionExecution(t,o,l.tx,u),g=gr(u,d.output);return d.next=lt(this.config,this.adapters,t,o,g,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(d.values),result:d})),d}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action),a=this.factory.getSerializer(),s=G(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,s,e);let{values:p,output:l}=await Z(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async executeCompute(t){let e=P(this.config,t.chain.name),n=this.factory.getSerializer(),i=G(t.resolvedInputs,n),{values:a,output:s}=await Z(t.warp,i,t.action,t.resolvedInputs,n,this.config);return this.buildCollectResult(t,e,"success",a,s)}async doHttpRequest(t,e,n,i,a){let s=new $(this.config,C(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await he(s,e,t,n,i,p,a,async g=>await this.callHandler(()=>this.handlers?.onSignRequest?.(g)));A.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:u,body:d});try{let g={method:o,headers:u,body:d},h=await(await se(this.adapters))(l,g);A.debug("Collect response status",{status:h.status});let y=await h.json();A.debug("Collect response content",{content:y});let{values:v,output:W}=await Z(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),h.ok?"success":"error",v,W,y)}catch(g){A.error("WarpActionExecutor: Error executing collect",g);let f=V(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:g},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let f=V(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:f}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let h=V(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:h}}let p=this.factory.getSerializer(),l=new $(this.config,C(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()),g={};o.headers&&Object.entries(o.headers).forEach(([f,h])=>{let y=l.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());g[f]=y}),A.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:g});try{let f=new s(new URL(u),{requestInit:{headers:g}}),h=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await h.connect(f);let y={};t.resolvedInputs.forEach(({input:x,value:N})=>{if(N&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let F=x.position.replace("payload:",""),[E,B]=p.stringToNative(N);if(E==="string")y[F]=String(B);else if(E==="bool")y[F]=!!B;else if(E==="uint8"||E==="uint16"||E==="uint32"||E==="uint64"||E==="uint128"||E==="uint256"||E==="biguint"){let D=Number(B);y[F]=(Number.isInteger(D),D)}else y[F]=B}}),e&&Object.assign(y,e);let v=await h.callTool({name:d,arguments:y});await h.close();let W;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{W=JSON.parse(x.text)}catch{W=x.text}else x.type,W=x}else W=v;let{values:w,output:U}=await Z(t.warp,W,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",w,U,v)}catch(f){A.error("WarpExecutor: Error executing MCP",f);let h=V(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:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}buildCollectResult(t,e,n,i,a,s){let p=lt(this.config,this.adapters,t.warp,t.action,a,n),l=V(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:bt(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=C(s.name,this.adapters),l=new $(this.config,p,this.adapters),o=await l.apply(t,a),u=T(o,n),{action:d}=R(o),g=this.factory.getStringTypedInputs(d,i),f=await this.factory.getResolvedInputs(s.name,d,g,l,a.queries),h=await this.factory.getModifiedInputs(f),y=h;if(e.inputs&&e.inputs.length>0){let B=this.factory.getStringTypedInputs(e,i),D=await this.factory.getResolvedInputs(s.name,e,B,l,a.queries);y=await this.factory.getModifiedInputs(D)}let v=ne(u.prompt,this.config.platform),W=l.applyInputs(v,y,this.factory.getSerializer(),h),w=V(y),U=P(this.config,s.name),x=this.factory.getSerializer(),{values:N,output:F}=await re(o,W,n,y,x,this.config),E=y.find(B=>B.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:U,txHash:null,tx:null,next:pt(this.config,this.adapters,o,n,F),values:N,output:F,messages:bt(o,F,this.config),destination:E,resolvedInputs:w}}catch(s){return A.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:lt(this.config,this.adapters,t,n,{},"error"),values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=C(p.name,this.adapters),o=new $(this.config,l,this.adapters),{action:u}=R(t),d=this.factory.getStringTypedInputs(u,n),g=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),f=await this.factory.getModifiedInputs(g),h;if(a)h=a;else{let w=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);h=await this.factory.getModifiedInputs(w)}let y=o.buildInputBag(h,this.factory.getSerializer(),f),v={...i.envs??{},...y},W=zt(e.when,v);return Gt(W)}},gr=(r,t)=>{let e=Object.fromEntries((r??[]).flatMap(i=>{let a=i.input.as||i.input.name;return a?[[a,i.value]]:[]})),n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!=null));return{...e,...n}};var Wt=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 A.error("WarpIndex: Error searching for warps: ",i),i}}};var vt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!K(t,this.config.defaultChain):!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)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.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)?K(t,this.config.defaultChain):O(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,u=t.startsWith(c.HttpProtocolPrefix)?Jt(t):Qt(i.identifier);if(this.resolver){let h=null;if(a==="hash")h=await this.resolver.getByHash(s,e);else if(a==="alias"){let y=`${i.chain}:${s}`;h=await this.resolver.getByAlias(y,e)||await this.resolver.getByAlias(s,e)}h&&(p=h.warp,l=h.registryInfo,o=h.brand)}else{let h=C(i.chain,this.adapters);if(a==="hash"){p=await h.builder().createFromTransactionHash(s,e);let y=await h.registry.getInfoByHash(s,e);l=y.registryInfo,o=y.brand}else if(a==="alias"){let y=await h.registry.getInfoByAlias(s,e);l=y.registryInfo,o=y.brand,y.registryInfo&&(p=await h.builder().createFromTransactionHash(y.registryInfo.hash,e))}}if(p&&p.meta&&(fr(p,i.chain,l,i.identifier),p.meta.query=u?Kt(u):null),!p)return n;let d=p.chain||i.chain,g=this.adapters.find(h=>h.chainInfo.name.toLowerCase()===d.toLowerCase()),f=g?await new $(this.config,g,this.adapters).apply(p):p;return{match:!0,url:t,warp:f,chain:d,registryInfo:l,brand:o}}catch(a){return A.error("Error detecting warp link",a),n}}},fr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?St(null,"alias",e.alias):St(t,"hash",e?.hash??n))};var me=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new rt(e));return new nt(t)}getConfig(){return this.config}getResolver(){return this.resolver}createExecutor(t){return new yt(this.config,this.chains,t)}async detectWarp(t,e){return new vt(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let h=await fetch(t);if(!h.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await h.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:g}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async h=>{await l.evaluateOutput(p,h)},resolvedInputs:g}}async createInscriptionTransaction(t,e){return await C(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return C(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=O(t,this.config.defaultChain);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return C(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return C(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return C(t,this.chains).explorer}getOutput(t){return C(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??R(e).index+1,p=await C(t,this.chains).output.getActionExecution(e,a,n);return p.next=pt(this.config,this.chains,e,a,p.output),p}async getRegistry(t){let e=C(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return C(t,this.chains).dataLoader}getWallet(t){return C(t,this.chains).wallet}get factory(){return new J(this.config,this.chains)}get index(){return new Wt(this.config)}get linkBuilder(){return new z(this.config,this.chains)}createBuilder(t){return C(t,this.chains).builder()}createAbiBuilder(t){return C(t,this.chains).abiBuilder()}createBrandBuilder(t){return C(t,this.chains).brandBuilder()}createSerializer(t){return C(t,this.chains).serializer}resolveText(t){return ot(t,this.config)}};var ye=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()]))}};function ss(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(We(t,n)!==i)return!1;return!0}function os(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?We(t,i):i;return e}function We(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}export{At as BrowserCryptoProvider,Nr as CLOUD_WALLET_PROVIDERS,fe as CacheTtl,Er as EvmWalletChainNames,Rr as MultiversxWalletChainNames,wt as NodeCryptoProvider,on as WARP_LANGUAGES,S as WarpAssets,pe as WarpBrandBuilder,le as WarpBuilder,ht as WarpCache,mt as WarpCacheKey,Fe as WarpChainDisplayNames,Oe as WarpChainLogos,$e as WarpChainName,rt as WarpChainResolver,me as WarpClient,nt as WarpCompositeResolver,k as WarpConfig,c as WarpConstants,yt as WarpExecutor,J as WarpFactory,Wt as WarpIndex,m as WarpInputTypes,$ as WarpInterpolator,z as WarpLinkBuilder,vt as WarpLinkDetecter,A as WarpLogger,Ht as WarpPlatformName,Ut as WarpPlatforms,q as WarpProtocolVersions,I as WarpSerializer,ye as WarpTypeRegistry,ut as WarpValidator,Pi as address,bt as applyOutputToMessages,oe as asset,Ii as biguint,Si as bool,Ze as buildGeneratedFallbackWarpIdentifier,ei as buildGeneratedSourceWarpIdentifier,ct as buildInputsContext,G as buildMappedOutput,ke as buildNestedPayload,Jr as bytesToBase64,Ve as bytesToHex,ci as checkWarpAssetBalance,Q as cleanWarpIdentifier,Et as createAuthHeaders,Tt as createAuthMessage,Kr as createCryptoProvider,oi as createDefaultWalletProvider,Xn as createHttpAuthHeaders,Je as createSignableMessage,ln as createWarpI18nText,St as createWarpIdentifier,an as doesWarpRequireWallet,ee as evaluateOutputCommon,Gt as evaluateWhenCondition,Z as extractCollectOutput,K as extractIdentifierInfoFromUrl,re as extractPromptOutput,Qt as extractQueryStringFromIdentifier,Jt as extractQueryStringFromUrl,V as extractResolvedInputValues,Yr as extractWarpSecrets,C as findWarpAdapterForChain,Lr as getChainDisplayName,Hr as getChainLogo,kt as getCryptoProvider,kr as getEventNameFromWarp,Qe as getGeneratedSourceWarpName,at as getLatestProtocolIdentifier,se as getMppFetch,pt as getNextInfo,lt as getNextInfoForStatus,_n as getProviderConfig,Mt as getRandomBytes,jt as getRandomHex,Ye as getRequiredAssetIds,vr as getWalletFromConfigOrFail,T as getWarpActionByIndex,jr as getWarpBrandLogoUrl,qr as getWarpChainAssetLogoUrl,zr as getWarpChainInfoLogoUrl,hn as getWarpIdentifierWithQuery,O as getWarpInfoFromIdentifier,R as getWarpPrimaryAction,Pe as getWarpWalletAddress,P as getWarpWalletAddressFromConfig,Ee as getWarpWalletExternalId,Re as getWarpWalletExternalIdFromConfig,Ar as getWarpWalletExternalIdFromConfigOrFail,Te as getWarpWalletMnemonic,xr as getWarpWalletMnemonicFromConfig,be as getWarpWalletPrivateKey,Cr as getWarpWalletPrivateKeyFromConfig,Wn as hasInputPrefix,bi as hex,ai as initializeWalletCache,gn as isEqualWarpIdentifier,ni as isGeneratedSourcePrivateIdentifier,_e as isPlatformValue,It as isWarpActionAutoExecute,pn as isWarpI18nText,wr as isWarpWalletReadOnly,ss as matchesTrigger,Yt as mergeNestedPayload,Pr as normalizeAndValidateMnemonic,Ne as normalizeMnemonic,Ti as option,Ge as parseOutputOutIndex,Yn as parseSignedMessage,Kt as parseWarpQueryStringToObject,fn as removeWarpChainPrefix,Sr as removeWarpWalletFromConfig,L as replacePlaceholders,zt as replacePlaceholdersInWhenExpression,os as resolveInputs,Zt as resolveNextString,We as resolvePath,ne as resolvePlatformValue,ot as resolveWarpText,Dt as safeWindow,_r as setCryptoProvider,Ir as setWarpWalletInConfig,st as shiftBigintBy,Pt as splitInput,ri as stampGeneratedWarpMeta,vi as string,Ri as struct,Qr as testCryptoAvailability,Me as toInputPayloadValue,qt as toPreviewText,Ei as tuple,xi as uint16,Ai as uint32,wi as uint64,Ci as uint8,Be as validateMnemonicLength,Zn as validateSignedMessage,Ni as vector,Or as withAdapterFallback};
|
|
1
|
+
var rt=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var nt=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var Cr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},be=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>be(r.user?.wallets?.[t]||null),Te=r=>r?typeof r=="string"?r:r.privateKey||null:null,Ee=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Re=r=>r?typeof r=="string"?r:r.externalId||null:null,xr=(r,t)=>Te(r.user?.wallets?.[t]||null)?.trim()||null,Ar=(r,t)=>Ee(r.user?.wallets?.[t]||null)?.trim()||null,Ne=(r,t)=>Re(r.user?.wallets?.[t]||null)?.trim()||null,wr=(r,t)=>{let e=Ne(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Ir=r=>typeof r=="string",Sr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},Pr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},Be=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},$e=(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`)},br=(r,t=24)=>{let e=Be(r);return $e(e,t),e};var Fe=(g=>(g.Multiversx="multiversx",g.Claws="claws",g.Sui="sui",g.Ethereum="ethereum",g.Base="base",g.Arbitrum="arbitrum",g.Polygon="polygon",g.Somnia="somnia",g.Tempo="tempo",g.Fastset="fastset",g.Solana="solana",g.Near="near",g))(Fe||{}),Ht=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Ht||{}),Ut=Object.values(Ht),Rr=["ethereum","base","arbitrum","polygon","somnia","tempo"],Nr=["multiversx","claws"],Br=["coinbase","privy","gaupa"],c={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(r.config,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"}},m={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"},Dt=typeof window<"u"?window:{open:()=>{}};var q={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},k={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${q.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${q.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 Vr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var it="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",S={baseUrl:it,chainLogo:r=>`${it}/chains/logos/${r}`,tokenLogo:r=>`${it}/tokens/logos/${r}`,walletLogo:r=>`${it}/wallets/logos/${r}`},Oe={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},Hr=r=>Oe[r]??r.charAt(0).toUpperCase()+r.slice(1),Ve={ethereum:{light:S.chainLogo("ethereum-white.svg"),dark:S.chainLogo("ethereum-black.svg")},base:{light:S.chainLogo("base-white.svg"),dark:S.chainLogo("base-black.svg")},arbitrum:S.chainLogo("arbitrum.svg"),polygon:S.chainLogo("polygon.svg"),somnia:S.chainLogo("somnia.png"),tempo:{light:S.chainLogo("tempo-white.svg"),dark:S.chainLogo("tempo-black.svg")},multiversx:S.chainLogo("multiversx.svg"),claws:S.chainLogo("claws.png"),sui:S.chainLogo("sui.svg"),solana:S.chainLogo("solana.svg"),near:{light:S.chainLogo("near-white.svg"),dark:S.chainLogo("near-black.svg")},fastset:{light:S.chainLogo("fastset-white.svg"),dark:S.chainLogo("fastset-black.svg")}},Ur=(r,t="dark")=>{let e=Ve[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var Mr=(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 xt=(r,t)=>r[t]??r.default??Object.values(r)[0],qr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:xt(r.logo,e)},zr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return xt(r.logoUrl,e)},Gr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return xt(r.logoUrl,e)};var At=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}},wt=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"}`)}}},M=null;function kt(){if(M)return M;if(typeof window<"u"&&window.crypto)return M=new At,M;if(typeof process<"u"&&process.versions?.node)return M=new wt,M;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Jr(r){M=r}async function Mt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||kt()).getRandomBytes(r)}function Le(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 Qr(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 jt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Mt(r/2,t);return Le(e)}async function Kr(){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 Mt(16),r.randomBytes=!0}catch{}return r}function Xr(){return kt()}var tn=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 C=(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},at=r=>{if(r==="warp")return`warp:${q.Warp}`;if(r==="brand")return`brand:${q.Brand}`;if(r==="abi")return`abi:${q.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},T=(r,t)=>r?.actions[t-1],R=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","compute","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},It=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=R(t);return r===e}return!0},st=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},qt=(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},L=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),zt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),sn=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===c.Source.UserWallet||n.default===`{{${c.Globals.UserWallet.Placeholder}}}`||n.default===`{{${c.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},Gt=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 pn={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"},ot=(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""},ln=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,cn=r=>r;var Q=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,fn=(r,t)=>!r||!t?!1:Q(r)===Q(t),St=(r,t,e)=>{let n=Q(e);if(t===c.IdentifierType.Alias)return c.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+n},O=(r,t)=>{let e=t||c.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=Q(n),a=i.split("?")[0],s=_t(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:c.IdentifierType.Hash,identifier:i,identifierBase:a};if(s.length===2&&/^[a-zA-Z0-9]{62}$/.test(s[0])&&/^[a-zA-Z0-9]{2}$/.test(s[1]))return null;if(s.length===3){let[p,l,o]=s;if(l===c.IdentifierType.Alias||l===c.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:l,identifier:u,identifierBase:o}}}if(s.length===2){let[p,l]=s;if(p===c.IdentifierType.Alias||p===c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l;return{chain:e,type:p,identifier:o,identifierBase:l}}}if(s.length===2){let[p,l]=s;if(p!==c.IdentifierType.Alias&&p!==c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l,u=He(l,p)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:l}}}return{chain:e,type:c.IdentifierType.Alias,identifier:i,identifierBase:a}},K=(r,t)=>{let e=new URL(r),i=e.searchParams.get(c.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return O(a,t)},He=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Ue=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},_t=r=>{let t=Ue(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=_t(a);return[i,...s]},Jt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},Qt=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},Kt=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},hn=(r,t)=>{let e=O(r,t);return(e?e.identifierBase:Q(r)).trim()},mn=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var Pt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},vn=r=>{let t=new Set(Object.values(m));if(!r.includes(c.ArgParamsSeparator))return!1;let e=Pt(r)[0];return t.has(e)};var bt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=ot(a,e);return[i,L(s,t)]});return Object.fromEntries(n)};import De from"qr-code-styling";var z=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!K(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||k.DefaultClientUrl(this.config.env),a=C(t,this.adapters),s=e===c.IdentifierType.Alias?n:e+c.IdentifierParamSeparator+n,p=a.chainInfo.name+c.IdentifierParamSeparator+s,l=encodeURIComponent(p);return k.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${c.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=O(t,this.config.defaultChain);if(!e)return null;let n=C(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=C(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new De({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},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 Xt="https://",Zt=(r,t)=>r?typeof r=="string"?t==="success"?r:null:r[t]||null:null,pt=(r,t,e,n,i)=>{let a=T(e,n)?.next||e.next||null,s=Zt(a,"success");if(!s)return null;if(s.startsWith(Xt))return[{identifier:null,url:s}];let[p,l]=s.split("?");if(!l){let v=L(p,{...e.vars,...i});return[{identifier:v,url:X(t,v,r)}]}let o=l.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let v=L(l,{...e.vars,...i}),W=v?`${p}?${v}`:p;return[{identifier:W,url:X(t,W,r)}]}let u=o[0];if(!u)return[];let d=u.match(/{{([^[]+)\[\]/),g=d?d[1]:null;if(!g||i[g]===void 0)return[];let f=Array.isArray(i[g])?i[g]:[i[g]];if(f.length===0)return[];let h=o.filter(v=>v.includes(`{{${g}[]`)).map(v=>{let W=v.match(/\[\](\.[^}]+)?}}/),w=W&&W[1]||"";return{placeholder:v,field:w?w.slice(1):"",regex:new RegExp(v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(v=>{let W=l;for(let{regex:U,field:x}of h){let N=x?ke(v,x):v;if(N==null)return null;W=W.replace(U,N)}if(W.includes("{{")||W.includes("}}"))return null;let w=W?`${p}?${W}`:p;return{identifier:w,url:X(t,w,r)}}).filter(v=>v!==null)},lt=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=T(e,n)?.next||e.next||null,l=Zt(p,s);if(!l)return null;if(l.startsWith(Xt))return[{identifier:null,url:l}];let[o,u]=l.split("?");if(!u){let f=L(o,{...e.vars,...i});return[{identifier:f,url:X(t,f,r)}]}let d=L(u,{...e.vars,...i}),g=d?`${o}?${d}`:o;return[{identifier:g,url:X(t,g,r)}]},X=(r,t,e)=>{let[n,i]=t.split("?"),a=O(n,e.defaultChain)||{chain:c.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=C(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let p=new z(e,r).build(s.chainInfo.name,a.type,a.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(/\/\?/,"?")},ke=(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 A=j;function Me(r,t,e){return r.startsWith(c.Position.Payload)?r.slice(c.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Yt(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]=Yt(e[n],t[n]):e[n]=t[n]}),e}function je(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 V(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function G(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=je(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let s=Me(n.input.position,i,a);e=Yt(e,s)}else e[i]=a}),e}function ct(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let u=o;if("identifier"in u&&"amount"in u){let d=String(u.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(u.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var te=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(c.Transform.Prefix))continue;let l=_e(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...u]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},Z=async(r,t,e,n,i,a)=>{let s=(d,g)=>g.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:u}=te(r,e,p);return{values:{string:l,native:o,mapped:G(n,i)},output:await ee(r,u,t,e,n,i,a)}},ee=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=qe(p,r,n,i,a),p=await ze(r,p,e,i,a,s.transform?.runner||null),p},qe=(r,t,e,n,i)=>{let a={...r},s=T(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],u=s.findIndex(g=>g.as===o||g.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},ze=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(c.Transform.Prefix)).map(([o,u])=>({key:o,code:u.substring(c.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:Ge(e),inputs:ct(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,l),l[o]=s[o]}catch(d){A.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},Ge=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},re=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=te(r,e,s),u=await ee(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:l,mapped:G(n,i)},output:u}},_e=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 Je=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Ut.some(t=>t in r),ne=(r,t)=>{if(!Je(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var Jn=(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 Qe(r,t,e,n=5){let i=await jt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function Tt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Qe(r,i,e,5)}function Et(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Zn(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Tt(r,e,n),p=await t(i);return Et(r,p,a,s)}function Yn(r){let t=new Date(r).getTime();return Date.now()<t}function ti(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=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Xe=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),ie=(r,t=24)=>{let e=Xe(r);return e?e.slice(0,t):"action"},ae=r=>{let t=3735928559^r.length,e=1103547991^r.length;for(let a=0;a<r.length;a++){let s=r.charCodeAt(a);t=Math.imul(t^s,2654435761),e=Math.imul(e^s,1597334677)}t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909);let n=(e>>>0).toString(16).padStart(8,"0"),i=(t>>>0).toString(16).padStart(8,"0");return`${n}${i}`.slice(0,12)},Ze=r=>{let t=(r||"").trim();if(!t)return"";try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"").toLowerCase()||"/";return`${e.origin.toLowerCase()}${n}`}catch{return t.toLowerCase()}},ri=(r,t,e)=>{let n=ie((e||t||"").trim()||"action"),i=`${r.type}|${Ze(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=ae(i);return`private_src_${n}_${a}`},Ye=r=>{let t=Ke(r),e=ie(t),n=ae(t.trim().toLowerCase());return`private_gen_${e}_${n}`},ni=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ye(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},ii=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function si(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 pi(r,t,e){return null}var tr=(r,t)=>{let e=null;try{e=R(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},ui=async(r,t,e,n)=>{try{let i=C(e,n),a=tr(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};import{Mppx as er,tempo as rr}from"mppx/client";async function se(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return A.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),er.create({methods:[rr({account:e})],polyfill:!1}).fetch}return fetch}var oe={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},I=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=oe[t]??t,t===m.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(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===m.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,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${c.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}if(t===m.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),a=n.substring(0,i),s=e.map(l=>{let o=l.indexOf(c.ArgParamsSeparator),u=l.substring(o+1);return a.startsWith(m.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=a.startsWith(m.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+a+c.ArgParamsSeparator+s.join(p)}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):m.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=oe[e[0]]??e[0],i=e.slice(1).join(c.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(c.ArgParamsSeparator);return[m.Option+c.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(c.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(m.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(s+c.ArgParamsSeparator+d)[1]);return[m.Vector+c.ArgParamsSeparator+s,u]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),p=i.split(c.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${c.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(c.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,g]=o;p[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${g}`)[1]}}),[n,p]}else{if(n===m.String)return[n,i];if(n===m.Uint8||n===m.Uint16||n===m.Uint32)return[n,Number(i)];if(n===m.Uint64||n===m.Uint128||n===m.Uint256||n===m.Biguint)return[n,BigInt(i||0)];if(n===m.Bool)return[n,i==="true"];if(n===m.Address)return[n,i];if(n===m.Hex)return[n,i];if(n===m.Asset){let[a,s]=i.split(c.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${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"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var Ci=r=>new I().nativeToString(m.String,r),xi=r=>new I().nativeToString(m.Uint8,r),Ai=r=>new I().nativeToString(m.Uint16,r),wi=r=>new I().nativeToString(m.Uint32,r),Ii=r=>new I().nativeToString(m.Uint64,r),Si=r=>new I().nativeToString(m.Biguint,r),Pi=r=>new I().nativeToString(m.Bool,r),bi=r=>new I().nativeToString(m.Address,r),pe=r=>new I().nativeToString(m.Asset,r),Ti=r=>new I().nativeToString(m.Hex,r),Ei=(r,t)=>{if(t===null)return m.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+a},Ri=(...r)=>new I().nativeToString(m.Tuple,r),Ni=r=>new I().nativeToString(m.Struct,r),Bi=r=>new I().nativeToString(m.Vector,r);import nr from"ajv";var le=class{constructor(t){this.pendingBrand={protocol:at("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||k.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new nr,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import ir from"ajv";var ut=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}=R(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,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||k.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new ir({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ce=class{constructor(t){this.config=t;this.pendingWarp={protocol:at("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 qt(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 ut(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
+
`))}};import{existsSync as Nt,mkdirSync as ar,readdirSync as ue,readFileSync as sr,unlinkSync as Bt,writeFileSync as or}from"fs";import{join as de,resolve as ge}from"path";var Rt="$bigint:",dt=(r,t)=>typeof t=="bigint"?Rt+t.toString():t,_=(r,t)=>typeof t=="string"&&t.startsWith(Rt)?BigInt(t.slice(Rt.length)):t;var gt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?ge(n):ge(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){Nt(this.cacheDir)||ar(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return de(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!Nt(e))return null;let n=sr(e,"utf-8"),i=JSON.parse(n,_);return i.expiresAt!==null&&Date.now()>i.expiresAt?(Bt(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);or(a,JSON.stringify(i,dt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);Nt(e)&&Bt(e)}catch{}}async keys(t){try{let e=ue(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{ue(this.cacheDir).forEach(e=>{e.endsWith(".json")&&Bt(de(this.cacheDir,e))})}catch{}}};var Y=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,_);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,dt))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var H=class H{constructor(t,e){}async get(t){let e=H.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(H.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;H.cache.set(t,{value:e,expiresAt:i})}async delete(t){H.cache.delete(t)}async keys(t){let e=Array.from(H.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){H.cache.clear()}};H.cache=new Map;var tt=H;import{readFileSync as pr}from"fs";import{resolve as fe}from"path";var ft=class{constructor(t,e){let n=e?.path?fe(e.path):fe(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=pr(t,"utf-8");return new Map(Object.entries(JSON.parse(e,_)))}catch(e){return A.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var he={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},mt={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}`,AccountNfts:(r,t,e,n,i)=>`account-nfts:${r}:${t}:${e}:${n}:${i}`},ht=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new Y(t,e):e?.type==="memory"?new tt(t,e):e?.type==="static"?new ft(t,e):e?.type==="filesystem"?new gt(t,e):typeof window<"u"&&window.localStorage?new Y(t,e):new tt(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var et={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},$t={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Ft=(r,t,e)=>{let n=r.find(a=>a.input.as===t||a.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},Ot=r=>{try{return JSON.parse(r)}catch{return null}},lr=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:u}=await Tt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(Et(n,d,o,u)).forEach(([g,f])=>s.set(g,f))}let p=Ft(e.resolvedInputs,et.Headers,i);if(p){let l=Ot(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},cr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===$t.Get){let s=Ft(e.resolvedInputs,et.Queries,i);if(s){let p=Ot(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&l.searchParams.set(o,String(u))),a=l.toString()}}}return a},ur=(r,t,e,n,i)=>{if(r===$t.Get)return;let a=Ft(t.resolvedInputs,et.Payload,n);if(a&&Ot(a)!==null)return a;let{[et.Payload]:s,[et.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},me=async(r,t,e,n,i,a,s,p)=>{let l=t.method||$t.Get,o=await lr(r,t,e,n,a,p),u=cr(r,t,e,l,a),d=ur(l,e,i,a,s);return{url:u,method:l,headers:o,body:d}};var $=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e),i=await this.applyGlobals(n);return e.envs?this.applyEnvs(i,e.envs):i}applyEnvs(t,e){if(!e||Object.keys(e).length===0)return t;let n=JSON.stringify(t);for(let[i,a]of Object.entries(e)){if(a==null)continue;let s=JSON.stringify(String(a)).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${dr(i)}\\}\\}`,"g"),s)}return JSON.parse(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=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,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,f=e.queries?.[o]??null??d;f!=null&&a(s,f)}else if(p.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Env.length+1),[o,u]=l.split(c.ArgCompositeSeparator),g={...this.config.vars,...e.envs}?.[o];g!=null&&a(s,g)}else p===c.Source.UserWallet&&n?a(s,n):a(s,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 a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.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 a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.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 a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return L(a,s)}applyGlobalsToText(t){if(!Object.values(c.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(c.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=C(l,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let l=p;l&&typeof l=="object"&&"identifier"in l&&"amount"in l&&(i[`primary.${s}.token`]=String(l.identifier),i[`primary.${s}.amount`]=String(l.amount))}}),i}},dr=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var gr=["collect","compute","mcp","state","mount","unmount"],J=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 I,this.cache=new ht(t.env,t.cache)}getSerializer(){return this.serializer}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(mt.WarpExecutable(t,e||"",n))||[];return V(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(mt.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=T(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=C(s.name,this.adapters),l=new $(this.config,p,this.adapters),o=await l.apply(t,i),u=T(o,e),{action:d,index:g}=R(o),f=this.getStringTypedInputs(d,n),h=await this.getResolvedInputs(s.name,d,f,l,i.queries),y=await this.getModifiedInputs(h),v=[],W=[];g===e-1?(v=h,W=y):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,l,i.queries),W=await this.getModifiedInputs(v));let w=W.find(b=>b.input.position==="receiver"||b.input.position==="destination")?.value,U=this.getDestinationFromAction(u),x=w?this.serializer.stringToNative(w)[1]:U;if(x&&(x=l.applyInputs(x,W,this.serializer,y)),!x&&!gr.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let N=this.getPreparedArgs(u,W);N=N.map(b=>l.applyInputs(b,W,this.serializer,y));let F=W.find(b=>b.input.position==="value")?.value||null,E="value"in u?u.value:null,B=F?.split(c.ArgParamsSeparator)[1]||E||"0",D=l.applyInputs(B,W,this.serializer,y),Ce=BigInt(D),xe=W.filter(b=>b.input.position==="transfer"&&b.value).map(b=>b.value),Ae=[...("transfers"in u?u.transfers:[])||[],...xe||[]].map(b=>{let Ct=l.applyInputs(b,W,this.serializer,y),Pe=Ct.startsWith(`asset${c.ArgParamsSeparator}`)?Ct:`asset${c.ArgParamsSeparator}${Ct}`;return this.serializer.stringToNative(Pe)[1]}),we=W.find(b=>b.input.position==="data")?.value,Ie="data"in u?u.data||"":null,Vt=we||Ie||null,Se=Vt?l.applyInputs(Vt,W,this.serializer,y):null,Lt={adapter:p,warp:o,chain:s,action:e,destination:x,args:N,value:Ce,transfers:Ae,data:Se,resolvedInputs:W};return await this.cache.set(mt.WarpExecutable(this.config.env,o.meta?.hash||"",e),Lt.resolvedInputs,he.OneWeek),Lt}async getChainInfoForWarp(t,e){if(t.chain)return C(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,a)=>{let s=n[a];return!s||i.includes(c.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(u=>i.applyInputs(u,[],this.serializer)),l=await Promise.all(p.map(u=>this.preprocessInput(t,u))),o=(u,d)=>{if(u.source===c.Source.UserWallet){let v=P(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(u.source==="hidden"){if(u.default===void 0)return null;let v=i?i.applyInputs(String(u.default),[],this.serializer):String(u.default);return this.serializer.nativeToString(u.type,v)}if(l[d])return l[d];let g=u.as||u.name,f=a?.[g],h=this.url.searchParams.get(g),y=f||h;return y?this.serializer.nativeToString(u.type,String(y)):null};return s.map((u,d)=>{let g=o(u,d),f=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:g||(f!==void 0?this.serializer.nativeToString(u.type,f):null)}})}async resolveInputsFromQuery(t,e,n){let i=T(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=C(a.name,this.adapters),p=new $(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],p,n)}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i,a){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i,a)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=st(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=st(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let a=i.input.modifier.substring(c.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=ct(t,this.serializer,n,i),l=await s.run(a,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}async preprocessInput(t,e){try{let[n,i]=Pt(e),a=C(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(c.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=st(p,o.decimals);return pe({...o,amount:u})}else return e}catch(n){throw A.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:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.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(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==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 a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return C(s,this.adapters).chainInfo}};var yt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new J(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:g}=R(t);for(let f=1;f<=t.actions.length;f++){let h=T(t,f);if(!It(h,t))continue;let{tx:y,chain:v,immediateExecution:W,executable:w}=await this.executeAction(t,f,e,u);y&&i.push(y),v&&(a=v),W&&s.push(W),w&&f===g+1&&w.resolvedInputs&&(p=V(w.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let f=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(f))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=T(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Dt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,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 s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);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:s};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:s};{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:s}}if(a.type==="compute"){let o=await this.executeCompute(s);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:s};{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:s}}if(a.type==="state"||a.type==="mount"||a.type==="unmount")return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="mcp"){let o=await this.executeMcp(s);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:s};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:s};{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:s}}}let p=C(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.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:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=C(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!It(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let f=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(u.length===0){let f=t.meta?.query;f&&Object.keys(f).length>0&&(u=await this.factory.resolveInputsFromQuery(t,o,f))}let d=await i.output.getActionExecution(t,o,l.tx,u),g=fr(u,d.output);return d.next=lt(this.config,this.adapters,t,o,g,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(d.values),result:d})),d}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action),a=this.factory.getSerializer(),s=G(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,s,e);let{values:p,output:l}=await Z(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async executeCompute(t){let e=P(this.config,t.chain.name),n=this.factory.getSerializer(),i=G(t.resolvedInputs,n),{values:a,output:s}=await Z(t.warp,i,t.action,t.resolvedInputs,n,this.config);return this.buildCollectResult(t,e,"success",a,s)}async doHttpRequest(t,e,n,i,a){let s=new $(this.config,C(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await me(s,e,t,n,i,p,a,async g=>await this.callHandler(()=>this.handlers?.onSignRequest?.(g)));A.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:u,body:d});try{let g={method:o,headers:u,body:d},h=await(await se(this.adapters))(l,g);A.debug("Collect response status",{status:h.status});let y=await h.json();A.debug("Collect response content",{content:y});let{values:v,output:W}=await Z(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),h.ok?"success":"error",v,W,y)}catch(g){A.error("WarpActionExecutor: Error executing collect",g);let f=V(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:g},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let f=V(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:f}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let h=V(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:h}}let p=this.factory.getSerializer(),l=new $(this.config,C(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()),g={};o.headers&&Object.entries(o.headers).forEach(([f,h])=>{let y=l.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());g[f]=y}),A.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:g});try{let f=new s(new URL(u),{requestInit:{headers:g}}),h=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await h.connect(f);let y={};t.resolvedInputs.forEach(({input:x,value:N})=>{if(N&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let F=x.position.replace("payload:",""),[E,B]=p.stringToNative(N);if(E==="string")y[F]=String(B);else if(E==="bool")y[F]=!!B;else if(E==="uint8"||E==="uint16"||E==="uint32"||E==="uint64"||E==="uint128"||E==="uint256"||E==="biguint"){let D=Number(B);y[F]=(Number.isInteger(D),D)}else y[F]=B}}),e&&Object.assign(y,e);let v=await h.callTool({name:d,arguments:y});await h.close();let W;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{W=JSON.parse(x.text)}catch{W=x.text}else x.type,W=x}else W=v;let{values:w,output:U}=await Z(t.warp,W,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",w,U,v)}catch(f){A.error("WarpExecutor: Error executing MCP",f);let h=V(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:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}buildCollectResult(t,e,n,i,a,s){let p=lt(this.config,this.adapters,t.warp,t.action,a,n),l=V(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:bt(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=C(s.name,this.adapters),l=new $(this.config,p,this.adapters),o=await l.apply(t,a),u=T(o,n),{action:d}=R(o),g=this.factory.getStringTypedInputs(d,i),f=await this.factory.getResolvedInputs(s.name,d,g,l,a.queries),h=await this.factory.getModifiedInputs(f),y=h;if(e.inputs&&e.inputs.length>0){let B=this.factory.getStringTypedInputs(e,i),D=await this.factory.getResolvedInputs(s.name,e,B,l,a.queries);y=await this.factory.getModifiedInputs(D)}let v=ne(u.prompt,this.config.platform),W=l.applyInputs(v,y,this.factory.getSerializer(),h),w=V(y),U=P(this.config,s.name),x=this.factory.getSerializer(),{values:N,output:F}=await re(o,W,n,y,x,this.config),E=y.find(B=>B.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:U,txHash:null,tx:null,next:pt(this.config,this.adapters,o,n,F),values:N,output:F,messages:bt(o,F,this.config),destination:E,resolvedInputs:w}}catch(s){return A.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:lt(this.config,this.adapters,t,n,{},"error"),values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=C(p.name,this.adapters),o=new $(this.config,l,this.adapters),{action:u}=R(t),d=this.factory.getStringTypedInputs(u,n),g=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),f=await this.factory.getModifiedInputs(g),h;if(a)h=a;else{let w=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);h=await this.factory.getModifiedInputs(w)}let y=o.buildInputBag(h,this.factory.getSerializer(),f),v={...i.envs??{},...y},W=zt(e.when,v);return Gt(W)}},fr=(r,t)=>{let e=Object.fromEntries((r??[]).flatMap(i=>{let a=i.input.as||i.input.name;return a?[[a,i.value]]:[]})),n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!=null));return{...e,...n}};var Wt=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 A.error("WarpIndex: Error searching for warps: ",i),i}}};var vt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!K(t,this.config.defaultChain):!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)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.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)?K(t,this.config.defaultChain):O(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,u=t.startsWith(c.HttpProtocolPrefix)?Jt(t):Qt(i.identifier);if(this.resolver){let h=null;if(a==="hash")h=await this.resolver.getByHash(s,e);else if(a==="alias"){let y=`${i.chain}:${s}`;h=await this.resolver.getByAlias(y,e)||await this.resolver.getByAlias(s,e)}h&&(p=h.warp,l=h.registryInfo,o=h.brand)}else{let h=C(i.chain,this.adapters);if(a==="hash"){p=await h.builder().createFromTransactionHash(s,e);let y=await h.registry.getInfoByHash(s,e);l=y.registryInfo,o=y.brand}else if(a==="alias"){let y=await h.registry.getInfoByAlias(s,e);l=y.registryInfo,o=y.brand,y.registryInfo&&(p=await h.builder().createFromTransactionHash(y.registryInfo.hash,e))}}if(p&&p.meta&&(hr(p,i.chain,l,i.identifier),p.meta.query=u?Kt(u):null),!p)return n;let d=p.chain||i.chain,g=this.adapters.find(h=>h.chainInfo.name.toLowerCase()===d.toLowerCase()),f=g?await new $(this.config,g,this.adapters).apply(p):p;return{match:!0,url:t,warp:f,chain:d,registryInfo:l,brand:o}}catch(a){return A.error("Error detecting warp link",a),n}}},hr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?St(null,"alias",e.alias):St(t,"hash",e?.hash??n))};var ye=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new rt(e));return new nt(t)}getConfig(){return this.config}getResolver(){return this.resolver}createExecutor(t){return new yt(this.config,this.chains,t)}async detectWarp(t,e){return new vt(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let h=await fetch(t);if(!h.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await h.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:g}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async h=>{await l.evaluateOutput(p,h)},resolvedInputs:g}}async createInscriptionTransaction(t,e){return await C(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return C(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=O(t,this.config.defaultChain);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return C(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return C(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return C(t,this.chains).explorer}getOutput(t){return C(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??R(e).index+1,p=await C(t,this.chains).output.getActionExecution(e,a,n);return p.next=pt(this.config,this.chains,e,a,p.output),p}async getRegistry(t){let e=C(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return C(t,this.chains).dataLoader}getWallet(t){return C(t,this.chains).wallet}get factory(){return new J(this.config,this.chains)}get index(){return new Wt(this.config)}get linkBuilder(){return new z(this.config,this.chains)}createBuilder(t){return C(t,this.chains).builder()}createAbiBuilder(t){return C(t,this.chains).abiBuilder()}createBrandBuilder(t){return C(t,this.chains).brandBuilder()}createSerializer(t){return C(t,this.chains).serializer}resolveText(t){return ot(t,this.config)}};var We=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()]))}};function os(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(ve(t,n)!==i)return!1;return!0}function ps(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?ve(t,i):i;return e}function ve(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}export{At as BrowserCryptoProvider,Br as CLOUD_WALLET_PROVIDERS,he as CacheTtl,Rr as EvmWalletChainNames,Nr as MultiversxWalletChainNames,wt as NodeCryptoProvider,pn as WARP_LANGUAGES,S as WarpAssets,le as WarpBrandBuilder,ce as WarpBuilder,ht as WarpCache,mt as WarpCacheKey,Oe as WarpChainDisplayNames,Ve as WarpChainLogos,Fe as WarpChainName,rt as WarpChainResolver,ye as WarpClient,nt as WarpCompositeResolver,k as WarpConfig,c as WarpConstants,yt as WarpExecutor,J as WarpFactory,Wt as WarpIndex,m as WarpInputTypes,$ as WarpInterpolator,z as WarpLinkBuilder,vt as WarpLinkDetecter,A as WarpLogger,Ht as WarpPlatformName,Ut as WarpPlatforms,q as WarpProtocolVersions,I as WarpSerializer,We as WarpTypeRegistry,ut as WarpValidator,bi as address,bt as applyOutputToMessages,pe as asset,Si as biguint,Pi as bool,Ye as buildGeneratedFallbackWarpIdentifier,ri as buildGeneratedSourceWarpIdentifier,ct as buildInputsContext,G as buildMappedOutput,Me as buildNestedPayload,Qr as bytesToBase64,Le as bytesToHex,ui as checkWarpAssetBalance,Q as cleanWarpIdentifier,Et as createAuthHeaders,Tt as createAuthMessage,Xr as createCryptoProvider,pi as createDefaultWalletProvider,Zn as createHttpAuthHeaders,Qe as createSignableMessage,cn as createWarpI18nText,St as createWarpIdentifier,sn as doesWarpRequireWallet,ee as evaluateOutputCommon,Gt as evaluateWhenCondition,Z as extractCollectOutput,K as extractIdentifierInfoFromUrl,re as extractPromptOutput,Qt as extractQueryStringFromIdentifier,Jt as extractQueryStringFromUrl,V as extractResolvedInputValues,tn as extractWarpSecrets,C as findWarpAdapterForChain,Hr as getChainDisplayName,Ur as getChainLogo,kt as getCryptoProvider,Mr as getEventNameFromWarp,Ke as getGeneratedSourceWarpName,at as getLatestProtocolIdentifier,se as getMppFetch,pt as getNextInfo,lt as getNextInfoForStatus,Jn as getProviderConfig,Mt as getRandomBytes,jt as getRandomHex,tr as getRequiredAssetIds,Cr as getWalletFromConfigOrFail,T as getWarpActionByIndex,qr as getWarpBrandLogoUrl,zr as getWarpChainAssetLogoUrl,Gr as getWarpChainInfoLogoUrl,mn as getWarpIdentifierWithQuery,O as getWarpInfoFromIdentifier,R as getWarpPrimaryAction,be as getWarpWalletAddress,P as getWarpWalletAddressFromConfig,Re as getWarpWalletExternalId,Ne as getWarpWalletExternalIdFromConfig,wr as getWarpWalletExternalIdFromConfigOrFail,Ee as getWarpWalletMnemonic,Ar as getWarpWalletMnemonicFromConfig,Te as getWarpWalletPrivateKey,xr as getWarpWalletPrivateKeyFromConfig,vn as hasInputPrefix,Ti as hex,si as initializeWalletCache,fn as isEqualWarpIdentifier,ii as isGeneratedSourcePrivateIdentifier,Je as isPlatformValue,It as isWarpActionAutoExecute,ln as isWarpI18nText,Ir as isWarpWalletReadOnly,os as matchesTrigger,Yt as mergeNestedPayload,br as normalizeAndValidateMnemonic,Be as normalizeMnemonic,Ei as option,_e as parseOutputOutIndex,ti as parseSignedMessage,Kt as parseWarpQueryStringToObject,hn as removeWarpChainPrefix,Pr as removeWarpWalletFromConfig,L as replacePlaceholders,zt as replacePlaceholdersInWhenExpression,ps as resolveInputs,Zt as resolveNextString,ve as resolvePath,ne as resolvePlatformValue,ot as resolveWarpText,Dt as safeWindow,Jr as setCryptoProvider,Sr as setWarpWalletInConfig,st as shiftBigintBy,Pt as splitInput,ni as stampGeneratedWarpMeta,Ci as string,Ni as struct,Kr as testCryptoAvailability,je as toInputPayloadValue,qt as toPreviewText,Ri as tuple,Ai as uint16,wi as uint32,Ii as uint64,xi as uint8,$e as validateMnemonicLength,Yn as validateSignedMessage,Bi as vector,Vr as withAdapterFallback};
|