@joai/warps 4.10.0 → 4.11.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 CHANGED
@@ -62,6 +62,17 @@ type WarpChainAssetValue = {
62
62
  };
63
63
  type WarpChainAssetLogoThemed = Record<WarpTheme, string>;
64
64
  type WarpChainAssetLogo = string | WarpChainAssetLogoThemed | null;
65
+ type WarpChainAssetType = 'fungible' | 'nft' | 'sft';
66
+ type WarpChainAssetNftMetadata = {
67
+ collection?: string;
68
+ nonce?: bigint;
69
+ mediaUrl?: string;
70
+ thumbnailUrl?: string;
71
+ attributes?: Record<string, string>;
72
+ royalties?: number;
73
+ rank?: number;
74
+ creator?: string;
75
+ };
65
76
  type WarpChainAsset = {
66
77
  chain: WarpChainName;
67
78
  identifier: string;
@@ -72,6 +83,8 @@ type WarpChainAsset = {
72
83
  logoUrl?: WarpChainAssetLogo;
73
84
  price?: number;
74
85
  supply?: bigint;
86
+ type?: WarpChainAssetType;
87
+ nft?: WarpChainAssetNftMetadata;
75
88
  };
76
89
  type WarpChainAction = {
77
90
  chain: WarpChainName;
@@ -334,6 +347,7 @@ interface WarpDataLoaderOptions {
334
347
  interface AdapterWarpDataLoader {
335
348
  getAccount(address: string): Promise<WarpChainAccount>;
336
349
  getAccountAssets(address: string): Promise<WarpChainAsset[]>;
350
+ getAccountNfts?(address: string, options?: WarpDataLoaderOptions): Promise<WarpChainAsset[]>;
337
351
  getAsset(identifier: string): Promise<WarpChainAsset | null>;
338
352
  getAction(identifier: string, awaitCompleted?: boolean): Promise<WarpChainAction | null>;
339
353
  getAccountActions(address: string, options?: WarpDataLoaderOptions): Promise<WarpChainAction[]>;
@@ -375,6 +389,7 @@ declare enum WarpPlatformName {
375
389
  }
376
390
  declare const WarpPlatforms: WarpPlatformName[];
377
391
  declare const EvmWalletChainNames: WarpChainName[];
392
+ declare const MultiversxWalletChainNames: WarpChainName[];
378
393
  declare const CLOUD_WALLET_PROVIDERS: WarpWalletProvider[];
379
394
  declare const WarpConstants: {
380
395
  HttpProtocolPrefix: string;
@@ -789,6 +804,10 @@ declare const WarpAssets: {
789
804
  declare const WarpChainDisplayNames: Record<WarpChainName, string>;
790
805
  declare const getChainDisplayName: (chain: WarpChainName) => string;
791
806
  declare const WarpChainLogos: Record<WarpChainName, WarpChainInfoLogo>;
807
+ /**
808
+ * Get chain logo URL for a given background.
809
+ * @param variant - the background color: 'dark' returns the light/white logo, 'light' returns the dark/black logo
810
+ */
792
811
  declare const getChainLogo: (chain: WarpChainName, variant?: "light" | "dark") => string;
793
812
 
794
813
  declare const getEventNameFromWarp: (warp: Warp, alertName: string) => string | null;
@@ -1151,6 +1170,7 @@ declare const WarpCacheKey: {
1151
1170
  RegistryInfo: (env: WarpChainEnv, id: string) => string;
1152
1171
  Brand: (env: WarpChainEnv, hash: string) => string;
1153
1172
  Asset: (env: WarpChainEnv, chain: string, identifier: string) => string;
1173
+ AccountNfts: (env: WarpChainEnv, chain: string, address: string, page: number, size: number) => string;
1154
1174
  };
1155
1175
  declare class WarpCache {
1156
1176
  private strategy;
@@ -1399,4 +1419,4 @@ declare class WarpValidator {
1399
1419
  private validateSchema;
1400
1420
  }
1401
1421
 
1402
- 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, 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 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 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, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
1422
+ 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 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, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, 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
@@ -62,6 +62,17 @@ type WarpChainAssetValue = {
62
62
  };
63
63
  type WarpChainAssetLogoThemed = Record<WarpTheme, string>;
64
64
  type WarpChainAssetLogo = string | WarpChainAssetLogoThemed | null;
65
+ type WarpChainAssetType = 'fungible' | 'nft' | 'sft';
66
+ type WarpChainAssetNftMetadata = {
67
+ collection?: string;
68
+ nonce?: bigint;
69
+ mediaUrl?: string;
70
+ thumbnailUrl?: string;
71
+ attributes?: Record<string, string>;
72
+ royalties?: number;
73
+ rank?: number;
74
+ creator?: string;
75
+ };
65
76
  type WarpChainAsset = {
66
77
  chain: WarpChainName;
67
78
  identifier: string;
@@ -72,6 +83,8 @@ type WarpChainAsset = {
72
83
  logoUrl?: WarpChainAssetLogo;
73
84
  price?: number;
74
85
  supply?: bigint;
86
+ type?: WarpChainAssetType;
87
+ nft?: WarpChainAssetNftMetadata;
75
88
  };
76
89
  type WarpChainAction = {
77
90
  chain: WarpChainName;
@@ -334,6 +347,7 @@ interface WarpDataLoaderOptions {
334
347
  interface AdapterWarpDataLoader {
335
348
  getAccount(address: string): Promise<WarpChainAccount>;
336
349
  getAccountAssets(address: string): Promise<WarpChainAsset[]>;
350
+ getAccountNfts?(address: string, options?: WarpDataLoaderOptions): Promise<WarpChainAsset[]>;
337
351
  getAsset(identifier: string): Promise<WarpChainAsset | null>;
338
352
  getAction(identifier: string, awaitCompleted?: boolean): Promise<WarpChainAction | null>;
339
353
  getAccountActions(address: string, options?: WarpDataLoaderOptions): Promise<WarpChainAction[]>;
@@ -375,6 +389,7 @@ declare enum WarpPlatformName {
375
389
  }
376
390
  declare const WarpPlatforms: WarpPlatformName[];
377
391
  declare const EvmWalletChainNames: WarpChainName[];
392
+ declare const MultiversxWalletChainNames: WarpChainName[];
378
393
  declare const CLOUD_WALLET_PROVIDERS: WarpWalletProvider[];
379
394
  declare const WarpConstants: {
380
395
  HttpProtocolPrefix: string;
@@ -789,6 +804,10 @@ declare const WarpAssets: {
789
804
  declare const WarpChainDisplayNames: Record<WarpChainName, string>;
790
805
  declare const getChainDisplayName: (chain: WarpChainName) => string;
791
806
  declare const WarpChainLogos: Record<WarpChainName, WarpChainInfoLogo>;
807
+ /**
808
+ * Get chain logo URL for a given background.
809
+ * @param variant - the background color: 'dark' returns the light/white logo, 'light' returns the dark/black logo
810
+ */
792
811
  declare const getChainLogo: (chain: WarpChainName, variant?: "light" | "dark") => string;
793
812
 
794
813
  declare const getEventNameFromWarp: (warp: Warp, alertName: string) => string | null;
@@ -1151,6 +1170,7 @@ declare const WarpCacheKey: {
1151
1170
  RegistryInfo: (env: WarpChainEnv, id: string) => string;
1152
1171
  Brand: (env: WarpChainEnv, hash: string) => string;
1153
1172
  Asset: (env: WarpChainEnv, chain: string, identifier: string) => string;
1173
+ AccountNfts: (env: WarpChainEnv, chain: string, address: string, page: number, size: number) => string;
1154
1174
  };
1155
1175
  declare class WarpCache {
1156
1176
  private strategy;
@@ -1399,4 +1419,4 @@ declare class WarpValidator {
1399
1419
  private validateSchema;
1400
1420
  }
1401
1421
 
1402
- 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, 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 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 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, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
1422
+ 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 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, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, 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 _e=Object.create;var mt=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var Ze=(r,t)=>{for(var e in t)mt(r,e,{get:t[e],enumerable:!0})},ue=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Qe(t))!Xe.call(r,i)&&i!==e&&mt(r,i,{get:()=>t[i],enumerable:!(n=Je(t,i))||n.enumerable});return r};var K=(r,t,e)=>(e=r!=null?_e(Ke(r)):{},ue(t||!r||!r.__esModule?mt(e,"default",{value:r,enumerable:!0}):e,r)),Ye=r=>ue(mt({},"__esModule",{value:!0}),r);var yn={};Ze(yn,{BrowserCryptoProvider:()=>Wt,CLOUD_WALLET_PROVIDERS:()=>lr,CacheTtl:()=>ne,EvmWalletChainNames:()=>pr,NodeCryptoProvider:()=>vt,WARP_LANGUAGES:()=>wr,WarpAssets:()=>I,WarpBrandBuilder:()=>Yt,WarpBuilder:()=>te,WarpCache:()=>ut,WarpCacheKey:()=>Et,WarpChainDisplayNames:()=>Ae,WarpChainLogos:()=>Ce,WarpChainName:()=>ve,WarpChainResolver:()=>rt,WarpClient:()=>oe,WarpCompositeResolver:()=>nt,WarpConfig:()=>D,WarpConstants:()=>c,WarpExecutor:()=>gt,WarpFactory:()=>Q,WarpIndex:()=>ft,WarpInputTypes:()=>y,WarpInterpolator:()=>$,WarpLinkBuilder:()=>z,WarpLinkDetecter:()=>ht,WarpLogger:()=>C,WarpPlatformName:()=>Nt,WarpPlatforms:()=>Bt,WarpProtocolVersions:()=>M,WarpSerializer:()=>w,WarpTypeRegistry:()=>pe,WarpValidator:()=>pt,address:()=>an,applyOutputToMessages:()=>wt,asset:()=>Zt,biguint:()=>rn,bool:()=>nn,buildGeneratedFallbackWarpIdentifier:()=>Oe,buildGeneratedSourceWarpIdentifier:()=>Mr,buildInputsContext:()=>ot,buildMappedOutput:()=>J,buildNestedPayload:()=>Se,bytesToBase64:()=>Wr,bytesToHex:()=>xe,checkWarpAssetBalance:()=>Jr,cleanWarpIdentifier:()=>X,createAuthHeaders:()=>St,createAuthMessage:()=>It,createCryptoProvider:()=>Ar,createDefaultWalletProvider:()=>_r,createHttpAuthHeaders:()=>Fr,createSignableMessage:()=>Re,createWarpI18nText:()=>Sr,createWarpIdentifier:()=>Ct,doesWarpRequireWallet:()=>xr,evaluateOutputCommon:()=>Gt,evaluateWhenCondition:()=>Dt,extractCollectOutput:()=>Y,extractIdentifierInfoFromUrl:()=>Z,extractPromptOutput:()=>_t,extractQueryStringFromIdentifier:()=>kt,extractQueryStringFromUrl:()=>jt,extractResolvedInputValues:()=>V,extractWarpSecrets:()=>Cr,findWarpAdapterForChain:()=>W,getChainDisplayName:()=>ur,getChainLogo:()=>dr,getCryptoProvider:()=>Vt,getEventNameFromWarp:()=>gr,getGeneratedSourceWarpName:()=>Ne,getLatestProtocolIdentifier:()=>it,getNextInfo:()=>G,getProviderConfig:()=>Lr,getRandomBytes:()=>Ht,getRandomHex:()=>Lt,getRequiredAssetIds:()=>Ve,getWalletFromConfigOrFail:()=>tr,getWarpActionByIndex:()=>B,getWarpBrandLogoUrl:()=>fr,getWarpChainAssetLogoUrl:()=>hr,getWarpChainInfoLogoUrl:()=>mr,getWarpIdentifierWithQuery:()=>Rr,getWarpInfoFromIdentifier:()=>O,getWarpPrimaryAction:()=>E,getWarpWalletAddress:()=>de,getWarpWalletAddressFromConfig:()=>S,getWarpWalletExternalId:()=>he,getWarpWalletExternalIdFromConfig:()=>me,getWarpWalletExternalIdFromConfigOrFail:()=>nr,getWarpWalletMnemonic:()=>fe,getWarpWalletMnemonicFromConfig:()=>rr,getWarpWalletPrivateKey:()=>ge,getWarpWalletPrivateKeyFromConfig:()=>er,handleX402Payment:()=>Xt,hasInputPrefix:()=>Nr,hex:()=>sn,initializeWalletCache:()=>Gr,isEqualWarpIdentifier:()=>Pr,isGeneratedSourcePrivateIdentifier:()=>zr,isPlatformValue:()=>Ee,isWarpActionAutoExecute:()=>At,isWarpI18nText:()=>Ir,isWarpWalletReadOnly:()=>ir,mergeNestedPayload:()=>zt,normalizeAndValidateMnemonic:()=>or,normalizeMnemonic:()=>ye,option:()=>on,parseOutputOutIndex:()=>Te,parseSignedMessage:()=>Dr,parseWarpQueryStringToObject:()=>Mt,removeWarpChainPrefix:()=>Er,removeWarpWalletFromConfig:()=>sr,replacePlaceholders:()=>j,replacePlaceholdersInWhenExpression:()=>Ut,resolvePlatformValue:()=>Jt,resolveWarpText:()=>st,safeWindow:()=>$t,setCryptoProvider:()=>yr,setWarpWalletInConfig:()=>ar,shiftBigintBy:()=>at,splitInput:()=>xt,stampGeneratedWarpMeta:()=>qr,string:()=>Xr,struct:()=>ln,testCryptoAvailability:()=>vr,toInputPayloadValue:()=>Pe,toPreviewText:()=>Ft,tuple:()=>pn,uint16:()=>Yr,uint32:()=>tn,uint64:()=>en,uint8:()=>Zr,validateMnemonicLength:()=>We,validateSignedMessage:()=>Ur,vector:()=>cn,withAdapterFallback:()=>cr});module.exports=Ye(yn);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 tr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},de=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>de(r.user?.wallets?.[t]||null),ge=r=>r?typeof r=="string"?r:r.privateKey||null:null,fe=r=>r?typeof r=="string"?r:r.mnemonic||null:null,he=r=>r?typeof r=="string"?r:r.externalId||null:null,er=(r,t)=>ge(r.user?.wallets?.[t]||null)?.trim()||null,rr=(r,t)=>fe(r.user?.wallets?.[t]||null)?.trim()||null,me=(r,t)=>he(r.user?.wallets?.[t]||null)?.trim()||null,nr=(r,t)=>{let e=me(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},ir=r=>typeof r=="string",ar=(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]},ye=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},We=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},or=(r,t=24)=>{let e=ye(r);return We(e,t),e};var ve=(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))(ve||{}),Nt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Nt||{}),Bt=Object.values(Nt),pr=["ethereum","base","arbitrum","polygon","somnia","tempo"],lr=["coinbase","privy","gaupa"],c={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>S(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"}},y={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"},$t=typeof window<"u"?window:{open:()=>{}};var M={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${M.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${M.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",c.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var cr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var yt="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",I={baseUrl:yt,chainLogo:r=>`${yt}/chains/logos/${r}`,tokenLogo:r=>`${yt}/tokens/logos/${r}`,walletLogo:r=>`${yt}/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"},ur=r=>Ae[r]??r.charAt(0).toUpperCase()+r.slice(1),Ce={ethereum:{light:I.chainLogo("ethereum-white.svg"),dark:I.chainLogo("ethereum-black.svg")},base:{light:I.chainLogo("base-white.svg"),dark:I.chainLogo("base-black.svg")},arbitrum:I.chainLogo("arbitrum.svg"),polygon:I.chainLogo("polygon.svg"),somnia:I.chainLogo("somnia.png"),tempo:{light:I.chainLogo("tempo-white.svg"),dark:I.chainLogo("tempo-black.svg")},multiversx:I.chainLogo("multiversx.svg"),claws:I.chainLogo("claws.png"),sui:I.chainLogo("sui.svg"),solana:I.chainLogo("solana.svg"),near:{light:I.chainLogo("near-white.svg"),dark:I.chainLogo("near-black.svg")},fastset:{light:I.chainLogo("fastset-white.svg"),dark:I.chainLogo("fastset-black.svg")}},dr=(r,t="dark")=>{let e=Ce[r];return typeof e=="string"?e:t==="dark"?e.dark:e.light};var gr=(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 Ot=(r,t)=>r[t]??r.default??Object.values(r)[0],fr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:Ot(r.logo,e)},hr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Ot(r.logoUrl,e)},mr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Ot(r.logoUrl,e)};var Wt=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}},vt=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 Vt(){if(q)return q;if(typeof window<"u"&&window.crypto)return q=new Wt,q;if(typeof process<"u"&&process.versions?.node)return q=new vt,q;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function yr(r){q=r}async function Ht(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Vt()).getRandomBytes(r)}function xe(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 Lt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Ht(r/2,t);return xe(e)}async function vr(){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 Ht(16),r.randomBytes=!0}catch{}return r}function Ar(){return Vt()}var Cr=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 W=(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},it=r=>{if(r==="warp")return`warp:${M.Warp}`;if(r==="brand")return`brand:${M.Brand}`;if(r==="abi")return`abi:${M.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},B=(r,t)=>r?.actions[t-1],E=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}},At=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=E(t);return r===e}return!0},at=(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)},Ft=(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},j=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),Ut=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),xr=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}},Dt=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 wr={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"},st=(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""},Ir=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Sr=r=>r;var X=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,Pr=(r,t)=>!r||!t?!1:X(r)===X(t),Ct=(r,t,e)=>{let n=X(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=X(n),a=i.split("?")[0],s=we(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}},Z=(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,Tr=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},we=r=>{let t=Tr(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=we(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}},kt=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},Mt=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},Er=(r,t)=>{let e=O(r,t);return(e?e.identifierBase:X(r)).trim()},Rr=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 xt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Nr=r=>{let t=new Set(Object.values(y));if(!r.includes(c.ArgParamsSeparator))return!1;let e=xt(r)[0];return t.has(e)};var wt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=st(a,e);return[i,j(s,t)]});return Object.fromEntries(n)};var Ie=K(require("qr-code-styling"),1);var z=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!Z(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||D.DefaultClientUrl(this.config.env),a=W(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=W(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=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Ie.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 Br="https://",G=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(Br))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=j(s,{...e.vars,...i});return[{identifier:f,url:qt(t,f,r)}]}let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let f=j(p,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:qt(t,v,r)}]}let o=l[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let g=Array.isArray(i[d])?i[d]:[i[d]];if(g.length===0)return[];let h=l.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return g.map(f=>{let v=p;for(let{regex:T,field:F}of h){let x=F?$r(f,F):f;if(x==null)return null;v=v.replace(T,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${s}?${v}`:s;return{identifier:A,url:qt(t,A,r)}}).filter(f=>f!==null)},qt=(r,t,e)=>{let[n,i]=t.split("?"),a=O(n,e.defaultChain)||{chain:c.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=W(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(/\/\?/,"?")},$r=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var _=class _{static debug(...t){_.isTestEnv||console.debug(...t)}static info(...t){_.isTestEnv||console.info(...t)}static warn(...t){_.isTestEnv||console.warn(...t)}static error(...t){_.isTestEnv||console.error(...t)}};_.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=_;function Se(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 zt(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]=zt(e[n],t[n]):e[n]=t[n]}),e}function Pe(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 J(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=Pe(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let s=Se(n.input.position,i,a);e=zt(e,s)}else e[i]=a}),e}function ot(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 be=(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=Te(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}},Y=async(r,t,e,n,i,a)=>{let s=(d,g)=>g.reduce((h,m)=>h&&h[m]!==void 0?h[m]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:u}=be(r,e,p);return{values:{string:l,native:o,mapped:J(n,i)},output:await Gt(r,u,t,e,n,i,a)}},Gt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Or(p,r,n,i,a),p=await Vr(r,p,e,i,a,s.transform?.runner||null),p},Or=(r,t,e,n,i)=>{let a={...r},s=B(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},Vr=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:Hr(e),inputs:ot(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,l),l[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},Hr=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},_t=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=be(r,e,s),u=await Gt(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:l,mapped:J(n,i)},output:u}},Te=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 Ee=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Bt.some(t=>t in r),Jt=(r,t)=>{if(!Ee(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 Lr=(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 Re(r,t,e,n=5){let i=await Lt(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 It(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Re(r,i,e,5)}function St(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Fr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await It(r,e,n),p=await t(i);return St(r,p,a,s)}function Ur(r){let t=new Date(r).getTime();return Date.now()<t}function Dr(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 Ne=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",jr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Be=(r,t=24)=>{let e=jr(r);return e?e.slice(0,t):"action"},$e=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)},kr=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()}},Mr=(r,t,e)=>{let n=Be((e||t||"").trim()||"action"),i=`${r.type}|${kr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=$e(i);return`private_src_${n}_${a}`},Oe=r=>{let t=Ne(r),e=Be(t),n=$e(t.trim().toLowerCase());return`private_gen_${e}_${n}`},qr=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Oe(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},zr=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Gr(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 _r(r,t,e){return null}var Ve=(r,t)=>{let e=null;try{e=E(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]:[]},Jr=async(r,t,e,n)=>{try{let i=W(e,n),a=Ve(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 Qt=require("@x402/core/client"),Kt=require("@x402/core/http");async function Xt(r,t,e,n,i){let a=await Qr(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([l,o])=>{s.set(l,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var Qr=async(r,t)=>{let e=await Kr(r),i=new Kt.x402HTTPClient(new Qt.x402Client).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new Qt.x402Client,p=await a.wallet.registerX402Handlers(s),l=i.accepts.find(g=>g?.network&&p[g.network]);if(!l?.network)continue;p[l.network]();let o=new Kt.x402HTTPClient(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${l.network} scheme`),d}catch{continue}return null},Kr=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===y.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===y.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===y.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(y.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=a.startsWith(y.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===y.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?y.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):y.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===y.Option){let[a,s]=i.split(c.ArgParamsSeparator);return[y.Option+c.ArgParamsSeparator+a,s||null]}if(n===y.Vector){let a=i.indexOf(c.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(y.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(s+c.ArgParamsSeparator+d)[1]);return[y.Vector+c.ArgParamsSeparator+s,u]}else if(n.startsWith(y.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(y.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===y.String)return[n,i];if(n===y.Uint8||n===y.Uint16||n===y.Uint32)return[n,Number(i)];if(n===y.Uint64||n===y.Uint128||n===y.Uint256||n===y.Biguint)return[n,BigInt(i||0)];if(n===y.Bool)return[n,i==="true"];if(n===y.Address)return[n,i];if(n===y.Hex)return[n,i];if(n===y.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"?[y.Uint32,t]:typeof t=="bigint"?[y.Uint64,t]:typeof t=="boolean"?[y.Bool,t]:[typeof t,t]}};var Xr=r=>new w().nativeToString(y.String,r),Zr=r=>new w().nativeToString(y.Uint8,r),Yr=r=>new w().nativeToString(y.Uint16,r),tn=r=>new w().nativeToString(y.Uint32,r),en=r=>new w().nativeToString(y.Uint64,r),rn=r=>new w().nativeToString(y.Biguint,r),nn=r=>new w().nativeToString(y.Bool,r),an=r=>new w().nativeToString(y.Address,r),Zt=r=>new w().nativeToString(y.Asset,r),sn=r=>new w().nativeToString(y.Hex,r),on=(r,t)=>{if(t===null)return y.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return y.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+a},pn=(...r)=>new w().nativeToString(y.Tuple,r),ln=r=>new w().nativeToString(y.Struct,r),cn=r=>new w().nativeToString(y.Vector,r);var He=K(require("ajv"),1);var Yt=class{constructor(t){this.pendingBrand={protocol:it("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 He.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var Le=K(require("ajv"),1);var pt=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}=E(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,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"),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 Le.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 te=class{constructor(t){this.config=t;this.pendingWarp={protocol:it("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 Ft(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 pt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
- `))}};var P=require("fs"),et=require("path");var ee="$bigint:",Pt=(r,t)=>typeof t=="bigint"?ee+t.toString():t,tt=(r,t)=>typeof t=="string"&&t.startsWith(ee)?BigInt(t.slice(ee.length)):t;var bt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,et.resolve)(n):(0,et.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,P.existsSync)(this.cacheDir)||(0,P.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,et.join)(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!(0,P.existsSync)(e))return null;let n=(0,P.readFileSync)(e,"utf-8"),i=JSON.parse(n,tt);return i.expiresAt!==null&&Date.now()>i.expiresAt?((0,P.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,P.writeFileSync)(a,JSON.stringify(i,Pt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);(0,P.existsSync)(e)&&(0,P.unlinkSync)(e)}catch{}}async keys(t){try{let e=(0,P.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,P.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,P.unlinkSync)((0,et.join)(this.cacheDir,e))})}catch{}}};var lt=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,tt);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,Pt))}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 L=class L{constructor(t,e){}async get(t){let e=L.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(L.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;L.cache.set(t,{value:e,expiresAt:i})}async delete(t){L.cache.delete(t)}async keys(t){let e=Array.from(L.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){L.cache.clear()}};L.cache=new Map;var ct=L;var Fe=require("fs"),re=require("path");var Tt=class{constructor(t,e){let n=e?.path?(0,re.resolve)(e.path):(0,re.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,Fe.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,tt)))}catch(e){return C.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 ne={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Et={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}`},ut=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new lt(t,e):e?.type==="memory"?new ct(t,e):e?.type==="static"?new Tt(t,e):e?.type==="filesystem"?new bt(t,e):typeof window<"u"&&window.localStorage?new lt(t,e):new ct(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 dt={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},ie={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},ae=(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)},se=r=>{try{return JSON.parse(r)}catch{return null}},un=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 It(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(St(n,d,o,u)).forEach(([g,h])=>s.set(g,h))}let p=ae(e.resolvedInputs,dt.Headers,i);if(p){let l=se(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},dn=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===ie.Get){let s=ae(e.resolvedInputs,dt.Queries,i);if(s){let p=se(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},gn=(r,t,e,n,i)=>{if(r===ie.Get)return;let a=ae(t.resolvedInputs,dt.Payload,n);if(a&&se(a)!==null)return a;let{[dt.Payload]:s,[dt.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},Ue=async(r,t,e,n,i,a,s,p)=>{let l=t.method||ie.Get,o=await un(r,t,e,n,a,p),u=dn(r,t,e,l,a),d=gn(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(`\\{\\{${fn(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=S(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,h=e.queries?.[o]??null??d;h!=null&&a(s,h)}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 j(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=W(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}},fn=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var hn=["collect","compute","mcp","state","mount","unmount"],Q=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new ut(t.env,t.cache)}getSerializer(){return this.serializer}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(Et.WarpExecutable(t,e||"",n))||[];return V(i)}async createExecutable(t,e,n,i={}){let a=B(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=W(s.name,this.adapters),l=new $(this.config,p,this.adapters),o=await l.apply(t,i),u=B(o,e),{action:d,index:g}=E(o),h=this.getStringTypedInputs(d,n),m=await this.getResolvedInputs(s.name,d,h,l,i.queries),f=await this.getModifiedInputs(m),v=[],A=[];g===e-1?(v=m,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,l,i.queries),A=await this.getModifiedInputs(v));let T=A.find(b=>b.input.position==="receiver"||b.input.position==="destination")?.value,F=this.getDestinationFromAction(u),x=T?this.serializer.stringToNative(T)[1]:F;if(x&&(x=l.applyInputs(x,A,this.serializer,f)),!x&&!hn.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let U=this.getPreparedArgs(u,A);U=U.map(b=>l.applyInputs(b,A,this.serializer,f));let H=A.find(b=>b.input.position==="value")?.value||null,R="value"in u?u.value:null,N=H?.split(c.ArgParamsSeparator)[1]||R||"0",k=l.applyInputs(N,A,this.serializer,f),De=BigInt(k),je=A.filter(b=>b.input.position==="transfer"&&b.value).map(b=>b.value),ke=[...("transfers"in u?u.transfers:[])||[],...je||[]].map(b=>{let Rt=l.applyInputs(b,A,this.serializer,f),Ge=Rt.startsWith(`asset${c.ArgParamsSeparator}`)?Rt:`asset${c.ArgParamsSeparator}${Rt}`;return this.serializer.stringToNative(Ge)[1]}),Me=A.find(b=>b.input.position==="data")?.value,qe="data"in u?u.data||"":null,le=Me||qe||null,ze=le?l.applyInputs(le,A,this.serializer,f):null,ce={adapter:p,warp:o,chain:s,action:e,destination:x,args:U,value:De,transfers:ke,data:ze,resolvedInputs:A};return await this.cache.set(Et.WarpExecutable(this.config.env,o.meta?.hash||"",e),ce.resolvedInputs,ne.OneWeek),ce}async getChainInfoForWarp(t,e){if(t.chain)return W(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=S(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,h=a?.[g],m=this.url.searchParams.get(g),f=h||m;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let g=o(u,d),h=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:g||(h!==void 0?this.serializer.nativeToString(u.type,h):null)}})}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=at(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=at(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=ot(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]=xt(e),a=W(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=at(p,o.decimals);return Zt({...o,amount:u})}else return e}catch(n){throw C.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input: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 W(s,this.adapters).chainInfo}};var gt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new Q(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:g}=E(t);for(let h=1;h<=t.actions.length;h++){let m=B(t,h);if(!At(m,t))continue;let{tx:f,chain:v,immediateExecution:A,executable:T}=await this.executeAction(t,h,e,u);f&&i.push(f),v&&(a=v),A&&s.push(A),T&&h===g+1&&T.resolvedInputs&&(p=V(T.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 h=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(h))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=B(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):$t.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=W(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=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!At(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let d=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),g={status:"error",warp:t,action:o,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:g})),g}let u=await i.output.getActionExecution(t,o,l.tx);return u.next=G(this.config,this.adapters,t,o,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(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=S(this.config,t.chain.name),i=B(t.warp,t.action),a=this.factory.getSerializer(),s=J(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 Y(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async executeCompute(t){let e=S(this.config,t.chain.name),n=this.factory.getSerializer(),i=J(t.resolvedInputs,n),{values:a,output:s}=await Y(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,W(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await Ue(s,e,t,n,i,p,a,async g=>await this.callHandler(()=>this.handlers?.onSignRequest?.(g)));C.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:u,body:d});try{let h=await fetch(l,{method:o,headers:u,body:d});C.debug("Collect response status",{status:h.status}),h.status===402&&(h=await Xt(h,l,o,d,this.adapters));let m=await h.json();C.debug("Collect response content",{content:m});let{values:f,output:v}=await Y(t.warp,m,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),h.ok?"success":"error",f,v,m)}catch(g){C.error("WarpActionExecutor: Error executing collect",g);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:g},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=S(this.config,t.chain.name),i=B(t.warp,t.action);if(!i.destination){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("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let m=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:m}}let p=this.factory.getSerializer(),l=new $(this.config,W(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(([h,m])=>{let f=l.applyInputs(m,t.resolvedInputs,this.factory.getSerializer());g[h]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:g});try{let h=new s(new URL(u),{requestInit:{headers:g}}),m=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await m.connect(h);let f={};t.resolvedInputs.forEach(({input:x,value:U})=>{if(U&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let H=x.position.replace("payload:",""),[R,N]=p.stringToNative(U);if(R==="string")f[H]=String(N);else if(R==="bool")f[H]=!!N;else if(R==="uint8"||R==="uint16"||R==="uint32"||R==="uint64"||R==="uint128"||R==="uint256"||R==="biguint"){let k=Number(N);f[H]=(Number.isInteger(k),k)}else f[H]=N}}),e&&Object.assign(f,e);let v=await m.callTool({name:d,arguments:f});await m.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:T,output:F}=await Y(t.warp,A,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",T,F,v)}catch(h){C.error("WarpExecutor: Error executing MCP",h);let m=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:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}buildCollectResult(t,e,n,i,a,s){let p=G(this.config,this.adapters,t.warp,t.action,a),l=V(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:wt(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=W(s.name,this.adapters),l=new $(this.config,p,this.adapters),o=await l.apply(t,a),u=B(o,n),{action:d}=E(o),g=this.factory.getStringTypedInputs(d,i),h=await this.factory.getResolvedInputs(s.name,d,g,l,a.queries),m=await this.factory.getModifiedInputs(h),f=m;if(e.inputs&&e.inputs.length>0){let N=this.factory.getStringTypedInputs(e,i),k=await this.factory.getResolvedInputs(s.name,e,N,l,a.queries);f=await this.factory.getModifiedInputs(k)}let v=Jt(u.prompt,this.config.platform),A=l.applyInputs(v,f,this.factory.getSerializer(),m),T=V(f),F=S(this.config,s.name),x=this.factory.getSerializer(),{values:U,output:H}=await _t(o,A,n,f,x,this.config),R=f.find(N=>N.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:F,txHash:null,tx:null,next:G(this.config,this.adapters,o,n,H),values:U,output:H,messages:wt(o,H,this.config),destination:R,resolvedInputs:T}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,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=W(p.name,this.adapters),o=new $(this.config,l,this.adapters),{action:u}=E(t),d=this.factory.getStringTypedInputs(u,n),g=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),h=await this.factory.getModifiedInputs(g),m;if(a)m=a;else{let T=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);m=await this.factory.getModifiedInputs(T)}let f=o.buildInputBag(m,this.factory.getSerializer(),h),v={...i.envs??{},...f},A=Ut(e.when,v);return Dt(A)}};var ft=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw C.error("WarpIndex: Error searching for warps: ",i),i}}};var ht=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!Z(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)?Z(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):kt(i.identifier);if(this.resolver){let m=null;if(a==="hash")m=await this.resolver.getByHash(s,e);else if(a==="alias"){let f=`${i.chain}:${s}`;m=await this.resolver.getByAlias(f,e)||await this.resolver.getByAlias(s,e)}m&&(p=m.warp,l=m.registryInfo,o=m.brand)}else{let m=W(i.chain,this.adapters);if(a==="hash"){p=await m.builder().createFromTransactionHash(s,e);let f=await m.registry.getInfoByHash(s,e);l=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await m.registry.getInfoByAlias(s,e);l=f.registryInfo,o=f.brand,f.registryInfo&&(p=await m.builder().createFromTransactionHash(f.registryInfo.hash,e))}}if(p&&p.meta&&(mn(p,i.chain,l,i.identifier),p.meta.query=u?Mt(u):null),!p)return n;let d=p.chain||i.chain,g=this.adapters.find(m=>m.chainInfo.name.toLowerCase()===d.toLowerCase()),h=g?await new $(this.config,g,this.adapters).apply(p):p;return{match:!0,url:t,warp:h,chain:d,registryInfo:l,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},mn=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?Ct(null,"alias",e.alias):Ct(t,"hash",e?.hash??n))};var oe=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 gt(this.config,this.chains,t)}async detectWarp(t,e){return new ht(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 m=await fetch(t);if(!m.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await m.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 m=>{await l.evaluateOutput(p,m)},resolvedInputs:g}}async createInscriptionTransaction(t,e){return await W(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return W(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 W(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(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 W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??E(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=G(this.config,this.chains,e,a,p.output),p}async getRegistry(t){let e=W(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return W(t,this.chains).dataLoader}getWallet(t){return W(t,this.chains).wallet}get factory(){return new Q(this.config,this.chains)}get index(){return new ft(this.config)}get linkBuilder(){return new z(this.config,this.chains)}createBuilder(t){return W(t,this.chains).builder()}createAbiBuilder(t){return W(t,this.chains).abiBuilder()}createBrandBuilder(t){return W(t,this.chains).brandBuilder()}createSerializer(t){return W(t,this.chains).serializer}resolveText(t){return st(t,this.config)}};var pe=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,CLOUD_WALLET_PROVIDERS,CacheTtl,EvmWalletChainNames,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,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getRequiredAssetIds,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpIdentifierWithQuery,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isPlatformValue,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,removeWarpWalletFromConfig,replacePlaceholders,replacePlaceholdersInWhenExpression,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 _e=Object.create;var mt=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var Ze=(r,t)=>{for(var e in t)mt(r,e,{get:t[e],enumerable:!0})},ue=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Qe(t))!Xe.call(r,i)&&i!==e&&mt(r,i,{get:()=>t[i],enumerable:!(n=Je(t,i))||n.enumerable});return r};var K=(r,t,e)=>(e=r!=null?_e(Ke(r)):{},ue(t||!r||!r.__esModule?mt(e,"default",{value:r,enumerable:!0}):e,r)),Ye=r=>ue(mt({},"__esModule",{value:!0}),r);var Wn={};Ze(Wn,{BrowserCryptoProvider:()=>Wt,CLOUD_WALLET_PROVIDERS:()=>cr,CacheTtl:()=>ne,EvmWalletChainNames:()=>pr,MultiversxWalletChainNames:()=>lr,NodeCryptoProvider:()=>vt,WARP_LANGUAGES:()=>Ir,WarpAssets:()=>I,WarpBrandBuilder:()=>Yt,WarpBuilder:()=>te,WarpCache:()=>ut,WarpCacheKey:()=>Et,WarpChainDisplayNames:()=>Ce,WarpChainLogos:()=>Ae,WarpChainName:()=>ve,WarpChainResolver:()=>rt,WarpClient:()=>oe,WarpCompositeResolver:()=>nt,WarpConfig:()=>D,WarpConstants:()=>c,WarpExecutor:()=>gt,WarpFactory:()=>Q,WarpIndex:()=>ft,WarpInputTypes:()=>y,WarpInterpolator:()=>$,WarpLinkBuilder:()=>z,WarpLinkDetecter:()=>ht,WarpLogger:()=>A,WarpPlatformName:()=>Nt,WarpPlatforms:()=>Bt,WarpProtocolVersions:()=>k,WarpSerializer:()=>w,WarpTypeRegistry:()=>pe,WarpValidator:()=>pt,address:()=>sn,applyOutputToMessages:()=>wt,asset:()=>Zt,biguint:()=>nn,bool:()=>an,buildGeneratedFallbackWarpIdentifier:()=>Oe,buildGeneratedSourceWarpIdentifier:()=>qr,buildInputsContext:()=>ot,buildMappedOutput:()=>J,buildNestedPayload:()=>Se,bytesToBase64:()=>vr,bytesToHex:()=>xe,checkWarpAssetBalance:()=>Qr,cleanWarpIdentifier:()=>X,createAuthHeaders:()=>St,createAuthMessage:()=>It,createCryptoProvider:()=>Ar,createDefaultWalletProvider:()=>Jr,createHttpAuthHeaders:()=>Ur,createSignableMessage:()=>Re,createWarpI18nText:()=>Pr,createWarpIdentifier:()=>At,doesWarpRequireWallet:()=>wr,evaluateOutputCommon:()=>Gt,evaluateWhenCondition:()=>Dt,extractCollectOutput:()=>Y,extractIdentifierInfoFromUrl:()=>Z,extractPromptOutput:()=>_t,extractQueryStringFromIdentifier:()=>Mt,extractQueryStringFromUrl:()=>jt,extractResolvedInputValues:()=>V,extractWarpSecrets:()=>xr,findWarpAdapterForChain:()=>W,getChainDisplayName:()=>dr,getChainLogo:()=>gr,getCryptoProvider:()=>Vt,getEventNameFromWarp:()=>fr,getGeneratedSourceWarpName:()=>Ne,getLatestProtocolIdentifier:()=>it,getNextInfo:()=>G,getProviderConfig:()=>Fr,getRandomBytes:()=>Ht,getRandomHex:()=>Lt,getRequiredAssetIds:()=>Ve,getWalletFromConfigOrFail:()=>tr,getWarpActionByIndex:()=>B,getWarpBrandLogoUrl:()=>hr,getWarpChainAssetLogoUrl:()=>mr,getWarpChainInfoLogoUrl:()=>yr,getWarpIdentifierWithQuery:()=>Nr,getWarpInfoFromIdentifier:()=>O,getWarpPrimaryAction:()=>E,getWarpWalletAddress:()=>de,getWarpWalletAddressFromConfig:()=>S,getWarpWalletExternalId:()=>he,getWarpWalletExternalIdFromConfig:()=>me,getWarpWalletExternalIdFromConfigOrFail:()=>nr,getWarpWalletMnemonic:()=>fe,getWarpWalletMnemonicFromConfig:()=>rr,getWarpWalletPrivateKey:()=>ge,getWarpWalletPrivateKeyFromConfig:()=>er,handleX402Payment:()=>Xt,hasInputPrefix:()=>Br,hex:()=>on,initializeWalletCache:()=>_r,isEqualWarpIdentifier:()=>br,isGeneratedSourcePrivateIdentifier:()=>Gr,isPlatformValue:()=>Ee,isWarpActionAutoExecute:()=>Ct,isWarpI18nText:()=>Sr,isWarpWalletReadOnly:()=>ir,mergeNestedPayload:()=>zt,normalizeAndValidateMnemonic:()=>or,normalizeMnemonic:()=>ye,option:()=>pn,parseOutputOutIndex:()=>Te,parseSignedMessage:()=>jr,parseWarpQueryStringToObject:()=>kt,removeWarpChainPrefix:()=>Rr,removeWarpWalletFromConfig:()=>sr,replacePlaceholders:()=>j,replacePlaceholdersInWhenExpression:()=>Ut,resolvePlatformValue:()=>Jt,resolveWarpText:()=>st,safeWindow:()=>$t,setCryptoProvider:()=>Wr,setWarpWalletInConfig:()=>ar,shiftBigintBy:()=>at,splitInput:()=>xt,stampGeneratedWarpMeta:()=>zr,string:()=>Zr,struct:()=>cn,testCryptoAvailability:()=>Cr,toInputPayloadValue:()=>Pe,toPreviewText:()=>Ft,tuple:()=>ln,uint16:()=>tn,uint32:()=>en,uint64:()=>rn,uint8:()=>Yr,validateMnemonicLength:()=>We,validateSignedMessage:()=>Dr,vector:()=>un,withAdapterFallback:()=>ur});module.exports=Ye(Wn);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 tr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},de=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>de(r.user?.wallets?.[t]||null),ge=r=>r?typeof r=="string"?r:r.privateKey||null:null,fe=r=>r?typeof r=="string"?r:r.mnemonic||null:null,he=r=>r?typeof r=="string"?r:r.externalId||null:null,er=(r,t)=>ge(r.user?.wallets?.[t]||null)?.trim()||null,rr=(r,t)=>fe(r.user?.wallets?.[t]||null)?.trim()||null,me=(r,t)=>he(r.user?.wallets?.[t]||null)?.trim()||null,nr=(r,t)=>{let e=me(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},ir=r=>typeof r=="string",ar=(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]},ye=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},We=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},or=(r,t=24)=>{let e=ye(r);return We(e,t),e};var ve=(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))(ve||{}),Nt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Nt||{}),Bt=Object.values(Nt),pr=["ethereum","base","arbitrum","polygon","somnia","tempo"],lr=["multiversx","claws"],cr=["coinbase","privy","gaupa"],c={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>S(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"}},y={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"},$t=typeof window<"u"?window:{open:()=>{}};var k={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${k.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${k.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 ur=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var yt="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",I={baseUrl:yt,chainLogo:r=>`${yt}/chains/logos/${r}`,tokenLogo:r=>`${yt}/tokens/logos/${r}`,walletLogo:r=>`${yt}/wallets/logos/${r}`},Ce={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"},dr=r=>Ce[r]??r.charAt(0).toUpperCase()+r.slice(1),Ae={ethereum:{light:I.chainLogo("ethereum-white.svg"),dark:I.chainLogo("ethereum-black.svg")},base:{light:I.chainLogo("base-white.svg"),dark:I.chainLogo("base-black.svg")},arbitrum:I.chainLogo("arbitrum.svg"),polygon:I.chainLogo("polygon.svg"),somnia:I.chainLogo("somnia.png"),tempo:{light:I.chainLogo("tempo-white.svg"),dark:I.chainLogo("tempo-black.svg")},multiversx:I.chainLogo("multiversx.svg"),claws:I.chainLogo("claws.png"),sui:I.chainLogo("sui.svg"),solana:I.chainLogo("solana.svg"),near:{light:I.chainLogo("near-white.svg"),dark:I.chainLogo("near-black.svg")},fastset:{light:I.chainLogo("fastset-white.svg"),dark:I.chainLogo("fastset-black.svg")}},gr=(r,t="dark")=>{let e=Ae[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var fr=(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 Ot=(r,t)=>r[t]??r.default??Object.values(r)[0],hr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:Ot(r.logo,e)},mr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Ot(r.logoUrl,e)},yr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Ot(r.logoUrl,e)};var Wt=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}},vt=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 Vt(){if(q)return q;if(typeof window<"u"&&window.crypto)return q=new Wt,q;if(typeof process<"u"&&process.versions?.node)return q=new vt,q;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Wr(r){q=r}async function Ht(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Vt()).getRandomBytes(r)}function xe(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 vr(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 Lt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Ht(r/2,t);return xe(e)}async function Cr(){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 Ht(16),r.randomBytes=!0}catch{}return r}function Ar(){return Vt()}var xr=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 W=(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},it=r=>{if(r==="warp")return`warp:${k.Warp}`;if(r==="brand")return`brand:${k.Brand}`;if(r==="abi")return`abi:${k.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},B=(r,t)=>r?.actions[t-1],E=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}},Ct=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=E(t);return r===e}return!0},at=(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)},Ft=(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},j=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),Ut=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),wr=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}},Dt=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 Ir={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"},st=(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""},Sr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Pr=r=>r;var X=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,br=(r,t)=>!r||!t?!1:X(r)===X(t),At=(r,t,e)=>{let n=X(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=X(n),a=i.split("?")[0],s=we(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=Tr(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}},Z=(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)},Tr=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Er=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},we=r=>{let t=Er(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=we(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}},Mt=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},Rr=(r,t)=>{let e=O(r,t);return(e?e.identifierBase:X(r)).trim()},Nr=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 xt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Br=r=>{let t=new Set(Object.values(y));if(!r.includes(c.ArgParamsSeparator))return!1;let e=xt(r)[0];return t.has(e)};var wt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=st(a,e);return[i,j(s,t)]});return Object.fromEntries(n)};var Ie=K(require("qr-code-styling"),1);var z=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!Z(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||D.DefaultClientUrl(this.config.env),a=W(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=W(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=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Ie.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 $r="https://",G=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith($r))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=j(s,{...e.vars,...i});return[{identifier:f,url:qt(t,f,r)}]}let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let f=j(p,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:qt(t,v,r)}]}let o=l[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let g=Array.isArray(i[d])?i[d]:[i[d]];if(g.length===0)return[];let h=l.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),C=v&&v[1]||"";return{placeholder:f,field:C?C.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return g.map(f=>{let v=p;for(let{regex:T,field:F}of h){let x=F?Or(f,F):f;if(x==null)return null;v=v.replace(T,x)}if(v.includes("{{")||v.includes("}}"))return null;let C=v?`${s}?${v}`:s;return{identifier:C,url:qt(t,C,r)}}).filter(f=>f!==null)},qt=(r,t,e)=>{let[n,i]=t.split("?"),a=O(n,e.defaultChain)||{chain:c.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=W(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(/\/\?/,"?")},Or=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var _=class _{static debug(...t){_.isTestEnv||console.debug(...t)}static info(...t){_.isTestEnv||console.info(...t)}static warn(...t){_.isTestEnv||console.warn(...t)}static error(...t){_.isTestEnv||console.error(...t)}};_.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var A=_;function Se(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 zt(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]=zt(e[n],t[n]):e[n]=t[n]}),e}function Pe(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 J(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=Pe(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let s=Se(n.input.position,i,a);e=zt(e,s)}else e[i]=a}),e}function ot(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 be=(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=Te(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}},Y=async(r,t,e,n,i,a)=>{let s=(d,g)=>g.reduce((h,m)=>h&&h[m]!==void 0?h[m]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:u}=be(r,e,p);return{values:{string:l,native:o,mapped:J(n,i)},output:await Gt(r,u,t,e,n,i,a)}},Gt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Vr(p,r,n,i,a),p=await Hr(r,p,e,i,a,s.transform?.runner||null),p},Vr=(r,t,e,n,i)=>{let a={...r},s=B(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:Lr(e),inputs:ot(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},Lr=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},_t=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=be(r,e,s),u=await Gt(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:l,mapped:J(n,i)},output:u}},Te=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 Ee=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Bt.some(t=>t in r),Jt=(r,t)=>{if(!Ee(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 Fr=(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 Re(r,t,e,n=5){let i=await Lt(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 It(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Re(r,i,e,5)}function St(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Ur(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await It(r,e,n),p=await t(i);return St(r,p,a,s)}function Dr(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 Ne=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Mr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Be=(r,t=24)=>{let e=Mr(r);return e?e.slice(0,t):"action"},$e=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)},kr=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()}},qr=(r,t,e)=>{let n=Be((e||t||"").trim()||"action"),i=`${r.type}|${kr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=$e(i);return`private_src_${n}_${a}`},Oe=r=>{let t=Ne(r),e=Be(t),n=$e(t.trim().toLowerCase());return`private_gen_${e}_${n}`},zr=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Oe(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},Gr=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function _r(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 Jr(r,t,e){return null}var Ve=(r,t)=>{let e=null;try{e=E(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]:[]},Qr=async(r,t,e,n)=>{try{let i=W(e,n),a=Ve(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 Qt=require("@x402/core/client"),Kt=require("@x402/core/http");async function Xt(r,t,e,n,i){let a=await Kr(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([l,o])=>{s.set(l,o)}),A.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return A.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var Kr=async(r,t)=>{let e=await Xr(r),i=new Kt.x402HTTPClient(new Qt.x402Client).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new Qt.x402Client,p=await a.wallet.registerX402Handlers(s),l=i.accepts.find(g=>g?.network&&p[g.network]);if(!l?.network)continue;p[l.network]();let o=new Kt.x402HTTPClient(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return A.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${l.network} scheme`),d}catch{continue}return null},Xr=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===y.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===y.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===y.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(y.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=a.startsWith(y.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===y.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?y.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):y.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===y.Option){let[a,s]=i.split(c.ArgParamsSeparator);return[y.Option+c.ArgParamsSeparator+a,s||null]}if(n===y.Vector){let a=i.indexOf(c.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(y.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(s+c.ArgParamsSeparator+d)[1]);return[y.Vector+c.ArgParamsSeparator+s,u]}else if(n.startsWith(y.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(y.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===y.String)return[n,i];if(n===y.Uint8||n===y.Uint16||n===y.Uint32)return[n,Number(i)];if(n===y.Uint64||n===y.Uint128||n===y.Uint256||n===y.Biguint)return[n,BigInt(i||0)];if(n===y.Bool)return[n,i==="true"];if(n===y.Address)return[n,i];if(n===y.Hex)return[n,i];if(n===y.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"?[y.Uint32,t]:typeof t=="bigint"?[y.Uint64,t]:typeof t=="boolean"?[y.Bool,t]:[typeof t,t]}};var Zr=r=>new w().nativeToString(y.String,r),Yr=r=>new w().nativeToString(y.Uint8,r),tn=r=>new w().nativeToString(y.Uint16,r),en=r=>new w().nativeToString(y.Uint32,r),rn=r=>new w().nativeToString(y.Uint64,r),nn=r=>new w().nativeToString(y.Biguint,r),an=r=>new w().nativeToString(y.Bool,r),sn=r=>new w().nativeToString(y.Address,r),Zt=r=>new w().nativeToString(y.Asset,r),on=r=>new w().nativeToString(y.Hex,r),pn=(r,t)=>{if(t===null)return y.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return y.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+a},ln=(...r)=>new w().nativeToString(y.Tuple,r),cn=r=>new w().nativeToString(y.Struct,r),un=r=>new w().nativeToString(y.Vector,r);var He=K(require("ajv"),1);var Yt=class{constructor(t){this.pendingBrand={protocol:it("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 He.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var Le=K(require("ajv"),1);var pt=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}=E(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,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"),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 Le.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 te=class{constructor(t){this.config=t;this.pendingWarp={protocol:it("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 Ft(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 pt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
+ `))}};var P=require("fs"),et=require("path");var ee="$bigint:",Pt=(r,t)=>typeof t=="bigint"?ee+t.toString():t,tt=(r,t)=>typeof t=="string"&&t.startsWith(ee)?BigInt(t.slice(ee.length)):t;var bt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,et.resolve)(n):(0,et.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,P.existsSync)(this.cacheDir)||(0,P.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,et.join)(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!(0,P.existsSync)(e))return null;let n=(0,P.readFileSync)(e,"utf-8"),i=JSON.parse(n,tt);return i.expiresAt!==null&&Date.now()>i.expiresAt?((0,P.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,P.writeFileSync)(a,JSON.stringify(i,Pt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);(0,P.existsSync)(e)&&(0,P.unlinkSync)(e)}catch{}}async keys(t){try{let e=(0,P.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,P.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,P.unlinkSync)((0,et.join)(this.cacheDir,e))})}catch{}}};var lt=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,tt);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,Pt))}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 L=class L{constructor(t,e){}async get(t){let e=L.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(L.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;L.cache.set(t,{value:e,expiresAt:i})}async delete(t){L.cache.delete(t)}async keys(t){let e=Array.from(L.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){L.cache.clear()}};L.cache=new Map;var ct=L;var Fe=require("fs"),re=require("path");var Tt=class{constructor(t,e){let n=e?.path?(0,re.resolve)(e.path):(0,re.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,Fe.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,tt)))}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 ne={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Et={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}`},ut=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new lt(t,e):e?.type==="memory"?new ct(t,e):e?.type==="static"?new Tt(t,e):e?.type==="filesystem"?new bt(t,e):typeof window<"u"&&window.localStorage?new lt(t,e):new ct(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 dt={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},ie={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},ae=(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)},se=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 It(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(St(n,d,o,u)).forEach(([g,h])=>s.set(g,h))}let p=ae(e.resolvedInputs,dt.Headers,i);if(p){let l=se(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===ie.Get){let s=ae(e.resolvedInputs,dt.Queries,i);if(s){let p=se(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===ie.Get)return;let a=ae(t.resolvedInputs,dt.Payload,n);if(a&&se(a)!==null)return a;let{[dt.Payload]:s,[dt.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},Ue=async(r,t,e,n,i,a,s,p)=>{let l=t.method||ie.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 $=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=S(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,h=e.queries?.[o]??null??d;h!=null&&a(s,h)}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 j(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=W(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"],Q=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new ut(t.env,t.cache)}getSerializer(){return this.serializer}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(Et.WarpExecutable(t,e||"",n))||[];return V(i)}async createExecutable(t,e,n,i={}){let a=B(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=W(s.name,this.adapters),l=new $(this.config,p,this.adapters),o=await l.apply(t,i),u=B(o,e),{action:d,index:g}=E(o),h=this.getStringTypedInputs(d,n),m=await this.getResolvedInputs(s.name,d,h,l,i.queries),f=await this.getModifiedInputs(m),v=[],C=[];g===e-1?(v=m,C=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,l,i.queries),C=await this.getModifiedInputs(v));let T=C.find(b=>b.input.position==="receiver"||b.input.position==="destination")?.value,F=this.getDestinationFromAction(u),x=T?this.serializer.stringToNative(T)[1]:F;if(x&&(x=l.applyInputs(x,C,this.serializer,f)),!x&&!mn.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let U=this.getPreparedArgs(u,C);U=U.map(b=>l.applyInputs(b,C,this.serializer,f));let H=C.find(b=>b.input.position==="value")?.value||null,R="value"in u?u.value:null,N=H?.split(c.ArgParamsSeparator)[1]||R||"0",M=l.applyInputs(N,C,this.serializer,f),De=BigInt(M),je=C.filter(b=>b.input.position==="transfer"&&b.value).map(b=>b.value),Me=[...("transfers"in u?u.transfers:[])||[],...je||[]].map(b=>{let Rt=l.applyInputs(b,C,this.serializer,f),Ge=Rt.startsWith(`asset${c.ArgParamsSeparator}`)?Rt:`asset${c.ArgParamsSeparator}${Rt}`;return this.serializer.stringToNative(Ge)[1]}),ke=C.find(b=>b.input.position==="data")?.value,qe="data"in u?u.data||"":null,le=ke||qe||null,ze=le?l.applyInputs(le,C,this.serializer,f):null,ce={adapter:p,warp:o,chain:s,action:e,destination:x,args:U,value:De,transfers:Me,data:ze,resolvedInputs:C};return await this.cache.set(Et.WarpExecutable(this.config.env,o.meta?.hash||"",e),ce.resolvedInputs,ne.OneWeek),ce}async getChainInfoForWarp(t,e){if(t.chain)return W(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=S(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,h=a?.[g],m=this.url.searchParams.get(g),f=h||m;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let g=o(u,d),h=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:g||(h!==void 0?this.serializer.nativeToString(u.type,h):null)}})}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=at(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=at(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=ot(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]=xt(e),a=W(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=at(p,o.decimals);return Zt({...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 W(s,this.adapters).chainInfo}};var gt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new Q(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:g}=E(t);for(let h=1;h<=t.actions.length;h++){let m=B(t,h);if(!Ct(m,t))continue;let{tx:f,chain:v,immediateExecution:C,executable:T}=await this.executeAction(t,h,e,u);f&&i.push(f),v&&(a=v),C&&s.push(C),T&&h===g+1&&T.resolvedInputs&&(p=V(T.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 h=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(h))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=B(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):$t.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=W(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=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!Ct(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let d=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),g={status:"error",warp:t,action:o,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:g})),g}let u=await i.output.getActionExecution(t,o,l.tx);return u.next=G(this.config,this.adapters,t,o,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(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=S(this.config,t.chain.name),i=B(t.warp,t.action),a=this.factory.getSerializer(),s=J(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 Y(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async executeCompute(t){let e=S(this.config,t.chain.name),n=this.factory.getSerializer(),i=J(t.resolvedInputs,n),{values:a,output:s}=await Y(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,W(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await Ue(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 h=await fetch(l,{method:o,headers:u,body:d});A.debug("Collect response status",{status:h.status}),h.status===402&&(h=await Xt(h,l,o,d,this.adapters));let m=await h.json();A.debug("Collect response content",{content:m});let{values:f,output:v}=await Y(t.warp,m,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),h.ok?"success":"error",f,v,m)}catch(g){A.error("WarpActionExecutor: Error executing collect",g);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:g},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=S(this.config,t.chain.name),i=B(t.warp,t.action);if(!i.destination){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("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let m=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:m}}let p=this.factory.getSerializer(),l=new $(this.config,W(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(([h,m])=>{let f=l.applyInputs(m,t.resolvedInputs,this.factory.getSerializer());g[h]=f}),A.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:g});try{let h=new s(new URL(u),{requestInit:{headers:g}}),m=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await m.connect(h);let f={};t.resolvedInputs.forEach(({input:x,value:U})=>{if(U&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let H=x.position.replace("payload:",""),[R,N]=p.stringToNative(U);if(R==="string")f[H]=String(N);else if(R==="bool")f[H]=!!N;else if(R==="uint8"||R==="uint16"||R==="uint32"||R==="uint64"||R==="uint128"||R==="uint256"||R==="biguint"){let M=Number(N);f[H]=(Number.isInteger(M),M)}else f[H]=N}}),e&&Object.assign(f,e);let v=await m.callTool({name:d,arguments:f});await m.close();let C;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{C=JSON.parse(x.text)}catch{C=x.text}else x.type,C=x}else C=v;let{values:T,output:F}=await Y(t.warp,C,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",T,F,v)}catch(h){A.error("WarpExecutor: Error executing MCP",h);let m=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:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}buildCollectResult(t,e,n,i,a,s){let p=G(this.config,this.adapters,t.warp,t.action,a),l=V(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:wt(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=W(s.name,this.adapters),l=new $(this.config,p,this.adapters),o=await l.apply(t,a),u=B(o,n),{action:d}=E(o),g=this.factory.getStringTypedInputs(d,i),h=await this.factory.getResolvedInputs(s.name,d,g,l,a.queries),m=await this.factory.getModifiedInputs(h),f=m;if(e.inputs&&e.inputs.length>0){let N=this.factory.getStringTypedInputs(e,i),M=await this.factory.getResolvedInputs(s.name,e,N,l,a.queries);f=await this.factory.getModifiedInputs(M)}let v=Jt(u.prompt,this.config.platform),C=l.applyInputs(v,f,this.factory.getSerializer(),m),T=V(f),F=S(this.config,s.name),x=this.factory.getSerializer(),{values:U,output:H}=await _t(o,C,n,f,x,this.config),R=f.find(N=>N.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:F,txHash:null,tx:null,next:G(this.config,this.adapters,o,n,H),values:U,output:H,messages:wt(o,H,this.config),destination:R,resolvedInputs:T}}catch(s){return A.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,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=W(p.name,this.adapters),o=new $(this.config,l,this.adapters),{action:u}=E(t),d=this.factory.getStringTypedInputs(u,n),g=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),h=await this.factory.getModifiedInputs(g),m;if(a)m=a;else{let T=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);m=await this.factory.getModifiedInputs(T)}let f=o.buildInputBag(m,this.factory.getSerializer(),h),v={...i.envs??{},...f},C=Ut(e.when,v);return Dt(C)}};var ft=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 ht=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!Z(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)?Z(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):Mt(i.identifier);if(this.resolver){let m=null;if(a==="hash")m=await this.resolver.getByHash(s,e);else if(a==="alias"){let f=`${i.chain}:${s}`;m=await this.resolver.getByAlias(f,e)||await this.resolver.getByAlias(s,e)}m&&(p=m.warp,l=m.registryInfo,o=m.brand)}else{let m=W(i.chain,this.adapters);if(a==="hash"){p=await m.builder().createFromTransactionHash(s,e);let f=await m.registry.getInfoByHash(s,e);l=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await m.registry.getInfoByAlias(s,e);l=f.registryInfo,o=f.brand,f.registryInfo&&(p=await m.builder().createFromTransactionHash(f.registryInfo.hash,e))}}if(p&&p.meta&&(yn(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(m=>m.chainInfo.name.toLowerCase()===d.toLowerCase()),h=g?await new $(this.config,g,this.adapters).apply(p):p;return{match:!0,url:t,warp:h,chain:d,registryInfo:l,brand:o}}catch(a){return A.error("Error detecting warp link",a),n}}},yn=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?At(null,"alias",e.alias):At(t,"hash",e?.hash??n))};var oe=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 gt(this.config,this.chains,t)}async detectWarp(t,e){return new ht(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 m=await fetch(t);if(!m.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await m.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 m=>{await l.evaluateOutput(p,m)},resolvedInputs:g}}async createInscriptionTransaction(t,e){return await W(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return W(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 W(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(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 W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??E(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=G(this.config,this.chains,e,a,p.output),p}async getRegistry(t){let e=W(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return W(t,this.chains).dataLoader}getWallet(t){return W(t,this.chains).wallet}get factory(){return new Q(this.config,this.chains)}get index(){return new ft(this.config)}get linkBuilder(){return new z(this.config,this.chains)}createBuilder(t){return W(t,this.chains).builder()}createAbiBuilder(t){return W(t,this.chains).abiBuilder()}createBrandBuilder(t){return W(t,this.chains).brandBuilder()}createSerializer(t){return W(t,this.chains).serializer}resolveText(t){return st(t,this.config)}};var pe=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,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,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getRequiredAssetIds,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpIdentifierWithQuery,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isPlatformValue,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,removeWarpWalletFromConfig,replacePlaceholders,replacePlaceholdersInWhenExpression,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 yr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Ie=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>Ie(r.user?.wallets?.[t]||null),Se=r=>r?typeof r=="string"?r:r.privateKey||null:null,Pe=r=>r?typeof r=="string"?r:r.mnemonic||null:null,be=r=>r?typeof r=="string"?r:r.externalId||null:null,Wr=(r,t)=>Se(r.user?.wallets?.[t]||null)?.trim()||null,vr=(r,t)=>Pe(r.user?.wallets?.[t]||null)?.trim()||null,Te=(r,t)=>be(r.user?.wallets?.[t]||null)?.trim()||null,Ar=(r,t)=>{let e=Te(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Cr=r=>typeof r=="string",xr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},wr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},Ee=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Re=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},Ir=(r,t=24)=>{let e=Ee(r);return Re(e,t),e};var Ne=(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))(Ne||{}),Lt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Lt||{}),Ft=Object.values(Lt),br=["ethereum","base","arbitrum","polygon","somnia","tempo"],Tr=["coinbase","privy","gaupa"],c={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>S(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"}},y={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"},Ut=typeof window<"u"?window:{open:()=>{}};var q={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${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 Br=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var it="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",I={baseUrl:it,chainLogo:r=>`${it}/chains/logos/${r}`,tokenLogo:r=>`${it}/tokens/logos/${r}`,walletLogo:r=>`${it}/wallets/logos/${r}`},Be={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"},Or=r=>Be[r]??r.charAt(0).toUpperCase()+r.slice(1),$e={ethereum:{light:I.chainLogo("ethereum-white.svg"),dark:I.chainLogo("ethereum-black.svg")},base:{light:I.chainLogo("base-white.svg"),dark:I.chainLogo("base-black.svg")},arbitrum:I.chainLogo("arbitrum.svg"),polygon:I.chainLogo("polygon.svg"),somnia:I.chainLogo("somnia.png"),tempo:{light:I.chainLogo("tempo-white.svg"),dark:I.chainLogo("tempo-black.svg")},multiversx:I.chainLogo("multiversx.svg"),claws:I.chainLogo("claws.png"),sui:I.chainLogo("sui.svg"),solana:I.chainLogo("solana.svg"),near:{light:I.chainLogo("near-white.svg"),dark:I.chainLogo("near-black.svg")},fastset:{light:I.chainLogo("fastset-white.svg"),dark:I.chainLogo("fastset-black.svg")}},Vr=(r,t="dark")=>{let e=$e[r];return typeof e=="string"?e:t==="dark"?e.dark:e.light};var Fr=(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 Wt=(r,t)=>r[t]??r.default??Object.values(r)[0],Dr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:Wt(r.logo,e)},jr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Wt(r.logoUrl,e)},kr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Wt(r.logoUrl,e)};var vt=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"}`)}}},j=null;function Dt(){if(j)return j;if(typeof window<"u"&&window.crypto)return j=new vt,j;if(typeof process<"u"&&process.versions?.node)return j=new At,j;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function qr(r){j=r}async function jt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Dt()).getRandomBytes(r)}function Oe(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 zr(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 kt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await jt(r/2,t);return Oe(e)}async function Gr(){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 jt(16),r.randomBytes=!0}catch{}return r}function _r(){return Dt()}var Kr=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 W=(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}`)},N=(r,t)=>r?.actions[t-1],E=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}},Ct=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=E(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)},Mt=(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},k=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),qt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),en=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}},zt=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 nn={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""},an=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,sn=r=>r;var K=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,cn=(r,t)=>!r||!t?!1:K(r)===K(t),xt=(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=Gt(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=Ve(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)},Ve=(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},Gt=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=Gt(a);return[i,...s]},_t=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},Jt=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},Qt=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},un=(r,t)=>{let e=O(r,t);return(e?e.identifierBase:K(r)).trim()},dn=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 wt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},hn=r=>{let t=new Set(Object.values(y));if(!r.includes(c.ArgParamsSeparator))return!1;let e=wt(r)[0];return t.has(e)};var It=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=ot(a,e);return[i,k(s,t)]});return Object.fromEntries(n)};import Le from"qr-code-styling";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=W(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=W(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=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Le({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 Fe="https://",G=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(Fe))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=k(s,{...e.vars,...i});return[{identifier:f,url:St(t,f,r)}]}let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let f=k(p,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:St(t,v,r)}]}let o=l[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let g=Array.isArray(i[d])?i[d]:[i[d]];if(g.length===0)return[];let h=l.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return g.map(f=>{let v=p;for(let{regex:b,field:L}of h){let x=L?Ue(f,L):f;if(x==null)return null;v=v.replace(b,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${s}?${v}`:s;return{identifier:A,url:St(t,A,r)}}).filter(f=>f!==null)},St=(r,t,e)=>{let[n,i]=t.split("?"),a=O(n,e.defaultChain)||{chain:c.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=W(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(/\/\?/,"?")},Ue=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var M=class M{static debug(...t){M.isTestEnv||console.debug(...t)}static info(...t){M.isTestEnv||console.info(...t)}static warn(...t){M.isTestEnv||console.warn(...t)}static error(...t){M.isTestEnv||console.error(...t)}};M.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=M;function De(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 Kt(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]=Kt(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 _(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=De(n.input.position,i,a);e=Kt(e,s)}else e[i]=a}),e}function pt(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 Xt=(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=ze(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((h,m)=>h&&h[m]!==void 0?h[m]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:u}=Xt(r,e,p);return{values:{string:l,native:o,mapped:_(n,i)},output:await Zt(r,u,t,e,n,i,a)}},Zt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=ke(p,r,n,i,a),p=await Me(r,p,e,i,a,s.transform?.runner||null),p},ke=(r,t,e,n,i)=>{let a={...r},s=N(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},Me=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:qe(e),inputs:pt(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,l),l[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},qe=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},Yt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=Xt(r,e,s),u=await Zt(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:l,mapped:_(n,i)},output:u}},ze=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var Ge=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Ft.some(t=>t in r),te=(r,t)=>{if(!Ge(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 qn=(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 kt(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 Pt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return _e(r,i,e,5)}function bt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Jn(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Pt(r,e,n),p=await t(i);return bt(r,p,a,s)}function Qn(r){let t=new Date(r).getTime();return Date.now()<t}function Kn(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 Je=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Qe=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),ee=(r,t=24)=>{let e=Qe(r);return e?e.slice(0,t):"action"},re=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)},Ke=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()}},Zn=(r,t,e)=>{let n=ee((e||t||"").trim()||"action"),i=`${r.type}|${Ke(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=re(i);return`private_src_${n}_${a}`},Xe=r=>{let t=Je(r),e=ee(t),n=re(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Yn=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Xe(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},ti=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function ri(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 ii(r,t,e){return null}var Ze=(r,t)=>{let e=null;try{e=E(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]:[]},oi=async(r,t,e,n)=>{try{let i=W(e,n),a=Ze(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{x402Client as ne}from"@x402/core/client";import{x402HTTPClient as ie}from"@x402/core/http";async function ae(r,t,e,n,i){let a=await Ye(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([l,o])=>{s.set(l,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var Ye=async(r,t)=>{let e=await tr(r),i=new ie(new ne).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new ne,p=await a.wallet.registerX402Handlers(s),l=i.accepts.find(g=>g?.network&&p[g.network]);if(!l?.network)continue;p[l.network]();let o=new ie(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${l.network} scheme`),d}catch{continue}return null},tr=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===y.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===y.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===y.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(y.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=a.startsWith(y.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===y.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?y.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):y.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===y.Option){let[a,s]=i.split(c.ArgParamsSeparator);return[y.Option+c.ArgParamsSeparator+a,s||null]}if(n===y.Vector){let a=i.indexOf(c.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(y.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(s+c.ArgParamsSeparator+d)[1]);return[y.Vector+c.ArgParamsSeparator+s,u]}else if(n.startsWith(y.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(y.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===y.String)return[n,i];if(n===y.Uint8||n===y.Uint16||n===y.Uint32)return[n,Number(i)];if(n===y.Uint64||n===y.Uint128||n===y.Uint256||n===y.Biguint)return[n,BigInt(i||0)];if(n===y.Bool)return[n,i==="true"];if(n===y.Address)return[n,i];if(n===y.Hex)return[n,i];if(n===y.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"?[y.Uint32,t]:typeof t=="bigint"?[y.Uint64,t]:typeof t=="boolean"?[y.Bool,t]:[typeof t,t]}};var yi=r=>new w().nativeToString(y.String,r),Wi=r=>new w().nativeToString(y.Uint8,r),vi=r=>new w().nativeToString(y.Uint16,r),Ai=r=>new w().nativeToString(y.Uint32,r),Ci=r=>new w().nativeToString(y.Uint64,r),xi=r=>new w().nativeToString(y.Biguint,r),wi=r=>new w().nativeToString(y.Bool,r),Ii=r=>new w().nativeToString(y.Address,r),se=r=>new w().nativeToString(y.Asset,r),Si=r=>new w().nativeToString(y.Hex,r),Pi=(r,t)=>{if(t===null)return y.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return y.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+a},bi=(...r)=>new w().nativeToString(y.Tuple,r),Ti=r=>new w().nativeToString(y.Struct,r),Ei=r=>new w().nativeToString(y.Vector,r);import er from"ajv";var oe=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||D.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new er,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import rr from"ajv";var lt=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}=E(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,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"),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 rr({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 pe=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 Mt(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 lt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
- `))}};import{existsSync as Et,mkdirSync as nr,readdirSync as le,readFileSync as ir,unlinkSync as Rt,writeFileSync as ar}from"fs";import{join as ce,resolve as ue}from"path";var Tt="$bigint:",ct=(r,t)=>typeof t=="bigint"?Tt+t.toString():t,J=(r,t)=>typeof t=="string"&&t.startsWith(Tt)?BigInt(t.slice(Tt.length)):t;var ut=class{constructor(t,e){let n=e?.path;this.cacheDir=n?ue(n):ue(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){Et(this.cacheDir)||nr(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return ce(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!Et(e))return null;let n=ir(e,"utf-8"),i=JSON.parse(n,J);return i.expiresAt!==null&&Date.now()>i.expiresAt?(Rt(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);ar(a,JSON.stringify(i,ct),"utf-8")}async delete(t){try{let e=this.getFilePath(t);Et(e)&&Rt(e)}catch{}}async keys(t){try{let e=le(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{le(this.cacheDir).forEach(e=>{e.endsWith(".json")&&Rt(ce(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,J);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,ct))}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 sr}from"fs";import{resolve as de}from"path";var dt=class{constructor(t,e){let n=e?.path?de(e.path):de(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=sr(t,"utf-8");return new Map(Object.entries(JSON.parse(e,J)))}catch(e){return C.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 ge={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Nt={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}`},gt=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 dt(t,e):e?.type==="filesystem"?new ut(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"},Bt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},$t=(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}},or=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 Pt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(bt(n,d,o,u)).forEach(([g,h])=>s.set(g,h))}let p=$t(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},pr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Bt.Get){let s=$t(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},lr=(r,t,e,n,i)=>{if(r===Bt.Get)return;let a=$t(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})},fe=async(r,t,e,n,i,a,s,p)=>{let l=t.method||Bt.Get,o=await or(r,t,e,n,a,p),u=pr(r,t,e,l,a),d=lr(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(`\\{\\{${cr(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=S(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,h=e.queries?.[o]??null??d;h!=null&&a(s,h)}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 k(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=W(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}},cr=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var ur=["collect","compute","mcp","state","mount","unmount"],Q=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new gt(t.env,t.cache)}getSerializer(){return this.serializer}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(Nt.WarpExecutable(t,e||"",n))||[];return V(i)}async createExecutable(t,e,n,i={}){let a=N(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=W(s.name,this.adapters),l=new B(this.config,p,this.adapters),o=await l.apply(t,i),u=N(o,e),{action:d,index:g}=E(o),h=this.getStringTypedInputs(d,n),m=await this.getResolvedInputs(s.name,d,h,l,i.queries),f=await this.getModifiedInputs(m),v=[],A=[];g===e-1?(v=m,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,l,i.queries),A=await this.getModifiedInputs(v));let b=A.find(P=>P.input.position==="receiver"||P.input.position==="destination")?.value,L=this.getDestinationFromAction(u),x=b?this.serializer.stringToNative(b)[1]:L;if(x&&(x=l.applyInputs(x,A,this.serializer,f)),!x&&!ur.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let F=this.getPreparedArgs(u,A);F=F.map(P=>l.applyInputs(P,A,this.serializer,f));let $=A.find(P=>P.input.position==="value")?.value||null,T="value"in u?u.value:null,R=$?.split(c.ArgParamsSeparator)[1]||T||"0",U=l.applyInputs(R,A,this.serializer,f),ye=BigInt(U),We=A.filter(P=>P.input.position==="transfer"&&P.value).map(P=>P.value),ve=[...("transfers"in u?u.transfers:[])||[],...We||[]].map(P=>{let yt=l.applyInputs(P,A,this.serializer,f),we=yt.startsWith(`asset${c.ArgParamsSeparator}`)?yt:`asset${c.ArgParamsSeparator}${yt}`;return this.serializer.stringToNative(we)[1]}),Ae=A.find(P=>P.input.position==="data")?.value,Ce="data"in u?u.data||"":null,Vt=Ae||Ce||null,xe=Vt?l.applyInputs(Vt,A,this.serializer,f):null,Ht={adapter:p,warp:o,chain:s,action:e,destination:x,args:F,value:ye,transfers:ve,data:xe,resolvedInputs:A};return await this.cache.set(Nt.WarpExecutable(this.config.env,o.meta?.hash||"",e),Ht.resolvedInputs,ge.OneWeek),Ht}async getChainInfoForWarp(t,e){if(t.chain)return W(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=S(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,h=a?.[g],m=this.url.searchParams.get(g),f=h||m;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let g=o(u,d),h=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:g||(h!==void 0?this.serializer.nativeToString(u.type,h):null)}})}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=pt(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]=wt(e),a=W(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 se({...o,amount:u})}else return e}catch(n){throw C.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input: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 W(s,this.adapters).chainInfo}};var ft=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new Q(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:g}=E(t);for(let h=1;h<=t.actions.length;h++){let m=N(t,h);if(!Ct(m,t))continue;let{tx:f,chain:v,immediateExecution:A,executable:b}=await this.executeAction(t,h,e,u);f&&i.push(f),v&&(a=v),A&&s.push(A),b&&h===g+1&&b.resolvedInputs&&(p=V(b.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 h=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(h))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=N(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):Ut.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=W(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=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!Ct(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let d=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),g={status:"error",warp:t,action:o,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:g})),g}let u=await i.output.getActionExecution(t,o,l.tx);return u.next=G(this.config,this.adapters,t,o,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(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=S(this.config,t.chain.name),i=N(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=S(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,W(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await fe(s,e,t,n,i,p,a,async g=>await this.callHandler(()=>this.handlers?.onSignRequest?.(g)));C.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:u,body:d});try{let h=await fetch(l,{method:o,headers:u,body:d});C.debug("Collect response status",{status:h.status}),h.status===402&&(h=await ae(h,l,o,d,this.adapters));let m=await h.json();C.debug("Collect response content",{content:m});let{values:f,output:v}=await Z(t.warp,m,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),h.ok?"success":"error",f,v,m)}catch(g){C.error("WarpActionExecutor: Error executing collect",g);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:g},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=S(this.config,t.chain.name),i=N(t.warp,t.action);if(!i.destination){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("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let m=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:m}}let p=this.factory.getSerializer(),l=new B(this.config,W(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(([h,m])=>{let f=l.applyInputs(m,t.resolvedInputs,this.factory.getSerializer());g[h]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:g});try{let h=new s(new URL(u),{requestInit:{headers:g}}),m=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await m.connect(h);let f={};t.resolvedInputs.forEach(({input:x,value:F})=>{if(F&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let $=x.position.replace("payload:",""),[T,R]=p.stringToNative(F);if(T==="string")f[$]=String(R);else if(T==="bool")f[$]=!!R;else if(T==="uint8"||T==="uint16"||T==="uint32"||T==="uint64"||T==="uint128"||T==="uint256"||T==="biguint"){let U=Number(R);f[$]=(Number.isInteger(U),U)}else f[$]=R}}),e&&Object.assign(f,e);let v=await m.callTool({name:d,arguments:f});await m.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:b,output:L}=await Z(t.warp,A,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",b,L,v)}catch(h){C.error("WarpExecutor: Error executing MCP",h);let m=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:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}buildCollectResult(t,e,n,i,a,s){let p=G(this.config,this.adapters,t.warp,t.action,a),l=V(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:It(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=W(s.name,this.adapters),l=new B(this.config,p,this.adapters),o=await l.apply(t,a),u=N(o,n),{action:d}=E(o),g=this.factory.getStringTypedInputs(d,i),h=await this.factory.getResolvedInputs(s.name,d,g,l,a.queries),m=await this.factory.getModifiedInputs(h),f=m;if(e.inputs&&e.inputs.length>0){let R=this.factory.getStringTypedInputs(e,i),U=await this.factory.getResolvedInputs(s.name,e,R,l,a.queries);f=await this.factory.getModifiedInputs(U)}let v=te(u.prompt,this.config.platform),A=l.applyInputs(v,f,this.factory.getSerializer(),m),b=V(f),L=S(this.config,s.name),x=this.factory.getSerializer(),{values:F,output:$}=await Yt(o,A,n,f,x,this.config),T=f.find(R=>R.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:L,txHash:null,tx:null,next:G(this.config,this.adapters,o,n,$),values:F,output:$,messages:It(o,$,this.config),destination:T,resolvedInputs:b}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,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=W(p.name,this.adapters),o=new B(this.config,l,this.adapters),{action:u}=E(t),d=this.factory.getStringTypedInputs(u,n),g=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),h=await this.factory.getModifiedInputs(g),m;if(a)m=a;else{let b=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);m=await this.factory.getModifiedInputs(b)}let f=o.buildInputBag(m,this.factory.getSerializer(),h),v={...i.envs??{},...f},A=qt(e.when,v);return zt(A)}};var ht=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw C.error("WarpIndex: Error searching for warps: ",i),i}}};var mt=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)?_t(t):Jt(i.identifier);if(this.resolver){let m=null;if(a==="hash")m=await this.resolver.getByHash(s,e);else if(a==="alias"){let f=`${i.chain}:${s}`;m=await this.resolver.getByAlias(f,e)||await this.resolver.getByAlias(s,e)}m&&(p=m.warp,l=m.registryInfo,o=m.brand)}else{let m=W(i.chain,this.adapters);if(a==="hash"){p=await m.builder().createFromTransactionHash(s,e);let f=await m.registry.getInfoByHash(s,e);l=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await m.registry.getInfoByAlias(s,e);l=f.registryInfo,o=f.brand,f.registryInfo&&(p=await m.builder().createFromTransactionHash(f.registryInfo.hash,e))}}if(p&&p.meta&&(dr(p,i.chain,l,i.identifier),p.meta.query=u?Qt(u):null),!p)return n;let d=p.chain||i.chain,g=this.adapters.find(m=>m.chainInfo.name.toLowerCase()===d.toLowerCase()),h=g?await new B(this.config,g,this.adapters).apply(p):p;return{match:!0,url:t,warp:h,chain:d,registryInfo:l,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},dr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?xt(null,"alias",e.alias):xt(t,"hash",e?.hash??n))};var he=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 ft(this.config,this.chains,t)}async detectWarp(t,e){return new mt(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 m=await fetch(t);if(!m.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await m.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 m=>{await l.evaluateOutput(p,m)},resolvedInputs:g}}async createInscriptionTransaction(t,e){return await W(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return W(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 W(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(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 W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??E(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=G(this.config,this.chains,e,a,p.output),p}async getRegistry(t){let e=W(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return W(t,this.chains).dataLoader}getWallet(t){return W(t,this.chains).wallet}get factory(){return new Q(this.config,this.chains)}get index(){return new ht(this.config)}get linkBuilder(){return new z(this.config,this.chains)}createBuilder(t){return W(t,this.chains).builder()}createAbiBuilder(t){return W(t,this.chains).abiBuilder()}createBrandBuilder(t){return W(t,this.chains).brandBuilder()}createSerializer(t){return W(t,this.chains).serializer}resolveText(t){return ot(t,this.config)}};var me=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{vt as BrowserCryptoProvider,Tr as CLOUD_WALLET_PROVIDERS,ge as CacheTtl,br as EvmWalletChainNames,At as NodeCryptoProvider,nn as WARP_LANGUAGES,I as WarpAssets,oe as WarpBrandBuilder,pe as WarpBuilder,gt as WarpCache,Nt as WarpCacheKey,Be as WarpChainDisplayNames,$e as WarpChainLogos,Ne as WarpChainName,rt as WarpChainResolver,he as WarpClient,nt as WarpCompositeResolver,D as WarpConfig,c as WarpConstants,ft as WarpExecutor,Q as WarpFactory,ht as WarpIndex,y as WarpInputTypes,B as WarpInterpolator,z as WarpLinkBuilder,mt as WarpLinkDetecter,C as WarpLogger,Lt as WarpPlatformName,Ft as WarpPlatforms,q as WarpProtocolVersions,w as WarpSerializer,me as WarpTypeRegistry,lt as WarpValidator,Ii as address,It as applyOutputToMessages,se as asset,xi as biguint,wi as bool,Xe as buildGeneratedFallbackWarpIdentifier,Zn as buildGeneratedSourceWarpIdentifier,pt as buildInputsContext,_ as buildMappedOutput,De as buildNestedPayload,zr as bytesToBase64,Oe as bytesToHex,oi as checkWarpAssetBalance,K as cleanWarpIdentifier,bt as createAuthHeaders,Pt as createAuthMessage,_r as createCryptoProvider,ii as createDefaultWalletProvider,Jn as createHttpAuthHeaders,_e as createSignableMessage,sn as createWarpI18nText,xt as createWarpIdentifier,en as doesWarpRequireWallet,Zt as evaluateOutputCommon,zt as evaluateWhenCondition,Z as extractCollectOutput,X as extractIdentifierInfoFromUrl,Yt as extractPromptOutput,Jt as extractQueryStringFromIdentifier,_t as extractQueryStringFromUrl,V as extractResolvedInputValues,Kr as extractWarpSecrets,W as findWarpAdapterForChain,Or as getChainDisplayName,Vr as getChainLogo,Dt as getCryptoProvider,Fr as getEventNameFromWarp,Je as getGeneratedSourceWarpName,at as getLatestProtocolIdentifier,G as getNextInfo,qn as getProviderConfig,jt as getRandomBytes,kt as getRandomHex,Ze as getRequiredAssetIds,yr as getWalletFromConfigOrFail,N as getWarpActionByIndex,Dr as getWarpBrandLogoUrl,jr as getWarpChainAssetLogoUrl,kr as getWarpChainInfoLogoUrl,dn as getWarpIdentifierWithQuery,O as getWarpInfoFromIdentifier,E as getWarpPrimaryAction,Ie as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,be as getWarpWalletExternalId,Te as getWarpWalletExternalIdFromConfig,Ar as getWarpWalletExternalIdFromConfigOrFail,Pe as getWarpWalletMnemonic,vr as getWarpWalletMnemonicFromConfig,Se as getWarpWalletPrivateKey,Wr as getWarpWalletPrivateKeyFromConfig,ae as handleX402Payment,hn as hasInputPrefix,Si as hex,ri as initializeWalletCache,cn as isEqualWarpIdentifier,ti as isGeneratedSourcePrivateIdentifier,Ge as isPlatformValue,Ct as isWarpActionAutoExecute,an as isWarpI18nText,Cr as isWarpWalletReadOnly,Kt as mergeNestedPayload,Ir as normalizeAndValidateMnemonic,Ee as normalizeMnemonic,Pi as option,ze as parseOutputOutIndex,Kn as parseSignedMessage,Qt as parseWarpQueryStringToObject,un as removeWarpChainPrefix,wr as removeWarpWalletFromConfig,k as replacePlaceholders,qt as replacePlaceholdersInWhenExpression,te as resolvePlatformValue,ot as resolveWarpText,Ut as safeWindow,qr as setCryptoProvider,xr as setWarpWalletInConfig,st as shiftBigintBy,wt as splitInput,Yn as stampGeneratedWarpMeta,yi as string,Ti as struct,Gr as testCryptoAvailability,je as toInputPayloadValue,Mt as toPreviewText,bi as tuple,vi as uint16,Ai as uint32,Ci as uint64,Wi as uint8,Re as validateMnemonicLength,Qn as validateSignedMessage,Ei as vector,Br 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 yr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Ie=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>Ie(r.user?.wallets?.[t]||null),Se=r=>r?typeof r=="string"?r:r.privateKey||null:null,Pe=r=>r?typeof r=="string"?r:r.mnemonic||null:null,be=r=>r?typeof r=="string"?r:r.externalId||null:null,Wr=(r,t)=>Se(r.user?.wallets?.[t]||null)?.trim()||null,vr=(r,t)=>Pe(r.user?.wallets?.[t]||null)?.trim()||null,Te=(r,t)=>be(r.user?.wallets?.[t]||null)?.trim()||null,Cr=(r,t)=>{let e=Te(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Ar=r=>typeof r=="string",xr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},wr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},Ee=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Re=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},Ir=(r,t=24)=>{let e=Ee(r);return Re(e,t),e};var Ne=(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))(Ne||{}),Lt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Lt||{}),Ft=Object.values(Lt),br=["ethereum","base","arbitrum","polygon","somnia","tempo"],Tr=["multiversx","claws"],Er=["coinbase","privy","gaupa"],c={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>S(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"}},y={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"},Ut=typeof window<"u"?window:{open:()=>{}};var q={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${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 $r=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var it="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",I={baseUrl:it,chainLogo:r=>`${it}/chains/logos/${r}`,tokenLogo:r=>`${it}/tokens/logos/${r}`,walletLogo:r=>`${it}/wallets/logos/${r}`},Be={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"},Vr=r=>Be[r]??r.charAt(0).toUpperCase()+r.slice(1),$e={ethereum:{light:I.chainLogo("ethereum-white.svg"),dark:I.chainLogo("ethereum-black.svg")},base:{light:I.chainLogo("base-white.svg"),dark:I.chainLogo("base-black.svg")},arbitrum:I.chainLogo("arbitrum.svg"),polygon:I.chainLogo("polygon.svg"),somnia:I.chainLogo("somnia.png"),tempo:{light:I.chainLogo("tempo-white.svg"),dark:I.chainLogo("tempo-black.svg")},multiversx:I.chainLogo("multiversx.svg"),claws:I.chainLogo("claws.png"),sui:I.chainLogo("sui.svg"),solana:I.chainLogo("solana.svg"),near:{light:I.chainLogo("near-white.svg"),dark:I.chainLogo("near-black.svg")},fastset:{light:I.chainLogo("fastset-white.svg"),dark:I.chainLogo("fastset-black.svg")}},Hr=(r,t="dark")=>{let e=$e[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var Ur=(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 Wt=(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:Wt(r.logo,e)},Mr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Wt(r.logoUrl,e)},kr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Wt(r.logoUrl,e)};var vt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},Ct=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},j=null;function Dt(){if(j)return j;if(typeof window<"u"&&window.crypto)return j=new vt,j;if(typeof process<"u"&&process.versions?.node)return j=new Ct,j;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function zr(r){j=r}async function jt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Dt()).getRandomBytes(r)}function Oe(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 Gr(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 Mt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await jt(r/2,t);return Oe(e)}async function _r(){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 jt(16),r.randomBytes=!0}catch{}return r}function Jr(){return Dt()}var Xr=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 W=(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}`)},N=(r,t)=>r?.actions[t-1],E=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}},At=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=E(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)},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},M=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),qt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),rn=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}},zt=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 an={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""},sn=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,on=r=>r;var K=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,un=(r,t)=>!r||!t?!1:K(r)===K(t),xt=(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=Gt(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=Ve(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)},Ve=(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},Gt=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=Gt(a);return[i,...s]},_t=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},Jt=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},Qt=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},dn=(r,t)=>{let e=O(r,t);return(e?e.identifierBase:K(r)).trim()},gn=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 wt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},mn=r=>{let t=new Set(Object.values(y));if(!r.includes(c.ArgParamsSeparator))return!1;let e=wt(r)[0];return t.has(e)};var It=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=ot(a,e);return[i,M(s,t)]});return Object.fromEntries(n)};import Le from"qr-code-styling";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=W(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=W(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=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Le({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 Fe="https://",G=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(Fe))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=M(s,{...e.vars,...i});return[{identifier:f,url:St(t,f,r)}]}let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let f=M(p,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:St(t,v,r)}]}let o=l[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let g=Array.isArray(i[d])?i[d]:[i[d]];if(g.length===0)return[];let h=l.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),C=v&&v[1]||"";return{placeholder:f,field:C?C.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return g.map(f=>{let v=p;for(let{regex:b,field:L}of h){let x=L?Ue(f,L):f;if(x==null)return null;v=v.replace(b,x)}if(v.includes("{{")||v.includes("}}"))return null;let C=v?`${s}?${v}`:s;return{identifier:C,url:St(t,C,r)}}).filter(f=>f!==null)},St=(r,t,e)=>{let[n,i]=t.split("?"),a=O(n,e.defaultChain)||{chain:c.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=W(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(/\/\?/,"?")},Ue=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var k=class k{static debug(...t){k.isTestEnv||console.debug(...t)}static info(...t){k.isTestEnv||console.info(...t)}static warn(...t){k.isTestEnv||console.warn(...t)}static error(...t){k.isTestEnv||console.error(...t)}};k.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var A=k;function De(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 Kt(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]=Kt(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 _(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=De(n.input.position,i,a);e=Kt(e,s)}else e[i]=a}),e}function pt(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 Xt=(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=ze(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((h,m)=>h&&h[m]!==void 0?h[m]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:u}=Xt(r,e,p);return{values:{string:l,native:o,mapped:_(n,i)},output:await Zt(r,u,t,e,n,i,a)}},Zt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Me(p,r,n,i,a),p=await ke(r,p,e,i,a,s.transform?.runner||null),p},Me=(r,t,e,n,i)=>{let a={...r},s=N(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},ke=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:qe(e),inputs:pt(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},qe=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},Yt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=Xt(r,e,s),u=await Zt(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:l,mapped:_(n,i)},output:u}},ze=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var Ge=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Ft.some(t=>t in r),te=(r,t)=>{if(!Ge(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 zn=(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 Mt(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 Pt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return _e(r,i,e,5)}function bt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Qn(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Pt(r,e,n),p=await t(i);return bt(r,p,a,s)}function Kn(r){let t=new Date(r).getTime();return Date.now()<t}function Xn(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 Je=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Qe=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),ee=(r,t=24)=>{let e=Qe(r);return e?e.slice(0,t):"action"},re=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)},Ke=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()}},Yn=(r,t,e)=>{let n=ee((e||t||"").trim()||"action"),i=`${r.type}|${Ke(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=re(i);return`private_src_${n}_${a}`},Xe=r=>{let t=Je(r),e=ee(t),n=re(t.trim().toLowerCase());return`private_gen_${e}_${n}`},ti=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Xe(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},ei=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function ni(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 ai(r,t,e){return null}var Ze=(r,t)=>{let e=null;try{e=E(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]:[]},pi=async(r,t,e,n)=>{try{let i=W(e,n),a=Ze(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{x402Client as ne}from"@x402/core/client";import{x402HTTPClient as ie}from"@x402/core/http";async function ae(r,t,e,n,i){let a=await Ye(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([l,o])=>{s.set(l,o)}),A.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return A.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var Ye=async(r,t)=>{let e=await tr(r),i=new ie(new ne).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new ne,p=await a.wallet.registerX402Handlers(s),l=i.accepts.find(g=>g?.network&&p[g.network]);if(!l?.network)continue;p[l.network]();let o=new ie(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return A.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${l.network} scheme`),d}catch{continue}return null},tr=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===y.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===y.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===y.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(y.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=a.startsWith(y.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===y.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?y.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):y.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===y.Option){let[a,s]=i.split(c.ArgParamsSeparator);return[y.Option+c.ArgParamsSeparator+a,s||null]}if(n===y.Vector){let a=i.indexOf(c.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(y.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(s+c.ArgParamsSeparator+d)[1]);return[y.Vector+c.ArgParamsSeparator+s,u]}else if(n.startsWith(y.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(y.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===y.String)return[n,i];if(n===y.Uint8||n===y.Uint16||n===y.Uint32)return[n,Number(i)];if(n===y.Uint64||n===y.Uint128||n===y.Uint256||n===y.Biguint)return[n,BigInt(i||0)];if(n===y.Bool)return[n,i==="true"];if(n===y.Address)return[n,i];if(n===y.Hex)return[n,i];if(n===y.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"?[y.Uint32,t]:typeof t=="bigint"?[y.Uint64,t]:typeof t=="boolean"?[y.Bool,t]:[typeof t,t]}};var Wi=r=>new w().nativeToString(y.String,r),vi=r=>new w().nativeToString(y.Uint8,r),Ci=r=>new w().nativeToString(y.Uint16,r),Ai=r=>new w().nativeToString(y.Uint32,r),xi=r=>new w().nativeToString(y.Uint64,r),wi=r=>new w().nativeToString(y.Biguint,r),Ii=r=>new w().nativeToString(y.Bool,r),Si=r=>new w().nativeToString(y.Address,r),se=r=>new w().nativeToString(y.Asset,r),Pi=r=>new w().nativeToString(y.Hex,r),bi=(r,t)=>{if(t===null)return y.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return y.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+a},Ti=(...r)=>new w().nativeToString(y.Tuple,r),Ei=r=>new w().nativeToString(y.Struct,r),Ri=r=>new w().nativeToString(y.Vector,r);import er from"ajv";var oe=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||D.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new er,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import rr from"ajv";var lt=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}=E(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,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"),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 rr({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 pe=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 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 lt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
+ `))}};import{existsSync as Et,mkdirSync as nr,readdirSync as le,readFileSync as ir,unlinkSync as Rt,writeFileSync as ar}from"fs";import{join as ce,resolve as ue}from"path";var Tt="$bigint:",ct=(r,t)=>typeof t=="bigint"?Tt+t.toString():t,J=(r,t)=>typeof t=="string"&&t.startsWith(Tt)?BigInt(t.slice(Tt.length)):t;var ut=class{constructor(t,e){let n=e?.path;this.cacheDir=n?ue(n):ue(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){Et(this.cacheDir)||nr(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return ce(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!Et(e))return null;let n=ir(e,"utf-8"),i=JSON.parse(n,J);return i.expiresAt!==null&&Date.now()>i.expiresAt?(Rt(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);ar(a,JSON.stringify(i,ct),"utf-8")}async delete(t){try{let e=this.getFilePath(t);Et(e)&&Rt(e)}catch{}}async keys(t){try{let e=le(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{le(this.cacheDir).forEach(e=>{e.endsWith(".json")&&Rt(ce(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,J);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,ct))}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 sr}from"fs";import{resolve as de}from"path";var dt=class{constructor(t,e){let n=e?.path?de(e.path):de(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=sr(t,"utf-8");return new Map(Object.entries(JSON.parse(e,J)))}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 ge={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Nt={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 Y(t,e):e?.type==="memory"?new tt(t,e):e?.type==="static"?new dt(t,e):e?.type==="filesystem"?new ut(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"},Bt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},$t=(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}},or=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 Pt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(bt(n,d,o,u)).forEach(([g,h])=>s.set(g,h))}let p=$t(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},pr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Bt.Get){let s=$t(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},lr=(r,t,e,n,i)=>{if(r===Bt.Get)return;let a=$t(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})},fe=async(r,t,e,n,i,a,s,p)=>{let l=t.method||Bt.Get,o=await or(r,t,e,n,a,p),u=pr(r,t,e,l,a),d=lr(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(`\\{\\{${cr(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=S(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,h=e.queries?.[o]??null??d;h!=null&&a(s,h)}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 M(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=W(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}},cr=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var ur=["collect","compute","mcp","state","mount","unmount"],Q=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new gt(t.env,t.cache)}getSerializer(){return this.serializer}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(Nt.WarpExecutable(t,e||"",n))||[];return V(i)}async createExecutable(t,e,n,i={}){let a=N(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=W(s.name,this.adapters),l=new B(this.config,p,this.adapters),o=await l.apply(t,i),u=N(o,e),{action:d,index:g}=E(o),h=this.getStringTypedInputs(d,n),m=await this.getResolvedInputs(s.name,d,h,l,i.queries),f=await this.getModifiedInputs(m),v=[],C=[];g===e-1?(v=m,C=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,l,i.queries),C=await this.getModifiedInputs(v));let b=C.find(P=>P.input.position==="receiver"||P.input.position==="destination")?.value,L=this.getDestinationFromAction(u),x=b?this.serializer.stringToNative(b)[1]:L;if(x&&(x=l.applyInputs(x,C,this.serializer,f)),!x&&!ur.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let F=this.getPreparedArgs(u,C);F=F.map(P=>l.applyInputs(P,C,this.serializer,f));let $=C.find(P=>P.input.position==="value")?.value||null,T="value"in u?u.value:null,R=$?.split(c.ArgParamsSeparator)[1]||T||"0",U=l.applyInputs(R,C,this.serializer,f),ye=BigInt(U),We=C.filter(P=>P.input.position==="transfer"&&P.value).map(P=>P.value),ve=[...("transfers"in u?u.transfers:[])||[],...We||[]].map(P=>{let yt=l.applyInputs(P,C,this.serializer,f),we=yt.startsWith(`asset${c.ArgParamsSeparator}`)?yt:`asset${c.ArgParamsSeparator}${yt}`;return this.serializer.stringToNative(we)[1]}),Ce=C.find(P=>P.input.position==="data")?.value,Ae="data"in u?u.data||"":null,Vt=Ce||Ae||null,xe=Vt?l.applyInputs(Vt,C,this.serializer,f):null,Ht={adapter:p,warp:o,chain:s,action:e,destination:x,args:F,value:ye,transfers:ve,data:xe,resolvedInputs:C};return await this.cache.set(Nt.WarpExecutable(this.config.env,o.meta?.hash||"",e),Ht.resolvedInputs,ge.OneWeek),Ht}async getChainInfoForWarp(t,e){if(t.chain)return W(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=S(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,h=a?.[g],m=this.url.searchParams.get(g),f=h||m;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let g=o(u,d),h=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:g||(h!==void 0?this.serializer.nativeToString(u.type,h):null)}})}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=pt(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]=wt(e),a=W(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 se({...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 W(s,this.adapters).chainInfo}};var ft=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new Q(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:g}=E(t);for(let h=1;h<=t.actions.length;h++){let m=N(t,h);if(!At(m,t))continue;let{tx:f,chain:v,immediateExecution:C,executable:b}=await this.executeAction(t,h,e,u);f&&i.push(f),v&&(a=v),C&&s.push(C),b&&h===g+1&&b.resolvedInputs&&(p=V(b.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 h=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(h))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=N(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):Ut.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=W(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=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!At(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let d=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),g={status:"error",warp:t,action:o,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:g})),g}let u=await i.output.getActionExecution(t,o,l.tx);return u.next=G(this.config,this.adapters,t,o,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(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=S(this.config,t.chain.name),i=N(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=S(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,W(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await fe(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 h=await fetch(l,{method:o,headers:u,body:d});A.debug("Collect response status",{status:h.status}),h.status===402&&(h=await ae(h,l,o,d,this.adapters));let m=await h.json();A.debug("Collect response content",{content:m});let{values:f,output:v}=await Z(t.warp,m,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),h.ok?"success":"error",f,v,m)}catch(g){A.error("WarpActionExecutor: Error executing collect",g);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:g},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=S(this.config,t.chain.name),i=N(t.warp,t.action);if(!i.destination){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("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let m=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:m}}let p=this.factory.getSerializer(),l=new B(this.config,W(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(([h,m])=>{let f=l.applyInputs(m,t.resolvedInputs,this.factory.getSerializer());g[h]=f}),A.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:g});try{let h=new s(new URL(u),{requestInit:{headers:g}}),m=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await m.connect(h);let f={};t.resolvedInputs.forEach(({input:x,value:F})=>{if(F&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let $=x.position.replace("payload:",""),[T,R]=p.stringToNative(F);if(T==="string")f[$]=String(R);else if(T==="bool")f[$]=!!R;else if(T==="uint8"||T==="uint16"||T==="uint32"||T==="uint64"||T==="uint128"||T==="uint256"||T==="biguint"){let U=Number(R);f[$]=(Number.isInteger(U),U)}else f[$]=R}}),e&&Object.assign(f,e);let v=await m.callTool({name:d,arguments:f});await m.close();let C;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{C=JSON.parse(x.text)}catch{C=x.text}else x.type,C=x}else C=v;let{values:b,output:L}=await Z(t.warp,C,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",b,L,v)}catch(h){A.error("WarpExecutor: Error executing MCP",h);let m=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:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}buildCollectResult(t,e,n,i,a,s){let p=G(this.config,this.adapters,t.warp,t.action,a),l=V(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:It(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=W(s.name,this.adapters),l=new B(this.config,p,this.adapters),o=await l.apply(t,a),u=N(o,n),{action:d}=E(o),g=this.factory.getStringTypedInputs(d,i),h=await this.factory.getResolvedInputs(s.name,d,g,l,a.queries),m=await this.factory.getModifiedInputs(h),f=m;if(e.inputs&&e.inputs.length>0){let R=this.factory.getStringTypedInputs(e,i),U=await this.factory.getResolvedInputs(s.name,e,R,l,a.queries);f=await this.factory.getModifiedInputs(U)}let v=te(u.prompt,this.config.platform),C=l.applyInputs(v,f,this.factory.getSerializer(),m),b=V(f),L=S(this.config,s.name),x=this.factory.getSerializer(),{values:F,output:$}=await Yt(o,C,n,f,x,this.config),T=f.find(R=>R.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:L,txHash:null,tx:null,next:G(this.config,this.adapters,o,n,$),values:F,output:$,messages:It(o,$,this.config),destination:T,resolvedInputs:b}}catch(s){return A.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,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=W(p.name,this.adapters),o=new B(this.config,l,this.adapters),{action:u}=E(t),d=this.factory.getStringTypedInputs(u,n),g=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),h=await this.factory.getModifiedInputs(g),m;if(a)m=a;else{let b=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);m=await this.factory.getModifiedInputs(b)}let f=o.buildInputBag(m,this.factory.getSerializer(),h),v={...i.envs??{},...f},C=qt(e.when,v);return zt(C)}};var ht=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 mt=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)?_t(t):Jt(i.identifier);if(this.resolver){let m=null;if(a==="hash")m=await this.resolver.getByHash(s,e);else if(a==="alias"){let f=`${i.chain}:${s}`;m=await this.resolver.getByAlias(f,e)||await this.resolver.getByAlias(s,e)}m&&(p=m.warp,l=m.registryInfo,o=m.brand)}else{let m=W(i.chain,this.adapters);if(a==="hash"){p=await m.builder().createFromTransactionHash(s,e);let f=await m.registry.getInfoByHash(s,e);l=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await m.registry.getInfoByAlias(s,e);l=f.registryInfo,o=f.brand,f.registryInfo&&(p=await m.builder().createFromTransactionHash(f.registryInfo.hash,e))}}if(p&&p.meta&&(dr(p,i.chain,l,i.identifier),p.meta.query=u?Qt(u):null),!p)return n;let d=p.chain||i.chain,g=this.adapters.find(m=>m.chainInfo.name.toLowerCase()===d.toLowerCase()),h=g?await new B(this.config,g,this.adapters).apply(p):p;return{match:!0,url:t,warp:h,chain:d,registryInfo:l,brand:o}}catch(a){return A.error("Error detecting warp link",a),n}}},dr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?xt(null,"alias",e.alias):xt(t,"hash",e?.hash??n))};var he=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 ft(this.config,this.chains,t)}async detectWarp(t,e){return new mt(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 m=await fetch(t);if(!m.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await m.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 m=>{await l.evaluateOutput(p,m)},resolvedInputs:g}}async createInscriptionTransaction(t,e){return await W(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return W(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 W(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(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 W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??E(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=G(this.config,this.chains,e,a,p.output),p}async getRegistry(t){let e=W(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return W(t,this.chains).dataLoader}getWallet(t){return W(t,this.chains).wallet}get factory(){return new Q(this.config,this.chains)}get index(){return new ht(this.config)}get linkBuilder(){return new z(this.config,this.chains)}createBuilder(t){return W(t,this.chains).builder()}createAbiBuilder(t){return W(t,this.chains).abiBuilder()}createBrandBuilder(t){return W(t,this.chains).brandBuilder()}createSerializer(t){return W(t,this.chains).serializer}resolveText(t){return ot(t,this.config)}};var me=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{vt as BrowserCryptoProvider,Er as CLOUD_WALLET_PROVIDERS,ge as CacheTtl,br as EvmWalletChainNames,Tr as MultiversxWalletChainNames,Ct as NodeCryptoProvider,an as WARP_LANGUAGES,I as WarpAssets,oe as WarpBrandBuilder,pe as WarpBuilder,gt as WarpCache,Nt as WarpCacheKey,Be as WarpChainDisplayNames,$e as WarpChainLogos,Ne as WarpChainName,rt as WarpChainResolver,he as WarpClient,nt as WarpCompositeResolver,D as WarpConfig,c as WarpConstants,ft as WarpExecutor,Q as WarpFactory,ht as WarpIndex,y as WarpInputTypes,B as WarpInterpolator,z as WarpLinkBuilder,mt as WarpLinkDetecter,A as WarpLogger,Lt as WarpPlatformName,Ft as WarpPlatforms,q as WarpProtocolVersions,w as WarpSerializer,me as WarpTypeRegistry,lt as WarpValidator,Si as address,It as applyOutputToMessages,se as asset,wi as biguint,Ii as bool,Xe as buildGeneratedFallbackWarpIdentifier,Yn as buildGeneratedSourceWarpIdentifier,pt as buildInputsContext,_ as buildMappedOutput,De as buildNestedPayload,Gr as bytesToBase64,Oe as bytesToHex,pi as checkWarpAssetBalance,K as cleanWarpIdentifier,bt as createAuthHeaders,Pt as createAuthMessage,Jr as createCryptoProvider,ai as createDefaultWalletProvider,Qn as createHttpAuthHeaders,_e as createSignableMessage,on as createWarpI18nText,xt as createWarpIdentifier,rn as doesWarpRequireWallet,Zt as evaluateOutputCommon,zt as evaluateWhenCondition,Z as extractCollectOutput,X as extractIdentifierInfoFromUrl,Yt as extractPromptOutput,Jt as extractQueryStringFromIdentifier,_t as extractQueryStringFromUrl,V as extractResolvedInputValues,Xr as extractWarpSecrets,W as findWarpAdapterForChain,Vr as getChainDisplayName,Hr as getChainLogo,Dt as getCryptoProvider,Ur as getEventNameFromWarp,Je as getGeneratedSourceWarpName,at as getLatestProtocolIdentifier,G as getNextInfo,zn as getProviderConfig,jt as getRandomBytes,Mt as getRandomHex,Ze as getRequiredAssetIds,yr as getWalletFromConfigOrFail,N as getWarpActionByIndex,jr as getWarpBrandLogoUrl,Mr as getWarpChainAssetLogoUrl,kr as getWarpChainInfoLogoUrl,gn as getWarpIdentifierWithQuery,O as getWarpInfoFromIdentifier,E as getWarpPrimaryAction,Ie as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,be as getWarpWalletExternalId,Te as getWarpWalletExternalIdFromConfig,Cr as getWarpWalletExternalIdFromConfigOrFail,Pe as getWarpWalletMnemonic,vr as getWarpWalletMnemonicFromConfig,Se as getWarpWalletPrivateKey,Wr as getWarpWalletPrivateKeyFromConfig,ae as handleX402Payment,mn as hasInputPrefix,Pi as hex,ni as initializeWalletCache,un as isEqualWarpIdentifier,ei as isGeneratedSourcePrivateIdentifier,Ge as isPlatformValue,At as isWarpActionAutoExecute,sn as isWarpI18nText,Ar as isWarpWalletReadOnly,Kt as mergeNestedPayload,Ir as normalizeAndValidateMnemonic,Ee as normalizeMnemonic,bi as option,ze as parseOutputOutIndex,Xn as parseSignedMessage,Qt as parseWarpQueryStringToObject,dn as removeWarpChainPrefix,wr as removeWarpWalletFromConfig,M as replacePlaceholders,qt as replacePlaceholdersInWhenExpression,te as resolvePlatformValue,ot as resolveWarpText,Ut as safeWindow,zr as setCryptoProvider,xr as setWarpWalletInConfig,st as shiftBigintBy,wt as splitInput,ti as stampGeneratedWarpMeta,Wi as string,Ei as struct,_r as testCryptoAvailability,je as toInputPayloadValue,kt as toPreviewText,Ti as tuple,Ci as uint16,Ai as uint32,xi as uint64,vi as uint8,Re as validateMnemonicLength,Kn as validateSignedMessage,Ri as vector,$r as withAdapterFallback};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joai/warps",
3
- "version": "4.10.0",
3
+ "version": "4.11.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",