@joai/warps 3.0.0-beta.203 → 3.0.0-beta.205

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
@@ -769,6 +769,7 @@ declare const extractIdentifierInfoFromUrl: (url: string, defaultChain?: WarpCha
769
769
  } | null;
770
770
  declare const extractQueryStringFromUrl: (url: string) => string | null;
771
771
  declare const extractQueryStringFromIdentifier: (identifier: string) => string | null;
772
+ declare const parseWarpQueryStringToObject: (queryString: string | null) => Record<string, string>;
772
773
 
773
774
  /**
774
775
  * Splits an input string into type and value, using only the first colon as separator.
@@ -1272,4 +1273,4 @@ declare class WarpValidator {
1272
1273
  private validateSchema;
1273
1274
  }
1274
1275
 
1275
- export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
1276
+ export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
package/dist/index.d.ts CHANGED
@@ -769,6 +769,7 @@ declare const extractIdentifierInfoFromUrl: (url: string, defaultChain?: WarpCha
769
769
  } | null;
770
770
  declare const extractQueryStringFromUrl: (url: string) => string | null;
771
771
  declare const extractQueryStringFromIdentifier: (identifier: string) => string | null;
772
+ declare const parseWarpQueryStringToObject: (queryString: string | null) => Record<string, string>;
772
773
 
773
774
  /**
774
775
  * Splits an input string into type and value, using only the first colon as separator.
@@ -1272,4 +1273,4 @@ declare class WarpValidator {
1272
1273
  private validateSchema;
1273
1274
  }
1274
1275
 
1275
- export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
1276
+ export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var be=Object.create;var ut=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,Be=Object.prototype.hasOwnProperty;var $e=(r,t)=>{for(var e in t)ut(r,e,{get:t[e],enumerable:!0})},Yt=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Re(t))!Be.call(r,i)&&i!==e&&ut(r,i,{get:()=>t[i],enumerable:!(n=Ee(t,i))||n.enumerable});return r};var G=(r,t,e)=>(e=r!=null?be(Ne(r)):{},Yt(t||!r||!r.__esModule?ut(e,"default",{value:r,enumerable:!0}):e,r)),Oe=r=>Yt(ut({},"__esModule",{value:!0}),r);var Hr={};$e(Hr,{BrowserCryptoProvider:()=>dt,CacheTtl:()=>kt,EvmWalletChainNames:()=>Me,NodeCryptoProvider:()=>ft,WARP_LANGUAGES:()=>Ye,WarpBrandBuilder:()=>Mt,WarpBuilder:()=>zt,WarpCache:()=>st,WarpCacheKey:()=>It,WarpChainName:()=>oe,WarpClient:()=>Qt,WarpConfig:()=>U,WarpConstants:()=>l,WarpExecutor:()=>pt,WarpFactory:()=>k,WarpIndex:()=>ct,WarpInputTypes:()=>g,WarpInterpolator:()=>E,WarpLinkBuilder:()=>z,WarpLinkDetecter:()=>lt,WarpLogger:()=>C,WarpProtocolVersions:()=>L,WarpSerializer:()=>w,WarpTypeRegistry:()=>Kt,WarpValidator:()=>nt,address:()=>Sr,applyOutputToMessages:()=>yt,asset:()=>Lt,biguint:()=>wr,bool:()=>Ir,buildMappedOutput:()=>J,buildNestedPayload:()=>ue,bytesToBase64:()=>Qe,bytesToHex:()=>pe,cleanWarpIdentifier:()=>et,createAuthHeaders:()=>At,createAuthMessage:()=>vt,createCryptoProvider:()=>Xe,createDefaultWalletProvider:()=>hr,createHttpAuthHeaders:()=>ur,createSignableMessage:()=>he,createWarpI18nText:()=>er,createWarpIdentifier:()=>ht,evaluateOutputCommon:()=>Vt,evaluateWhenCondition:()=>Nt,extractCollectOutput:()=>rt,extractIdentifierInfoFromUrl:()=>_,extractPromptOutput:()=>Ft,extractQueryStringFromIdentifier:()=>$t,extractQueryStringFromUrl:()=>Bt,extractResolvedInputValues:()=>R,extractWarpSecrets:()=>Ze,findWarpAdapterForChain:()=>W,getCryptoProvider:()=>Pt,getEventNameFromWarp:()=>qe,getLatestProtocolIdentifier:()=>Z,getNextInfo:()=>Wt,getProviderConfig:()=>lr,getRandomBytes:()=>Tt,getRandomHex:()=>bt,getWalletFromConfigOrFail:()=>He,getWarpActionByIndex:()=>b,getWarpBrandLogoUrl:()=>ke,getWarpChainAssetLogoUrl:()=>Ge,getWarpChainInfoLogoUrl:()=>_e,getWarpInfoFromIdentifier:()=>$,getWarpPrimaryAction:()=>B,getWarpWalletAddress:()=>te,getWarpWalletAddressFromConfig:()=>I,getWarpWalletExternalId:()=>ne,getWarpWalletExternalIdFromConfig:()=>ie,getWarpWalletExternalIdFromConfigOrFail:()=>Ue,getWarpWalletMnemonic:()=>re,getWarpWalletMnemonicFromConfig:()=>Fe,getWarpWalletPrivateKey:()=>ee,getWarpWalletPrivateKeyFromConfig:()=>Ve,handleX402Payment:()=>jt,hasInputPrefix:()=>ar,hex:()=>Pr,initializeWalletCache:()=>gr,isEqualWarpIdentifier:()=>rr,isWarpActionAutoExecute:()=>gt,isWarpI18nText:()=>tr,isWarpWalletReadOnly:()=>De,mergeNestedPayload:()=>Ht,normalizeAndValidateMnemonic:()=>Le,normalizeMnemonic:()=>ae,option:()=>Tr,parseOutputOutIndex:()=>ge,parseSignedMessage:()=>fr,replacePlaceholders:()=>D,replacePlaceholdersInWhenExpression:()=>Rt,resolveWarpText:()=>tt,safeWindow:()=>St,setCryptoProvider:()=>Je,setWarpWalletInConfig:()=>je,shiftBigintBy:()=>Y,splitInput:()=>mt,string:()=>Wr,struct:()=>Er,testCryptoAvailability:()=>Ke,toInputPayloadValue:()=>de,toPreviewText:()=>Et,tuple:()=>br,uint16:()=>Ar,uint32:()=>Cr,uint64:()=>xr,uint8:()=>vr,validateMnemonicLength:()=>se,validateSignedMessage:()=>dr,vector:()=>Rr,withAdapterFallback:()=>ze});module.exports=Oe(Hr);var He=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},te=r=>r?typeof r=="string"?r:r.address:null,I=(r,t)=>te(r.user?.wallets?.[t]||null),ee=r=>r?typeof r=="string"?r:r.privateKey||null:null,re=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ne=r=>r?typeof r=="string"?r:r.externalId||null:null,Ve=(r,t)=>ee(r.user?.wallets?.[t]||null)?.trim()||null,Fe=(r,t)=>re(r.user?.wallets?.[t]||null)?.trim()||null,ie=(r,t)=>ne(r.user?.wallets?.[t]||null)?.trim()||null,Ue=(r,t)=>{let e=ie(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},De=r=>typeof r=="string",je=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},ae=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},se=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},Le=(r,t=24)=>{let e=ae(r);return se(e,t),e};var oe=(d=>(d.Multiversx="multiversx",d.Vibechain="vibechain",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(oe||{}),Me=["ethereum","base","arbitrum","polygon","somnia"],l={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>I(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"}},g={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},St=typeof window<"u"?window:{open:()=>{}};var L={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},U={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${L.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${L.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",l.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 ze=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var qe=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var ke=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Ge=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},_e=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var dt=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}},ft=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},M=null;function Pt(){if(M)return M;if(typeof window<"u"&&window.crypto)return M=new dt,M;if(typeof process<"u"&&process.versions?.node)return M=new ft,M;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Je(r){M=r}async function Tt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Pt()).getRandomBytes(r)}function pe(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 Qe(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 bt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Tt(r/2,t);return pe(e)}async function Ke(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await Tt(16),r.randomBytes=!0}catch{}return r}function Xe(){return Pt()}var Ze=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.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},Z=r=>{if(r==="warp")return`warp:${L.Warp}`;if(r==="brand")return`brand:${L.Brand}`;if(r==="abi")return`abi:${L.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},b=(r,t)=>r?.actions[t-1],B=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","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}},gt=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=B(t);return r===e}return!0},Y=(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)},Et=(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},D=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>t[n]||""),Rt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Nt=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 Ye={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"},tt=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},tr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,er=r=>r;var et=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,rr=(r,t)=>!r||!t?!1:et(r)===et(t),ht=(r,t,e)=>{let n=et(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},$=(r,t)=>{let e=t||l.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=et(n),a=i.split("?")[0],s=ce(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:l.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,c,o]=s;if(c===l.IdentifierType.Alias||c===l.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:c,identifier:u,identifierBase:o}}}if(s.length===2){let[p,c]=s;if(p===l.IdentifierType.Alias||p===l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c;return{chain:e,type:p,identifier:o,identifierBase:c}}}if(s.length===2){let[p,c]=s;if(p!==l.IdentifierType.Alias&&p!==l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c,u=nr(c,p)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:c}}}return{chain:e,type:l.IdentifierType.Alias,identifier:i,identifierBase:a}},_=(r,t)=>{let e=new URL(r),i=e.searchParams.get(l.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return $(a,t)},nr=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,ir=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},ce=r=>{let t=ir(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=ce(a);return[i,...s]},Bt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},$t=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null};var mt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},ar=r=>{let t=new Set(Object.values(g));if(!r.includes(l.ArgParamsSeparator))return!1;let e=mt(r)[0];return t.has(e)};var yt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=tt(a,e);return[i,D(s,t)]});return Object.fromEntries(n)};var le=G(require("qr-code-styling"),1);var z=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!_(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,p=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(p);return U.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=$(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 c=W(t,this.adapters),o=this.build(c.chainInfo.name,e,n);return new le.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 sr="https://",Wt=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(sr))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=D(s,{...e.vars,...i});return[{identifier:f,url:Ot(t,f,r)}]}let c=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=D(p,{...e.vars,...i}),A=f?`${s}?${f}`:s;return[{identifier:A,url:Ot(t,A,r)}]}let o=c[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let m=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let A=f.match(/\[\](\.[^}]+)?}}/),v=A&&A[1]||"";return{placeholder:f,field:v?v.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let A=p;for(let{regex:O,field:H}of m){let x=H?or(f,H):f;if(x==null)return null;A=A.replace(O,x)}if(A.includes("{{")||A.includes("}}"))return null;let v=A?`${s}?${A}`:s;return{identifier:v,url:Ot(t,v,r)}}).filter(f=>f!==null)},Ot=(r,t,e)=>{let[n,i]=t.split("?"),a=$(n,e.defaultChain)||{chain:l.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 c=new URL(p);return new URLSearchParams(i).forEach((o,u)=>c.searchParams.set(u,o)),c.toString().replace(/\/\?/,"?")},or=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var q=class q{static debug(...t){q.isTestEnv||console.debug(...t)}static info(...t){q.isTestEnv||console.info(...t)}static warn(...t){q.isTestEnv||console.warn(...t)}static error(...t){q.isTestEnv||console.error(...t)}};q.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=q;function ue(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Ht(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]=Ht(e[n],t[n]):e[n]=t[n]}),e}function de(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 R(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=de(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(l.Position.Payload)){let s=ue(n.input.position,i,a);e=Ht(e,s)}else e[i]=a}),e}var fe=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(l.Transform.Prefix))continue;let c=ge(p);if(c!==null&&c!==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}},rt=async(r,t,e,n,i,a)=>{let s=(d,h)=>h.reduce((m,y)=>m&&m[y]!==void 0?m[y]:null,d),p=d=>d.length===0?t?.data||t:s(t,d),{stringValues:c,nativeValues:o,output:u}=fe(r,e,p);return{values:{string:c,native:o,mapped:J(n,i)},output:await Vt(r,u,e,n,i,a)}},Vt=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t};return s=pr(s,r,e,n,i),s=await cr(r,s,a.transform?.runner||null),s},pr=(r,t,e,n,i)=>{let a={...r},s=b(t,e)?.inputs||[];for(let[p,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let o=c.split(".")[1],u=s.findIndex(h=>h.as===o||h.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},cr=async(r,t,e)=>{if(!r.output)return t;let n={...t},i=Object.entries(r.output).filter(([,a])=>a.startsWith(l.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(l.Transform.Prefix.length)}));if(i.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:a,code:s}of i)try{n[a]=await e.run(s,n)}catch(p){C.error(`Transform error for Warp '${r.name}' with output '${a}':`,p),n[a]=null}return n},Ft=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:c,output:o}=fe(r,e,s),u=await Vt(r,o,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:c,mapped:J(n,i)},output:u}},ge=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var 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 he(r,t,e,n=5){let i=await bt(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 vt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return he(r,i,e,5)}function At(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 vt(r,e,n),p=await t(i);return At(r,p,a,s)}function dr(r){let t=new Date(r).getTime();return Date.now()<t}function fr(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"}`)}}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 hr(r,t,e){return null}var Ut=require("@x402/core/client"),Dt=require("@x402/core/http");async function jt(r,t,e,n,i){let a=await mr(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(([c,o])=>{s.set(c,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 mr=async(r,t)=>{let e=await yr(r),i=new Dt.x402HTTPClient(new Ut.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 Ut.x402Client,p=await a.wallet.registerX402Handlers(s),c=i.accepts.find(h=>h?.network&&p[h.network]);if(!c?.network)continue;p[c.network]();let o=new Dt.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 ${c.network} scheme`),d}catch{continue}return null},yr=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===g.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===g.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${l.ArgParamsSeparator}`;let s=a.map(p=>{let[c,o]=this.getTypeAndValue(n[p]);return`(${p}${l.ArgParamsSeparator}${c})${o}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===g.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let o=c.indexOf(l.ArgParamsSeparator),u=c.substring(o+1);return a.startsWith(g.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),p=a.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(p)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===g.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?g.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):g.Asset+l.ArgParamsSeparator+e.identifier+l.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+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===g.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[g.Option+l.ArgParamsSeparator+a,s||null]}if(n===g.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),c=s.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(p?p.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[g.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(g.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),p=i.split(l.ArgCompositeSeparator).map((c,o)=>this.stringToNative(`${a[o]}${l.IdentifierParamSeparator}${c}`)[1]);return[n,p]}else if(n.startsWith(g.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(l.ArgListSeparator).forEach(c=>{let o=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[1]}}),[n,p]}else{if(n===g.String)return[n,i];if(n===g.Uint8||n===g.Uint16||n===g.Uint32)return[n,Number(i)];if(n===g.Uint64||n===g.Uint128||n===g.Uint256||n===g.Biguint)return[n,BigInt(i||0)];if(n===g.Bool)return[n,i==="true"];if(n===g.Address)return[n,i];if(n===g.Hex)return[n,i];if(n===g.Asset){let[a,s]=i.split(l.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,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[g.Uint32,t]:typeof t=="bigint"?[g.Uint64,t]:typeof t=="boolean"?[g.Bool,t]:[typeof t,t]}};var Wr=r=>new w().nativeToString(g.String,r),vr=r=>new w().nativeToString(g.Uint8,r),Ar=r=>new w().nativeToString(g.Uint16,r),Cr=r=>new w().nativeToString(g.Uint32,r),xr=r=>new w().nativeToString(g.Uint64,r),wr=r=>new w().nativeToString(g.Biguint,r),Ir=r=>new w().nativeToString(g.Bool,r),Sr=r=>new w().nativeToString(g.Address,r),Lt=r=>new w().nativeToString(g.Asset,r),Pr=r=>new w().nativeToString(g.Hex,r),Tr=(r,t)=>{if(t===null)return g.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return g.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},br=(...r)=>new w().nativeToString(g.Tuple,r),Er=r=>new w().nativeToString(g.Struct,r),Rr=r=>new w().nativeToString(g.Vector,r);var me=G(require("ajv"),1);var Mt=class{constructor(t){this.pendingBrand={protocol:Z("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||U.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new me.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var ye=G(require("ajv"),1);var nt=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}=B(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||U.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new ye.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 zt=class{constructor(t){this.config=t;this.pendingWarp={protocol:Z("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 Et(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 nt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
- `))}};var S=require("fs"),K=require("path");var We=new w,Ct=(r,t)=>typeof t=="bigint"?We.nativeToString("biguint",t):t,Q=(r,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?We.stringToNative(t)[1]:t;var xt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,K.resolve)(n):(0,K.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,S.existsSync)(this.cacheDir)||(0,S.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,K.join)(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!(0,S.existsSync)(e))return null;let n=(0,S.readFileSync)(e,"utf-8"),i=JSON.parse(n,Q);return Date.now()>i.expiresAt?((0,S.unlinkSync)(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);(0,S.writeFileSync)(a,JSON.stringify(i,Ct),"utf-8")}forget(t){try{let e=this.getFilePath(t);(0,S.existsSync)(e)&&(0,S.unlinkSync)(e)}catch{}}clear(){try{(0,S.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,S.unlinkSync)((0,K.join)(this.cacheDir,e))})}catch{}}};var it=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,Q);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,Ct))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var j=class j{constructor(t,e){}get(t){let e=j.cache.get(t);return e?Date.now()>e.expiresAt?(j.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;j.cache.set(t,{value:e,expiresAt:i})}forget(t){j.cache.delete(t)}clear(){j.cache.clear()}};j.cache=new Map;var at=j;var ve=require("fs"),qt=require("path");var wt=class{constructor(t,e){let n=e?.path?(0,qt.resolve)(e.path):(0,qt.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,ve.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,Q)))}catch(e){return C.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a)}forget(t){this.cache.delete(t)}clear(){this.cache.clear()}};var kt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},It={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}`},st=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new it(t,e):e?.type==="memory"?new at(t,e):e?.type==="static"?new wt(t,e):e?.type==="filesystem"?new xt(t,e):typeof window<"u"&&window.localStorage?new it(t,e):new at(t,e)}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var ot={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Gt={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)},Jt=r=>{try{return JSON.parse(r)}catch{return null}},Nr=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:c,nonce:o,expiresAt:u}=await vt(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(At(n,d,o,u)).forEach(([h,m])=>s.set(h,m))}let p=_t(e.resolvedInputs,ot.Headers,i);if(p){let c=Jt(p);c&&typeof c=="object"&&Object.entries(c).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([c,o])=>{s.set(c,r.applyInputs(o,e.resolvedInputs,i))});return s},Br=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Gt.Get){let s=_t(e.resolvedInputs,ot.Queries,i);if(s){let p=Jt(s);if(p&&typeof p=="object"){let c=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&c.searchParams.set(o,String(u))),a=c.toString()}}}return a},$r=(r,t,e,n,i)=>{if(r===Gt.Get)return;let a=_t(t.resolvedInputs,ot.Payload,n);if(a&&Jt(a)!==null)return a;let{[ot.Payload]:s,[ot.Queries]:p,...c}=e;return JSON.stringify({...c,...i})},Ae=async(r,t,e,n,i,a,s,p)=>{let c=t.method||Gt.Get,o=await Nr(r,t,e,n,a,p),u=Br(r,t,e,c,a),d=$r(c,e,i,a,s);return{url:u,method:c,headers:o,body:d}};var E=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);return await this.applyGlobals(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=I(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(l.Vars.Query+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Query.length+1),[o,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,m=e.queries?.[o]||null||d;m&&a(s,m)}else if(p.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Env.length+1),[o,u]=c.split(l.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h&&a(s,h)}else p===l.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(l.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(l.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 D(a,s)}applyGlobalsToText(t){if(!Object.values(l.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(l.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 c=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(c,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 c=p;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var k=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 st(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(It.WarpExecutable(t,e||"",n))||[];return R(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),c=new E(this.config,p,this.adapters),o=await c.apply(t,i),u=b(o,e),{action:d,index:h}=B(o),m=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(s.name,d,m,c),f=await this.getModifiedInputs(y),A=[],v=[];h===e-1?(A=y,v=f):this.requiresPayloadInputs(u)&&(A=await this.resolveActionInputs(s.name,u,n,c),v=await this.getModifiedInputs(A));let O=v.find(P=>P.input.position==="receiver"||P.input.position==="destination")?.value,H=this.getDestinationFromAction(u),x=O?this.serializer.stringToNative(O)[1]:H;if(x&&(x=c.applyInputs(x,v,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let N=this.getPreparedArgs(u,v);N=N.map(P=>c.applyInputs(P,v,this.serializer,f));let V=v.find(P=>P.input.position==="value")?.value||null,T="value"in u?u.value:null,F=V?.split(l.ArgParamsSeparator)[1]||T||"0",X=c.applyInputs(F,v,this.serializer,f),Ce=BigInt(X),xe=v.filter(P=>P.input.position==="transfer"&&P.value).map(P=>P.value),we=[...("transfers"in u?u.transfers:[])||[],...xe||[]].map(P=>{let Te=c.applyInputs(P,v,this.serializer,f);return this.serializer.stringToNative(Te)[1]}),Ie=v.find(P=>P.input.position==="data")?.value,Se="data"in u?u.data||"":null,Xt=Ie||Se||null,Pe=Xt?c.applyInputs(Xt,v,this.serializer,f):null,Zt={adapter:p,warp:o,chain:s,action:e,destination:x,args:N,value:Ce,transfers:we,data:Pe,resolvedInputs:v};return this.cache.set(It.WarpExecutable(this.config.env,o.meta?.hash||"",e),Zt.resolvedInputs,kt.OneWeek),Zt}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(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i){let a=e.inputs||[],s=n.map(o=>i.applyInputs(o,[],this.serializer)),p=await Promise.all(s.map(o=>this.preprocessInput(t,o))),c=(o,u)=>{if(o.source==="query"){let d=this.url.searchParams.get(o.name);return d?this.serializer.nativeToString(o.type,d):null}else if(o.source===l.Source.UserWallet){let d=I(this.config,t);return d?this.serializer.nativeToString("address",d):null}else if(o.source==="hidden"){if(o.default===void 0)return null;let d=i?i.applyInputs(String(o.default),[],this.serializer):String(o.default);return this.serializer.nativeToString(o.type,d)}else return p[u]||null};return a.map((o,u)=>{let d=c(o,u),h=o.default!==void 0?i?i.applyInputs(String(o.default),[],this.serializer):String(o.default):void 0;return{input:o,value:d||(h!==void 0?this.serializer.nativeToString(o.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){let a=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,a,i)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,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 c=Y(p,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=Y(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.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=this.buildInputContext(t,n,i),c=await s.run(a,p);if(c==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:o})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let a=0;a<e;a++){let s=t[a];if(!s.value)continue;let p=s.input.as||s.input.name,[,c]=this.serializer.stringToNative(s.value);if(i[p]=c,s.input.type==="asset"&&typeof c=="object"&&c!==null){let o=c;"identifier"in o&&"amount"in o&&(i[`${p}.token`]=String(o.identifier),i[`${p}.amount`]=String(o.amount),i[`${p}.identifier`]=String(o.identifier))}}if(n&&n.value){let a=n.input.as||n.input.name,[,s]=this.serializer.stringToNative(n.value);if(i[a]=s,n.input.type==="asset"&&typeof s=="object"&&s!==null){let p=s;"identifier"in p&&"amount"in p&&(i[`${a}.token`]=String(p.identifier),i[`${a}.amount`]=String(p.amount),i[`${a}.identifier`]=String(p.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=mt(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,c]=i.split(l.ArgCompositeSeparator);if(c)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=Y(p,o.decimals);return Lt({...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,c]=this.serializer.stringToNative(s),o=c;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(c=>c.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.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 pt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new k(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],{action:c,index:o}=B(t);for(let u=1;u<=t.actions.length;u++){let d=b(t,u);if(!gt(d,t))continue;let{tx:h,chain:m,immediateExecution:y,executable:f}=await this.executeAction(t,u,e,n);h&&i.push(h),m&&(a=m),y&&s.push(y),f&&u===o+1&&f.resolvedInputs&&(p=R(f.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 u=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}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):St.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==="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(!gt(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[p],o=p+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:I(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:c})):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=I(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:c}=await rt(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,c)}async doHttpRequest(t,e,n,i,a){let s=new E(this.config,W(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:c,method:o,headers:u,body:d}=await Ae(s,e,t,n,i,p,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:o,headers:u,body:d});try{let m=await fetch(c,{method:o,headers:u,body:d});C.debug("Collect response status",{status:m.status}),m.status===402&&(m=await jt(m,c,o,d,this.adapters));let y=await m.json();C.debug("Collect response content",{content:y});let{values:f,output:A}=await rt(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,I(this.config,t.chain.name),m.ok?"success":"error",f,A,y)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let m=R(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=I(this.config,t.chain.name),i=b(t.warp,t.action);if(!i.destination){let m=R(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let y=R(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:y}}let p=this.factory.getSerializer(),c=new E(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,u=c.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([m,y])=>{let f=c.applyInputs(y,t.resolvedInputs,this.factory.getSerializer());h[m]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let m=new s(new URL(u),{requestInit:{headers:h}}),y=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(m);let f={};t.resolvedInputs.forEach(({input:x,value:N})=>{if(N&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let V=x.position.replace("payload:",""),[T,F]=p.stringToNative(N);if(T==="string")f[V]=String(F);else if(T==="bool")f[V]=!!F;else if(T==="uint8"||T==="uint16"||T==="uint32"||T==="uint64"||T==="uint128"||T==="uint256"||T==="biguint"){let X=Number(F);f[V]=(Number.isInteger(X),X)}else f[V]=F}}),e&&Object.assign(f,e);let A=await y.callTool({name:d,arguments:f});await y.close();let v;if(A.content&&A.content.length>0){let x=A.content[0];if(x.type==="text")try{v=JSON.parse(x.text)}catch{v=x.text}else x.type,v=x}else v=A;let{values:O,output:H}=await rt(t.warp,v,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",O,H,A)}catch(m){C.error("WarpExecutor: Error executing MCP",m);let y=R(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:m},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:y}}}buildCollectResult(t,e,n,i,a,s){let p=Wt(this.config,this.adapters,t.warp,t.action,a),c=R(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||I(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:yt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}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),c=new E(this.config,p,this.adapters),o=await c.apply(t,a),u=b(o,n),{action:d}=B(o),h=this.factory.getStringTypedInputs(d,i),m=await this.factory.getResolvedInputs(s.name,d,h,c),y=await this.factory.getModifiedInputs(m),f=y;if(e.inputs&&e.inputs.length>0){let V=this.factory.getStringTypedInputs(e,i),T=await this.factory.getResolvedInputs(s.name,e,V,c);f=await this.factory.getModifiedInputs(T)}let A=c.applyInputs(u.prompt,f,this.factory.getSerializer(),y),v=R(f),O=I(this.config,s.name),H=this.factory.getSerializer(),{values:x,output:N}=await Ft(o,A,n,f,H,this.config);return{status:"success",warp:o,action:n,user:O,txHash:null,tx:null,next:Wt(this.config,this.adapters,o,n,N),values:x,output:N,messages:yt(o,N,this.config),destination:null,resolvedInputs:v}}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),c=W(p.name,this.adapters),o=new E(this.config,c,this.adapters),{action:u}=B(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(p.name,u,d,o),m=await this.factory.getModifiedInputs(h),y;if(a)y=a;else{let v=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o);y=await this.factory.getModifiedInputs(v)}let f=o.buildInputBag(y,this.factory.getSerializer(),m),A=Rt(e.when,f);return Nt(A)}};var ct=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 lt=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!_(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,c=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?_(t,this.config.defaultChain):$(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,c=null,o=null,u=W(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?Bt(t):$t(i.identifier);if(a==="hash"){p=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,o=f.brand,f.registryInfo&&(p=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(p&&p.meta&&(Or(p,u.chainInfo.name,c,i.identifier),p.meta.query=d),!p)return n;let h=p.chain||u.chainInfo.name,m=W(h,this.adapters),y=await new E(this.config,m,this.adapters).apply(p);return{match:!0,url:t,warp:y,chain:h,registryInfo:c,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},Or=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?ht(t,"alias",e.alias):ht(t,"hash",e?.hash??n))};var Qt=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new pt(this.config,this.chains,t)}async detectWarp(t,e){return new lt(this.config,this.chains).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 y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await y.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await c.evaluateOutput(p,y)},resolvedInputs:h}}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=$(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(!I(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 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 k(this.config,this.chains)}get index(){return new ct(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 tt(t,this.config)}};var Kt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,EvmWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
1
+ "use strict";var Ee=Object.create;var ut=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Be=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Oe=(r,t)=>{for(var e in t)ut(r,e,{get:t[e],enumerable:!0})},te=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ne(t))!$e.call(r,i)&&i!==e&&ut(r,i,{get:()=>t[i],enumerable:!(n=Re(t,i))||n.enumerable});return r};var G=(r,t,e)=>(e=r!=null?Ee(Be(r)):{},te(t||!r||!r.__esModule?ut(e,"default",{value:r,enumerable:!0}):e,r)),Ve=r=>te(ut({},"__esModule",{value:!0}),r);var Hr={};Oe(Hr,{BrowserCryptoProvider:()=>dt,CacheTtl:()=>Gt,EvmWalletChainNames:()=>ze,NodeCryptoProvider:()=>ft,WARP_LANGUAGES:()=>tr,WarpBrandBuilder:()=>zt,WarpBuilder:()=>qt,WarpCache:()=>st,WarpCacheKey:()=>It,WarpChainName:()=>pe,WarpClient:()=>Kt,WarpConfig:()=>U,WarpConstants:()=>l,WarpExecutor:()=>pt,WarpFactory:()=>k,WarpIndex:()=>ct,WarpInputTypes:()=>h,WarpInterpolator:()=>R,WarpLinkBuilder:()=>z,WarpLinkDetecter:()=>lt,WarpLogger:()=>C,WarpProtocolVersions:()=>L,WarpSerializer:()=>w,WarpTypeRegistry:()=>Xt,WarpValidator:()=>nt,address:()=>Pr,applyOutputToMessages:()=>yt,asset:()=>Mt,biguint:()=>Ir,bool:()=>Sr,buildMappedOutput:()=>J,buildNestedPayload:()=>de,bytesToBase64:()=>Ke,bytesToHex:()=>ce,cleanWarpIdentifier:()=>et,createAuthHeaders:()=>At,createAuthMessage:()=>vt,createCryptoProvider:()=>Ze,createDefaultWalletProvider:()=>mr,createHttpAuthHeaders:()=>dr,createSignableMessage:()=>me,createWarpI18nText:()=>rr,createWarpIdentifier:()=>ht,evaluateOutputCommon:()=>Ft,evaluateWhenCondition:()=>Nt,extractCollectOutput:()=>rt,extractIdentifierInfoFromUrl:()=>_,extractPromptOutput:()=>Ut,extractQueryStringFromIdentifier:()=>$t,extractQueryStringFromUrl:()=>Bt,extractResolvedInputValues:()=>N,extractWarpSecrets:()=>Ye,findWarpAdapterForChain:()=>y,getCryptoProvider:()=>Pt,getEventNameFromWarp:()=>ke,getLatestProtocolIdentifier:()=>Z,getNextInfo:()=>Wt,getProviderConfig:()=>ur,getRandomBytes:()=>Tt,getRandomHex:()=>bt,getWalletFromConfigOrFail:()=>He,getWarpActionByIndex:()=>E,getWarpBrandLogoUrl:()=>Ge,getWarpChainAssetLogoUrl:()=>_e,getWarpChainInfoLogoUrl:()=>Je,getWarpInfoFromIdentifier:()=>O,getWarpPrimaryAction:()=>$,getWarpWalletAddress:()=>ee,getWarpWalletAddressFromConfig:()=>I,getWarpWalletExternalId:()=>ie,getWarpWalletExternalIdFromConfig:()=>ae,getWarpWalletExternalIdFromConfigOrFail:()=>De,getWarpWalletMnemonic:()=>ne,getWarpWalletMnemonicFromConfig:()=>Ue,getWarpWalletPrivateKey:()=>re,getWarpWalletPrivateKeyFromConfig:()=>Fe,handleX402Payment:()=>Lt,hasInputPrefix:()=>sr,hex:()=>Tr,initializeWalletCache:()=>hr,isEqualWarpIdentifier:()=>nr,isWarpActionAutoExecute:()=>gt,isWarpI18nText:()=>er,isWarpWalletReadOnly:()=>je,mergeNestedPayload:()=>Ht,normalizeAndValidateMnemonic:()=>Me,normalizeMnemonic:()=>se,option:()=>br,parseOutputOutIndex:()=>he,parseSignedMessage:()=>gr,parseWarpQueryStringToObject:()=>Ot,replacePlaceholders:()=>D,replacePlaceholdersInWhenExpression:()=>Rt,resolveWarpText:()=>tt,safeWindow:()=>St,setCryptoProvider:()=>Qe,setWarpWalletInConfig:()=>Le,shiftBigintBy:()=>Y,splitInput:()=>mt,string:()=>vr,struct:()=>Rr,testCryptoAvailability:()=>Xe,toInputPayloadValue:()=>fe,toPreviewText:()=>Et,tuple:()=>Er,uint16:()=>Cr,uint32:()=>xr,uint64:()=>wr,uint8:()=>Ar,validateMnemonicLength:()=>oe,validateSignedMessage:()=>fr,vector:()=>Nr,withAdapterFallback:()=>qe});module.exports=Ve(Hr);var He=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},ee=r=>r?typeof r=="string"?r:r.address:null,I=(r,t)=>ee(r.user?.wallets?.[t]||null),re=r=>r?typeof r=="string"?r:r.privateKey||null:null,ne=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ie=r=>r?typeof r=="string"?r:r.externalId||null:null,Fe=(r,t)=>re(r.user?.wallets?.[t]||null)?.trim()||null,Ue=(r,t)=>ne(r.user?.wallets?.[t]||null)?.trim()||null,ae=(r,t)=>ie(r.user?.wallets?.[t]||null)?.trim()||null,De=(r,t)=>{let e=ae(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},je=r=>typeof r=="string",Le=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},se=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},oe=(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`)},Me=(r,t=24)=>{let e=se(r);return oe(e,t),e};var pe=(d=>(d.Multiversx="multiversx",d.Vibechain="vibechain",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(pe||{}),ze=["ethereum","base","arbitrum","polygon","somnia"],l={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>I(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"}},h={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"},St=typeof window<"u"?window:{open:()=>{}};var L={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},U={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${L.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${L.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",l.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 qe=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var ke=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var Ge=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},_e=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},Je=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var dt=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}},ft=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},M=null;function Pt(){if(M)return M;if(typeof window<"u"&&window.crypto)return M=new dt,M;if(typeof process<"u"&&process.versions?.node)return M=new ft,M;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Qe(r){M=r}async function Tt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Pt()).getRandomBytes(r)}function ce(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 Ke(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 bt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Tt(r/2,t);return ce(e)}async function Xe(){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 Tt(16),r.randomBytes=!0}catch{}return r}function Ze(){return Pt()}var Ye=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.ArgCompositeSeparator);return{key:n,description:i||null}});var y=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},Z=r=>{if(r==="warp")return`warp:${L.Warp}`;if(r==="brand")return`brand:${L.Brand}`;if(r==="abi")return`abi:${L.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},E=(r,t)=>r?.actions[t-1],$=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","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}},gt=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=$(t);return r===e}return!0},Y=(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)},Et=(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},D=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>t[n]||""),Rt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Nt=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var tr={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},tt=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},er=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,rr=r=>r;var et=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,nr=(r,t)=>!r||!t?!1:et(r)===et(t),ht=(r,t,e)=>{let n=et(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},O=(r,t)=>{let e=t||l.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=et(n),a=i.split("?")[0],s=le(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:l.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,c,o]=s;if(c===l.IdentifierType.Alias||c===l.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:c,identifier:u,identifierBase:o}}}if(s.length===2){let[p,c]=s;if(p===l.IdentifierType.Alias||p===l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c;return{chain:e,type:p,identifier:o,identifierBase:c}}}if(s.length===2){let[p,c]=s;if(p!==l.IdentifierType.Alias&&p!==l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c,u=ir(c,p)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:c}}}return{chain:e,type:l.IdentifierType.Alias,identifier:i,identifierBase:a}},_=(r,t)=>{let e=new URL(r),i=e.searchParams.get(l.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return O(a,t)},ir=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,ar=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},le=r=>{let t=ar(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=le(a);return[i,...s]},Bt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},$t=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},Ot=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};var mt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},sr=r=>{let t=new Set(Object.values(h));if(!r.includes(l.ArgParamsSeparator))return!1;let e=mt(r)[0];return t.has(e)};var yt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=tt(a,e);return[i,D(s,t)]});return Object.fromEntries(n)};var ue=G(require("qr-code-styling"),1);var z=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!_(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=y(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,p=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(p);return U.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=O(t,this.config.defaultChain);if(!e)return null;let n=y(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let c=y(t,this.adapters),o=this.build(c.chainInfo.name,e,n);return new ue.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 or="https://",Wt=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(or))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let g=D(s,{...e.vars,...i});return[{identifier:g,url:Vt(t,g,r)}]}let c=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let g=D(p,{...e.vars,...i}),A=g?`${s}?${g}`:s;return[{identifier:A,url:Vt(t,A,r)}]}let o=c[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let f=Array.isArray(i[d])?i[d]:[i[d]];if(f.length===0)return[];let m=c.filter(g=>g.includes(`{{${d}[]`)).map(g=>{let A=g.match(/\[\](\.[^}]+)?}}/),v=A&&A[1]||"";return{placeholder:g,field:v?v.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(g=>{let A=p;for(let{regex:b,field:V}of m){let x=V?pr(g,V):g;if(x==null)return null;A=A.replace(b,x)}if(A.includes("{{")||A.includes("}}"))return null;let v=A?`${s}?${A}`:s;return{identifier:v,url:Vt(t,v,r)}}).filter(g=>g!==null)},Vt=(r,t,e)=>{let[n,i]=t.split("?"),a=O(n,e.defaultChain)||{chain:l.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=y(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 c=new URL(p);return new URLSearchParams(i).forEach((o,u)=>c.searchParams.set(u,o)),c.toString().replace(/\/\?/,"?")},pr=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var q=class q{static debug(...t){q.isTestEnv||console.debug(...t)}static info(...t){q.isTestEnv||console.info(...t)}static warn(...t){q.isTestEnv||console.warn(...t)}static error(...t){q.isTestEnv||console.error(...t)}};q.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=q;function de(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Ht(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]=Ht(e[n],t[n]):e[n]=t[n]}),e}function fe(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function N(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function J(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=fe(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(l.Position.Payload)){let s=de(n.input.position,i,a);e=Ht(e,s)}else e[i]=a}),e}var ge=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(l.Transform.Prefix))continue;let c=he(p);if(c!==null&&c!==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}},rt=async(r,t,e,n,i,a)=>{let s=(d,f)=>f.reduce((m,W)=>m&&m[W]!==void 0?m[W]:null,d),p=d=>d.length===0?t?.data||t:s(t,d),{stringValues:c,nativeValues:o,output:u}=ge(r,e,p);return{values:{string:c,native:o,mapped:J(n,i)},output:await Ft(r,u,e,n,i,a)}},Ft=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t};return s=cr(s,r,e,n,i),s=await lr(r,s,a.transform?.runner||null),s},cr=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[p,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let o=c.split(".")[1],u=s.findIndex(f=>f.as===o||f.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},lr=async(r,t,e)=>{if(!r.output)return t;let n={...t},i=Object.entries(r.output).filter(([,a])=>a.startsWith(l.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(l.Transform.Prefix.length)}));if(i.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:a,code:s}of i)try{n[a]=await e.run(s,n)}catch(p){C.error(`Transform error for Warp '${r.name}' with output '${a}':`,p),n[a]=null}return n},Ut=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:c,output:o}=ge(r,e,s),u=await Ft(r,o,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:c,mapped:J(n,i)},output:u}},he=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 ur=(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 me(r,t,e,n=5){let i=await bt(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 vt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return me(r,i,e,5)}function At(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function dr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await vt(r,e,n),p=await t(i);return At(r,p,a,s)}function fr(r){let t=new Date(r).getTime();return Date.now()<t}function gr(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"}`)}}async function hr(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 mr(r,t,e){return null}var Dt=require("@x402/core/client"),jt=require("@x402/core/http");async function Lt(r,t,e,n,i){let a=await yr(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(([c,o])=>{s.set(c,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 yr=async(r,t)=>{let e=await Wr(r),i=new jt.x402HTTPClient(new Dt.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 Dt.x402Client,p=await a.wallet.registerX402Handlers(s),c=i.accepts.find(f=>f?.network&&p[f.network]);if(!c?.network)continue;p[c.network]();let o=new jt.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 ${c.network} scheme`),d}catch{continue}return null},Wr=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===h.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===h.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})${l.ArgParamsSeparator}`;let s=a.map(p=>{let[c,o]=this.getTypeAndValue(n[p]);return`(${p}${l.ArgParamsSeparator}${c})${o}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===h.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let o=c.indexOf(l.ArgParamsSeparator),u=c.substring(o+1);return a.startsWith(h.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),p=a.startsWith(h.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(p)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===h.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?h.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):h.Asset+l.ArgParamsSeparator+e.identifier+l.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+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===h.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[h.Option+l.ArgParamsSeparator+a,s||null]}if(n===h.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),c=s.startsWith(h.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(p?p.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[h.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(h.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),p=i.split(l.ArgCompositeSeparator).map((c,o)=>this.stringToNative(`${a[o]}${l.IdentifierParamSeparator}${c}`)[1]);return[n,p]}else if(n.startsWith(h.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(l.ArgListSeparator).forEach(c=>{let o=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,f]=o;p[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${f}`)[1]}}),[n,p]}else{if(n===h.String)return[n,i];if(n===h.Uint8||n===h.Uint16||n===h.Uint32)return[n,Number(i)];if(n===h.Uint64||n===h.Uint128||n===h.Uint256||n===h.Biguint)return[n,BigInt(i||0)];if(n===h.Bool)return[n,i==="true"];if(n===h.Address)return[n,i];if(n===h.Hex)return[n,i];if(n===h.Asset){let[a,s]=i.split(l.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,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[h.Uint32,t]:typeof t=="bigint"?[h.Uint64,t]:typeof t=="boolean"?[h.Bool,t]:[typeof t,t]}};var vr=r=>new w().nativeToString(h.String,r),Ar=r=>new w().nativeToString(h.Uint8,r),Cr=r=>new w().nativeToString(h.Uint16,r),xr=r=>new w().nativeToString(h.Uint32,r),wr=r=>new w().nativeToString(h.Uint64,r),Ir=r=>new w().nativeToString(h.Biguint,r),Sr=r=>new w().nativeToString(h.Bool,r),Pr=r=>new w().nativeToString(h.Address,r),Mt=r=>new w().nativeToString(h.Asset,r),Tr=r=>new w().nativeToString(h.Hex,r),br=(r,t)=>{if(t===null)return h.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return h.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},Er=(...r)=>new w().nativeToString(h.Tuple,r),Rr=r=>new w().nativeToString(h.Struct,r),Nr=r=>new w().nativeToString(h.Vector,r);var ye=G(require("ajv"),1);var zt=class{constructor(t){this.pendingBrand={protocol:Z("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||U.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new ye.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var We=G(require("ajv"),1);var nt=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=$(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,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||U.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new We.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 qt=class{constructor(t){this.config=t;this.pendingWarp={protocol:Z("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 Et(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 nt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
+ `))}};var S=require("fs"),K=require("path");var ve=new w,Ct=(r,t)=>typeof t=="bigint"?ve.nativeToString("biguint",t):t,Q=(r,t)=>typeof t=="string"&&t.startsWith(h.Biguint+":")?ve.stringToNative(t)[1]:t;var xt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,K.resolve)(n):(0,K.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,S.existsSync)(this.cacheDir)||(0,S.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,K.join)(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!(0,S.existsSync)(e))return null;let n=(0,S.readFileSync)(e,"utf-8"),i=JSON.parse(n,Q);return Date.now()>i.expiresAt?((0,S.unlinkSync)(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);(0,S.writeFileSync)(a,JSON.stringify(i,Ct),"utf-8")}forget(t){try{let e=this.getFilePath(t);(0,S.existsSync)(e)&&(0,S.unlinkSync)(e)}catch{}}clear(){try{(0,S.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,S.unlinkSync)((0,K.join)(this.cacheDir,e))})}catch{}}};var it=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,Q);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,Ct))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var j=class j{constructor(t,e){}get(t){let e=j.cache.get(t);return e?Date.now()>e.expiresAt?(j.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;j.cache.set(t,{value:e,expiresAt:i})}forget(t){j.cache.delete(t)}clear(){j.cache.clear()}};j.cache=new Map;var at=j;var Ae=require("fs"),kt=require("path");var wt=class{constructor(t,e){let n=e?.path?(0,kt.resolve)(e.path):(0,kt.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,Ae.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,Q)))}catch(e){return C.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a)}forget(t){this.cache.delete(t)}clear(){this.cache.clear()}};var Gt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},It={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}`},st=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new it(t,e):e?.type==="memory"?new at(t,e):e?.type==="static"?new wt(t,e):e?.type==="filesystem"?new xt(t,e):typeof window<"u"&&window.localStorage?new it(t,e):new at(t,e)}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var ot={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},_t={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Jt=(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)},Qt=r=>{try{return JSON.parse(r)}catch{return null}},Br=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:c,nonce:o,expiresAt:u}=await vt(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(At(n,d,o,u)).forEach(([f,m])=>s.set(f,m))}let p=Jt(e.resolvedInputs,ot.Headers,i);if(p){let c=Qt(p);c&&typeof c=="object"&&Object.entries(c).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([c,o])=>{s.set(c,r.applyInputs(o,e.resolvedInputs,i))});return s},$r=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===_t.Get){let s=Jt(e.resolvedInputs,ot.Queries,i);if(s){let p=Qt(s);if(p&&typeof p=="object"){let c=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&c.searchParams.set(o,String(u))),a=c.toString()}}}return a},Or=(r,t,e,n,i)=>{if(r===_t.Get)return;let a=Jt(t.resolvedInputs,ot.Payload,n);if(a&&Qt(a)!==null)return a;let{[ot.Payload]:s,[ot.Queries]:p,...c}=e;return JSON.stringify({...c,...i})},Ce=async(r,t,e,n,i,a,s,p)=>{let c=t.method||_t.Get,o=await Br(r,t,e,n,a,p),u=$r(r,t,e,c,a),d=Or(c,e,i,a,s);return{url:u,method:c,headers:o,body:d}};var R=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);return await this.applyGlobals(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=I(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(l.Vars.Query+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Query.length+1),[o,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,m=e.queries?.[o]||null||d;m&&a(s,m)}else if(p.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Env.length+1),[o,u]=c.split(l.ArgCompositeSeparator),f={...this.config.vars,...e.envs}?.[o];f&&a(s,f)}else p===l.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(l.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(l.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 D(a,s)}applyGlobalsToText(t){if(!Object.values(l.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(l.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 c=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=y(c,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 c=p;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var k=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 st(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(It.WarpExecutable(t,e||"",n))||[];return N(i)}async createExecutable(t,e,n,i={}){let a=E(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=y(s.name,this.adapters),c=new R(this.config,p,this.adapters),o=await c.apply(t,i),u=E(o,e),{action:d,index:f}=$(o),m=this.getStringTypedInputs(d,n),W=await this.getResolvedInputs(s.name,d,m,c),g=await this.getModifiedInputs(W),A=[],v=[];f===e-1?(A=W,v=g):this.requiresPayloadInputs(u)&&(A=await this.resolveActionInputs(s.name,u,n,c),v=await this.getModifiedInputs(A));let b=v.find(P=>P.input.position==="receiver"||P.input.position==="destination")?.value,V=this.getDestinationFromAction(u),x=b?this.serializer.stringToNative(b)[1]:V;if(x&&(x=c.applyInputs(x,v,this.serializer,g)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let B=this.getPreparedArgs(u,v);B=B.map(P=>c.applyInputs(P,v,this.serializer,g));let H=v.find(P=>P.input.position==="value")?.value||null,T="value"in u?u.value:null,F=H?.split(l.ArgParamsSeparator)[1]||T||"0",X=c.applyInputs(F,v,this.serializer,g),xe=BigInt(X),we=v.filter(P=>P.input.position==="transfer"&&P.value).map(P=>P.value),Ie=[...("transfers"in u?u.transfers:[])||[],...we||[]].map(P=>{let be=c.applyInputs(P,v,this.serializer,g);return this.serializer.stringToNative(be)[1]}),Se=v.find(P=>P.input.position==="data")?.value,Pe="data"in u?u.data||"":null,Zt=Se||Pe||null,Te=Zt?c.applyInputs(Zt,v,this.serializer,g):null,Yt={adapter:p,warp:o,chain:s,action:e,destination:x,args:B,value:xe,transfers:Ie,data:Te,resolvedInputs:v};return this.cache.set(It.WarpExecutable(this.config.env,o.meta?.hash||"",e),Yt.resolvedInputs,Gt.OneWeek),Yt}async getChainInfoForWarp(t,e){if(t.chain)return y(t.chain,this.adapters).chainInfo;if(e){let i=await this.tryGetChainFromInputs(t,e);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,e){let n=t.inputs||[];return e.map((i,a)=>{let s=n[a];return!s||i.includes(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i){let a=e.inputs||[],s=n.map(o=>i.applyInputs(o,[],this.serializer)),p=await Promise.all(s.map(o=>this.preprocessInput(t,o))),c=(o,u)=>{if(o.source===l.Source.UserWallet){let f=I(this.config,t);return f?this.serializer.nativeToString("address",f):null}if(o.source==="hidden"){if(o.default===void 0)return null;let f=i?i.applyInputs(String(o.default),[],this.serializer):String(o.default);return this.serializer.nativeToString(o.type,f)}if(p[u])return p[u];let d=this.url.searchParams.get(o.as||o.name);return d?this.serializer.nativeToString(o.type,d):null};return a.map((o,u)=>{let d=c(o,u),f=o.default!==void 0?i?i.applyInputs(String(o.default),[],this.serializer):String(o.default):void 0;return{input:o,value:d||(f!==void 0?this.serializer.nativeToString(o.type,f):null)}})}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i){let a=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,a,i)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,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 c=Y(p,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=Y(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.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=this.buildInputContext(t,n,i),c=await s.run(a,p);if(c==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:o})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let a=0;a<e;a++){let s=t[a];if(!s.value)continue;let p=s.input.as||s.input.name,[,c]=this.serializer.stringToNative(s.value);if(i[p]=c,s.input.type==="asset"&&typeof c=="object"&&c!==null){let o=c;"identifier"in o&&"amount"in o&&(i[`${p}.token`]=String(o.identifier),i[`${p}.amount`]=String(o.amount),i[`${p}.identifier`]=String(o.identifier))}}if(n&&n.value){let a=n.input.as||n.input.name,[,s]=this.serializer.stringToNative(n.value);if(i[a]=s,n.input.type==="asset"&&typeof s=="object"&&s!==null){let p=s;"identifier"in p&&"amount"in p&&(i[`${a}.token`]=String(p.identifier),i[`${a}.amount`]=String(p.amount),i[`${a}.identifier`]=String(p.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=mt(e),a=y(t,this.adapters);if(n==="asset"){let[s,p,c]=i.split(l.ArgCompositeSeparator);if(c)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=Y(p,o.decimals);return Mt({...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,c]=this.serializer.stringToNative(s),o=c;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(c=>c.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.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 y(s,this.adapters).chainInfo}};var pt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new k(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...Ot(t.meta?.query??null),...n.queries},u={...n,queries:o},{action:d,index:f}=$(t);for(let m=1;m<=t.actions.length;m++){let W=E(t,m);if(!gt(W,t))continue;let{tx:g,chain:A,immediateExecution:v,executable:b}=await this.executeAction(t,m,e,u);g&&i.push(g),A&&(a=A),v&&s.push(v),b&&m===f+1&&b.resolvedInputs&&(p=N(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 m=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(m))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=E(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):St.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==="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=y(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=y(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!gt(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[p],o=p+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),f={status:"error",warp:t,action:o,user:I(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:f})),f}let u=await i.output.getActionExecution(t,o,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:c})):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=I(this.config,t.chain.name),i=E(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:c}=await rt(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,c)}async doHttpRequest(t,e,n,i,a){let s=new R(this.config,y(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:c,method:o,headers:u,body:d}=await Ce(s,e,t,n,i,p,a,async f=>await this.callHandler(()=>this.handlers?.onSignRequest?.(f)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:o,headers:u,body:d});try{let m=await fetch(c,{method:o,headers:u,body:d});C.debug("Collect response status",{status:m.status}),m.status===402&&(m=await Lt(m,c,o,d,this.adapters));let W=await m.json();C.debug("Collect response content",{content:W});let{values:g,output:A}=await rt(t.warp,W,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,I(this.config,t.chain.name),m.ok?"success":"error",g,A,W)}catch(f){C.error("WarpActionExecutor: Error executing collect",f);let m=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=I(this.config,t.chain.name),i=E(t.warp,t.action);if(!i.destination){let m=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let W=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}let p=this.factory.getSerializer(),c=new R(this.config,y(t.chain.name,this.adapters),this.adapters),o=i.destination,u=c.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),f={};o.headers&&Object.entries(o.headers).forEach(([m,W])=>{let g=c.applyInputs(W,t.resolvedInputs,this.factory.getSerializer());f[m]=g}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:f});try{let m=new s(new URL(u),{requestInit:{headers:f}}),W=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await W.connect(m);let g={};t.resolvedInputs.forEach(({input:x,value:B})=>{if(B&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let H=x.position.replace("payload:",""),[T,F]=p.stringToNative(B);if(T==="string")g[H]=String(F);else if(T==="bool")g[H]=!!F;else if(T==="uint8"||T==="uint16"||T==="uint32"||T==="uint64"||T==="uint128"||T==="uint256"||T==="biguint"){let X=Number(F);g[H]=(Number.isInteger(X),X)}else g[H]=F}}),e&&Object.assign(g,e);let A=await W.callTool({name:d,arguments:g});await W.close();let v;if(A.content&&A.content.length>0){let x=A.content[0];if(x.type==="text")try{v=JSON.parse(x.text)}catch{v=x.text}else x.type,v=x}else v=A;let{values:b,output:V}=await rt(t.warp,v,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",b,V,A)}catch(m){C.error("WarpExecutor: Error executing MCP",m);let W=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:m},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}}buildCollectResult(t,e,n,i,a,s){let p=Wt(this.config,this.adapters,t.warp,t.action,a),c=N(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||I(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:yt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}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=y(s.name,this.adapters),c=new R(this.config,p,this.adapters),o=await c.apply(t,a),u=E(o,n),{action:d}=$(o),f=this.factory.getStringTypedInputs(d,i),m=await this.factory.getResolvedInputs(s.name,d,f,c),W=await this.factory.getModifiedInputs(m),g=W;if(e.inputs&&e.inputs.length>0){let H=this.factory.getStringTypedInputs(e,i),T=await this.factory.getResolvedInputs(s.name,e,H,c);g=await this.factory.getModifiedInputs(T)}let A=c.applyInputs(u.prompt,g,this.factory.getSerializer(),W),v=N(g),b=I(this.config,s.name),V=this.factory.getSerializer(),{values:x,output:B}=await Ut(o,A,n,g,V,this.config);return{status:"success",warp:o,action:n,user:b,txHash:null,tx:null,next:Wt(this.config,this.adapters,o,n,B),values:x,output:B,messages:yt(o,B,this.config),destination:null,resolvedInputs:v}}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),c=y(p.name,this.adapters),o=new R(this.config,c,this.adapters),{action:u}=$(t),d=this.factory.getStringTypedInputs(u,n),f=await this.factory.getResolvedInputs(p.name,u,d,o),m=await this.factory.getModifiedInputs(f),W;if(a)W=a;else{let v=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o);W=await this.factory.getModifiedInputs(v)}let g=o.buildInputBag(W,this.factory.getSerializer(),m),A=Rt(e.when,g);return Nt(A)}};var ct=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 lt=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!_(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,c=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?_(t,this.config.defaultChain):O(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,c=null,o=null,u=y(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?Bt(t):$t(i.identifier);if(a==="hash"){p=await u.builder().createFromTransactionHash(s,e);let g=await u.registry.getInfoByHash(s,e);c=g.registryInfo,o=g.brand}else if(a==="alias"){let g=await u.registry.getInfoByAlias(s,e);c=g.registryInfo,o=g.brand,g.registryInfo&&(p=await u.builder().createFromTransactionHash(g.registryInfo.hash,e))}if(p&&p.meta&&(Vr(p,u.chainInfo.name,c,i.identifier),p.meta.query=d),!p)return n;let f=p.chain||u.chainInfo.name,m=y(f,this.adapters),W=await new R(this.config,m,this.adapters).apply(p);return{match:!0,url:t,warp:W,chain:f,registryInfo:c,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},Vr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?ht(t,"alias",e.alias):ht(t,"hash",e?.hash??n))};var Kt=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new pt(this.config,this.chains,t)}async detectWarp(t,e){return new lt(this.config,this.chains).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 W=await fetch(t);if(!W.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await W.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:f}=await c.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async W=>{await c.evaluateOutput(p,W)},resolvedInputs:f}}async createInscriptionTransaction(t,e){return await y(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return y(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=O(t,this.config.defaultChain);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return y(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!I(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return y(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return y(t,this.chains).explorer}getOutput(t){return y(t,this.chains).output}async getRegistry(t){let e=y(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return y(t,this.chains).dataLoader}getWallet(t){return y(t,this.chains).wallet}get factory(){return new k(this.config,this.chains)}get index(){return new ct(this.config)}get linkBuilder(){return new z(this.config,this.chains)}createBuilder(t){return y(t,this.chains).builder()}createAbiBuilder(t){return y(t,this.chains).abiBuilder()}createBrandBuilder(t){return y(t,this.chains).brandBuilder()}createSerializer(t){return y(t,this.chains).serializer}resolveText(t){return tt(t,this.config)}};var Xt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,EvmWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var ke=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},le=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>le(r.user?.wallets?.[t]||null),ue=r=>r?typeof r=="string"?r:r.privateKey||null:null,de=r=>r?typeof r=="string"?r:r.mnemonic||null:null,fe=r=>r?typeof r=="string"?r:r.externalId||null:null,Ge=(r,t)=>ue(r.user?.wallets?.[t]||null)?.trim()||null,_e=(r,t)=>de(r.user?.wallets?.[t]||null)?.trim()||null,ge=(r,t)=>fe(r.user?.wallets?.[t]||null)?.trim()||null,Je=(r,t)=>{let e=ge(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Qe=r=>typeof r=="string",Ke=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},he=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},me=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},Xe=(r,t=24)=>{let e=he(r);return me(e,t),e};var ye=(d=>(d.Multiversx="multiversx",d.Vibechain="vibechain",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(ye||{}),tr=["ethereum","base","arbitrum","polygon","somnia"],l={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"}},g={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},Et=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},U={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",l.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 ir=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var or=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var cr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},lr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},ur=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var ut=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}},dt=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},D=null;function Rt(){if(D)return D;if(typeof window<"u"&&window.crypto)return D=new ut,D;if(typeof process<"u"&&process.versions?.node)return D=new dt,D;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function fr(r){D=r}async function Nt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Rt()).getRandomBytes(r)}function We(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 Bt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Nt(r/2,t);return We(e)}async function hr(){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 Nt(16),r.randomBytes=!0}catch{}return r}function mr(){return Rt()}var vr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.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},Z=r=>{if(r==="warp")return`warp:${M.Warp}`;if(r==="brand")return`brand:${M.Brand}`;if(r==="abi")return`abi:${M.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},T=(r,t)=>r?.actions[t-1],N=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","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}},ft=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=N(t);return r===e}return!0},Y=(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)},$t=(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)=>t[n]||""),Ot=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Ht=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"},tt=(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 et=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,Er=(r,t)=>!r||!t?!1:et(r)===et(t),gt=(r,t,e)=>{let n=et(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},B=(r,t)=>{let e=t||l.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=et(n),a=i.split("?")[0],s=Vt(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:l.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,c,o]=s;if(c===l.IdentifierType.Alias||c===l.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:c,identifier:u,identifierBase:o}}}if(s.length===2){let[p,c]=s;if(p===l.IdentifierType.Alias||p===l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c;return{chain:e,type:p,identifier:o,identifierBase:c}}}if(s.length===2){let[p,c]=s;if(p!==l.IdentifierType.Alias&&p!==l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c,u=ve(c,p)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:c}}}return{chain:e,type:l.IdentifierType.Alias,identifier:i,identifierBase:a}},_=(r,t)=>{let e=new URL(r),i=e.searchParams.get(l.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return B(a,t)},ve=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Ae=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Vt=r=>{let t=Ae(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Vt(a);return[i,...s]},Ft=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},Ut=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null};var ht=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Br=r=>{let t=new Set(Object.values(g));if(!r.includes(l.ArgParamsSeparator))return!1;let e=ht(r)[0];return t.has(e)};var mt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=tt(a,e);return[i,j(s,t)]});return Object.fromEntries(n)};import Ce from"qr-code-styling";var z=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!_(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,p=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(p);return U.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=B(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 c=W(t,this.adapters),o=this.build(c.chainInfo.name,e,n);return new Ce({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 xe="https://",Wt=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(xe))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=j(s,{...e.vars,...i});return[{identifier:f,url:yt(t,f,r)}]}let c=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=j(p,{...e.vars,...i}),A=f?`${s}?${f}`:s;return[{identifier:A,url:yt(t,A,r)}]}let o=c[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let m=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let A=f.match(/\[\](\.[^}]+)?}}/),v=A&&A[1]||"";return{placeholder:f,field:v?v.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let A=p;for(let{regex:$,field:O}of m){let x=O?we(f,O):f;if(x==null)return null;A=A.replace($,x)}if(A.includes("{{")||A.includes("}}"))return null;let v=A?`${s}?${A}`:s;return{identifier:v,url:yt(t,v,r)}}).filter(f=>f!==null)},yt=(r,t,e)=>{let[n,i]=t.split("?"),a=B(n,e.defaultChain)||{chain:l.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 c=new URL(p);return new URLSearchParams(i).forEach((o,u)=>c.searchParams.set(u,o)),c.toString().replace(/\/\?/,"?")},we=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var L=class L{static debug(...t){L.isTestEnv||console.debug(...t)}static info(...t){L.isTestEnv||console.info(...t)}static warn(...t){L.isTestEnv||console.warn(...t)}static error(...t){L.isTestEnv||console.error(...t)}};L.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=L;function Ie(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Dt(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]=Dt(e[n],t[n]):e[n]=t[n]}),e}function Se(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function R(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=Se(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(l.Position.Payload)){let s=Ie(n.input.position,i,a);e=Dt(e,s)}else e[i]=a}),e}var jt=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(l.Transform.Prefix))continue;let c=be(p);if(c!==null&&c!==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}},rt=async(r,t,e,n,i,a)=>{let s=(d,h)=>h.reduce((m,y)=>m&&m[y]!==void 0?m[y]:null,d),p=d=>d.length===0?t?.data||t:s(t,d),{stringValues:c,nativeValues:o,output:u}=jt(r,e,p);return{values:{string:c,native:o,mapped:J(n,i)},output:await Lt(r,u,e,n,i,a)}},Lt=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t};return s=Pe(s,r,e,n,i),s=await Te(r,s,a.transform?.runner||null),s},Pe=(r,t,e,n,i)=>{let a={...r},s=T(t,e)?.inputs||[];for(let[p,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let o=c.split(".")[1],u=s.findIndex(h=>h.as===o||h.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Te=async(r,t,e)=>{if(!r.output)return t;let n={...t},i=Object.entries(r.output).filter(([,a])=>a.startsWith(l.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(l.Transform.Prefix.length)}));if(i.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:a,code:s}of i)try{n[a]=await e.run(s,n)}catch(p){C.error(`Transform error for Warp '${r.name}' with output '${a}':`,p),n[a]=null}return n},Mt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:c,output:o}=jt(r,e,s),u=await Lt(r,o,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:c,mapped:J(n,i)},output:u}},be=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 an=(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 Ee(r,t,e,n=5){let i=await Bt(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 vt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Ee(r,i,e,5)}function At(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function cn(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await vt(r,e,n),p=await t(i);return At(r,p,a,s)}function ln(r){let t=new Date(r).getTime();return Date.now()<t}function un(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"}`)}}async function fn(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 hn(r,t,e){return null}import{x402Client as zt}from"@x402/core/client";import{x402HTTPClient as qt}from"@x402/core/http";async function kt(r,t,e,n,i){let a=await Re(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(([c,o])=>{s.set(c,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 Re=async(r,t)=>{let e=await Ne(r),i=new qt(new zt).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 zt,p=await a.wallet.registerX402Handlers(s),c=i.accepts.find(h=>h?.network&&p[h.network]);if(!c?.network)continue;p[c.network]();let o=new qt(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 ${c.network} scheme`),d}catch{continue}return null},Ne=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===g.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===g.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${l.ArgParamsSeparator}`;let s=a.map(p=>{let[c,o]=this.getTypeAndValue(n[p]);return`(${p}${l.ArgParamsSeparator}${c})${o}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===g.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let o=c.indexOf(l.ArgParamsSeparator),u=c.substring(o+1);return a.startsWith(g.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),p=a.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(p)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===g.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?g.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):g.Asset+l.ArgParamsSeparator+e.identifier+l.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+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===g.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[g.Option+l.ArgParamsSeparator+a,s||null]}if(n===g.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),c=s.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(p?p.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[g.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(g.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),p=i.split(l.ArgCompositeSeparator).map((c,o)=>this.stringToNative(`${a[o]}${l.IdentifierParamSeparator}${c}`)[1]);return[n,p]}else if(n.startsWith(g.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(l.ArgListSeparator).forEach(c=>{let o=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[1]}}),[n,p]}else{if(n===g.String)return[n,i];if(n===g.Uint8||n===g.Uint16||n===g.Uint32)return[n,Number(i)];if(n===g.Uint64||n===g.Uint128||n===g.Uint256||n===g.Biguint)return[n,BigInt(i||0)];if(n===g.Bool)return[n,i==="true"];if(n===g.Address)return[n,i];if(n===g.Hex)return[n,i];if(n===g.Asset){let[a,s]=i.split(l.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,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[g.Uint32,t]:typeof t=="bigint"?[g.Uint64,t]:typeof t=="boolean"?[g.Bool,t]:[typeof t,t]}};var Sn=r=>new w().nativeToString(g.String,r),Pn=r=>new w().nativeToString(g.Uint8,r),Tn=r=>new w().nativeToString(g.Uint16,r),bn=r=>new w().nativeToString(g.Uint32,r),En=r=>new w().nativeToString(g.Uint64,r),Rn=r=>new w().nativeToString(g.Biguint,r),Nn=r=>new w().nativeToString(g.Bool,r),Bn=r=>new w().nativeToString(g.Address,r),Gt=r=>new w().nativeToString(g.Asset,r),$n=r=>new w().nativeToString(g.Hex,r),On=(r,t)=>{if(t===null)return g.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return g.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},Hn=(...r)=>new w().nativeToString(g.Tuple,r),Vn=r=>new w().nativeToString(g.Struct,r),Fn=r=>new w().nativeToString(g.Vector,r);import Be from"ajv";var _t=class{constructor(t){this.pendingBrand={protocol:Z("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||U.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new Be,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import $e from"ajv";var nt=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=N(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,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||U.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new $e({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 Jt=class{constructor(t){this.config=t;this.pendingWarp={protocol:Z("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 $t(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 nt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
- `))}};import{existsSync as Ct,mkdirSync as Oe,readdirSync as He,readFileSync as Ve,unlinkSync as xt,writeFileSync as Fe}from"fs";import{join as Kt,resolve as Xt}from"path";var Qt=new w,it=(r,t)=>typeof t=="bigint"?Qt.nativeToString("biguint",t):t,q=(r,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?Qt.stringToNative(t)[1]:t;var at=class{constructor(t,e){let n=e?.path;this.cacheDir=n?Xt(n):Xt(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){Ct(this.cacheDir)||Oe(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return Kt(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!Ct(e))return null;let n=Ve(e,"utf-8"),i=JSON.parse(n,q);return Date.now()>i.expiresAt?(xt(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);Fe(a,JSON.stringify(i,it),"utf-8")}forget(t){try{let e=this.getFilePath(t);Ct(e)&&xt(e)}catch{}}clear(){try{He(this.cacheDir).forEach(e=>{e.endsWith(".json")&&xt(Kt(this.cacheDir,e))})}catch{}}};var Q=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,q);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,it))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var F=class F{constructor(t,e){}get(t){let e=F.cache.get(t);return e?Date.now()>e.expiresAt?(F.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;F.cache.set(t,{value:e,expiresAt:i})}forget(t){F.cache.delete(t)}clear(){F.cache.clear()}};F.cache=new Map;var K=F;import{readFileSync as Ue}from"fs";import{resolve as Zt}from"path";var st=class{constructor(t,e){let n=e?.path?Zt(e.path):Zt(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=Ue(t,"utf-8");return new Map(Object.entries(JSON.parse(e,q)))}catch(e){return C.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a)}forget(t){this.cache.delete(t)}clear(){this.cache.clear()}};var Yt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},wt={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`},ot=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new Q(t,e):e?.type==="memory"?new K(t,e):e?.type==="static"?new st(t,e):e?.type==="filesystem"?new at(t,e):typeof window<"u"&&window.localStorage?new Q(t,e):new K(t,e)}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var X={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},It={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},St=(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)},Pt=r=>{try{return JSON.parse(r)}catch{return null}},De=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:c,nonce:o,expiresAt:u}=await vt(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(At(n,d,o,u)).forEach(([h,m])=>s.set(h,m))}let p=St(e.resolvedInputs,X.Headers,i);if(p){let c=Pt(p);c&&typeof c=="object"&&Object.entries(c).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([c,o])=>{s.set(c,r.applyInputs(o,e.resolvedInputs,i))});return s},je=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===It.Get){let s=St(e.resolvedInputs,X.Queries,i);if(s){let p=Pt(s);if(p&&typeof p=="object"){let c=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&c.searchParams.set(o,String(u))),a=c.toString()}}}return a},Le=(r,t,e,n,i)=>{if(r===It.Get)return;let a=St(t.resolvedInputs,X.Payload,n);if(a&&Pt(a)!==null)return a;let{[X.Payload]:s,[X.Queries]:p,...c}=e;return JSON.stringify({...c,...i})},te=async(r,t,e,n,i,a,s,p)=>{let c=t.method||It.Get,o=await De(r,t,e,n,a,p),u=je(r,t,e,c,a),d=Le(c,e,i,a,s);return{url:u,method:c,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);return await this.applyGlobals(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),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(l.Vars.Query+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Query.length+1),[o,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,m=e.queries?.[o]||null||d;m&&a(s,m)}else if(p.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Env.length+1),[o,u]=c.split(l.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h&&a(s,h)}else p===l.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(l.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(l.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(l.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(l.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 c=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(c,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 c=p;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var k=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 ot(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(wt.WarpExecutable(t,e||"",n))||[];return R(i)}async createExecutable(t,e,n,i={}){let a=T(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=W(s.name,this.adapters),c=new b(this.config,p,this.adapters),o=await c.apply(t,i),u=T(o,e),{action:d,index:h}=N(o),m=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(s.name,d,m,c),f=await this.getModifiedInputs(y),A=[],v=[];h===e-1?(A=y,v=f):this.requiresPayloadInputs(u)&&(A=await this.resolveActionInputs(s.name,u,n,c),v=await this.getModifiedInputs(A));let $=v.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,O=this.getDestinationFromAction(u),x=$?this.serializer.stringToNative($)[1]:O;if(x&&(x=c.applyInputs(x,v,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let E=this.getPreparedArgs(u,v);E=E.map(I=>c.applyInputs(I,v,this.serializer,f));let H=v.find(I=>I.input.position==="value")?.value||null,P="value"in u?u.value:null,V=H?.split(l.ArgParamsSeparator)[1]||P||"0",G=c.applyInputs(V,v,this.serializer,f),ne=BigInt(G),ie=v.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),ae=[...("transfers"in u?u.transfers:[])||[],...ie||[]].map(I=>{let ce=c.applyInputs(I,v,this.serializer,f);return this.serializer.stringToNative(ce)[1]}),se=v.find(I=>I.input.position==="data")?.value,oe="data"in u?u.data||"":null,Tt=se||oe||null,pe=Tt?c.applyInputs(Tt,v,this.serializer,f):null,bt={adapter:p,warp:o,chain:s,action:e,destination:x,args:E,value:ne,transfers:ae,data:pe,resolvedInputs:v};return this.cache.set(wt.WarpExecutable(this.config.env,o.meta?.hash||"",e),bt.resolvedInputs,Yt.OneWeek),bt}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(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i){let a=e.inputs||[],s=n.map(o=>i.applyInputs(o,[],this.serializer)),p=await Promise.all(s.map(o=>this.preprocessInput(t,o))),c=(o,u)=>{if(o.source==="query"){let d=this.url.searchParams.get(o.name);return d?this.serializer.nativeToString(o.type,d):null}else if(o.source===l.Source.UserWallet){let d=S(this.config,t);return d?this.serializer.nativeToString("address",d):null}else if(o.source==="hidden"){if(o.default===void 0)return null;let d=i?i.applyInputs(String(o.default),[],this.serializer):String(o.default);return this.serializer.nativeToString(o.type,d)}else return p[u]||null};return a.map((o,u)=>{let d=c(o,u),h=o.default!==void 0?i?i.applyInputs(String(o.default),[],this.serializer):String(o.default):void 0;return{input:o,value:d||(h!==void 0?this.serializer.nativeToString(o.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){let a=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,a,i)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,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 c=Y(p,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=Y(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.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=this.buildInputContext(t,n,i),c=await s.run(a,p);if(c==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:o})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let a=0;a<e;a++){let s=t[a];if(!s.value)continue;let p=s.input.as||s.input.name,[,c]=this.serializer.stringToNative(s.value);if(i[p]=c,s.input.type==="asset"&&typeof c=="object"&&c!==null){let o=c;"identifier"in o&&"amount"in o&&(i[`${p}.token`]=String(o.identifier),i[`${p}.amount`]=String(o.amount),i[`${p}.identifier`]=String(o.identifier))}}if(n&&n.value){let a=n.input.as||n.input.name,[,s]=this.serializer.stringToNative(n.value);if(i[a]=s,n.input.type==="asset"&&typeof s=="object"&&s!==null){let p=s;"identifier"in p&&"amount"in p&&(i[`${a}.token`]=String(p.identifier),i[`${a}.amount`]=String(p.amount),i[`${a}.identifier`]=String(p.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=ht(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,c]=i.split(l.ArgCompositeSeparator);if(c)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=Y(p,o.decimals);return Gt({...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,c]=this.serializer.stringToNative(s),o=c;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(c=>c.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.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 pt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new k(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],{action:c,index:o}=N(t);for(let u=1;u<=t.actions.length;u++){let d=T(t,u);if(!ft(d,t))continue;let{tx:h,chain:m,immediateExecution:y,executable:f}=await this.executeAction(t,u,e,n);h&&i.push(h),m&&(a=m),y&&s.push(y),f&&u===o+1&&f.resolvedInputs&&(p=R(f.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 u=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=T(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Et.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==="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(!ft(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[p],o=p+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:c})):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=T(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:c}=await rt(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,c)}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:c,method:o,headers:u,body:d}=await te(s,e,t,n,i,p,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:o,headers:u,body:d});try{let m=await fetch(c,{method:o,headers:u,body:d});C.debug("Collect response status",{status:m.status}),m.status===402&&(m=await kt(m,c,o,d,this.adapters));let y=await m.json();C.debug("Collect response content",{content:y});let{values:f,output:A}=await rt(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),m.ok?"success":"error",f,A,y)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let m=R(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=S(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let m=R(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let y=R(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:y}}let p=this.factory.getSerializer(),c=new b(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,u=c.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([m,y])=>{let f=c.applyInputs(y,t.resolvedInputs,this.factory.getSerializer());h[m]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let m=new s(new URL(u),{requestInit:{headers:h}}),y=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(m);let f={};t.resolvedInputs.forEach(({input:x,value:E})=>{if(E&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let H=x.position.replace("payload:",""),[P,V]=p.stringToNative(E);if(P==="string")f[H]=String(V);else if(P==="bool")f[H]=!!V;else if(P==="uint8"||P==="uint16"||P==="uint32"||P==="uint64"||P==="uint128"||P==="uint256"||P==="biguint"){let G=Number(V);f[H]=(Number.isInteger(G),G)}else f[H]=V}}),e&&Object.assign(f,e);let A=await y.callTool({name:d,arguments:f});await y.close();let v;if(A.content&&A.content.length>0){let x=A.content[0];if(x.type==="text")try{v=JSON.parse(x.text)}catch{v=x.text}else x.type,v=x}else v=A;let{values:$,output:O}=await rt(t.warp,v,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",$,O,A)}catch(m){C.error("WarpExecutor: Error executing MCP",m);let y=R(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:m},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:y}}}buildCollectResult(t,e,n,i,a,s){let p=Wt(this.config,this.adapters,t.warp,t.action,a),c=R(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:mt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}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),c=new b(this.config,p,this.adapters),o=await c.apply(t,a),u=T(o,n),{action:d}=N(o),h=this.factory.getStringTypedInputs(d,i),m=await this.factory.getResolvedInputs(s.name,d,h,c),y=await this.factory.getModifiedInputs(m),f=y;if(e.inputs&&e.inputs.length>0){let H=this.factory.getStringTypedInputs(e,i),P=await this.factory.getResolvedInputs(s.name,e,H,c);f=await this.factory.getModifiedInputs(P)}let A=c.applyInputs(u.prompt,f,this.factory.getSerializer(),y),v=R(f),$=S(this.config,s.name),O=this.factory.getSerializer(),{values:x,output:E}=await Mt(o,A,n,f,O,this.config);return{status:"success",warp:o,action:n,user:$,txHash:null,tx:null,next:Wt(this.config,this.adapters,o,n,E),values:x,output:E,messages:mt(o,E,this.config),destination:null,resolvedInputs:v}}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),c=W(p.name,this.adapters),o=new b(this.config,c,this.adapters),{action:u}=N(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(p.name,u,d,o),m=await this.factory.getModifiedInputs(h),y;if(a)y=a;else{let v=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o);y=await this.factory.getModifiedInputs(v)}let f=o.buildInputBag(y,this.factory.getSerializer(),m),A=Ot(e.when,f);return Ht(A)}};var ct=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 lt=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!_(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,c=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?_(t,this.config.defaultChain):B(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,c=null,o=null,u=W(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?Ft(t):Ut(i.identifier);if(a==="hash"){p=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,o=f.brand,f.registryInfo&&(p=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(p&&p.meta&&(Me(p,u.chainInfo.name,c,i.identifier),p.meta.query=d),!p)return n;let h=p.chain||u.chainInfo.name,m=W(h,this.adapters),y=await new b(this.config,m,this.adapters).apply(p);return{match:!0,url:t,warp:y,chain:h,registryInfo:c,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},Me=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?gt(t,"alias",e.alias):gt(t,"hash",e?.hash??n))};var ee=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new pt(this.config,this.chains,t)}async detectWarp(t,e){return new lt(this.config,this.chains).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 y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await y.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await c.evaluateOutput(p,y)},resolvedInputs:h}}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=B(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 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 k(this.config,this.chains)}get index(){return new ct(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 tt(t,this.config)}};var re=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{ut as BrowserCryptoProvider,Yt as CacheTtl,tr as EvmWalletChainNames,dt as NodeCryptoProvider,wr as WARP_LANGUAGES,_t as WarpBrandBuilder,Jt as WarpBuilder,ot as WarpCache,wt as WarpCacheKey,ye as WarpChainName,ee as WarpClient,U as WarpConfig,l as WarpConstants,pt as WarpExecutor,k as WarpFactory,ct as WarpIndex,g as WarpInputTypes,b as WarpInterpolator,z as WarpLinkBuilder,lt as WarpLinkDetecter,C as WarpLogger,M as WarpProtocolVersions,w as WarpSerializer,re as WarpTypeRegistry,nt as WarpValidator,Bn as address,mt as applyOutputToMessages,Gt as asset,Rn as biguint,Nn as bool,J as buildMappedOutput,Ie as buildNestedPayload,gr as bytesToBase64,We as bytesToHex,et as cleanWarpIdentifier,At as createAuthHeaders,vt as createAuthMessage,mr as createCryptoProvider,hn as createDefaultWalletProvider,cn as createHttpAuthHeaders,Ee as createSignableMessage,Sr as createWarpI18nText,gt as createWarpIdentifier,Lt as evaluateOutputCommon,Ht as evaluateWhenCondition,rt as extractCollectOutput,_ as extractIdentifierInfoFromUrl,Mt as extractPromptOutput,Ut as extractQueryStringFromIdentifier,Ft as extractQueryStringFromUrl,R as extractResolvedInputValues,vr as extractWarpSecrets,W as findWarpAdapterForChain,Rt as getCryptoProvider,or as getEventNameFromWarp,Z as getLatestProtocolIdentifier,Wt as getNextInfo,an as getProviderConfig,Nt as getRandomBytes,Bt as getRandomHex,ke as getWalletFromConfigOrFail,T as getWarpActionByIndex,cr as getWarpBrandLogoUrl,lr as getWarpChainAssetLogoUrl,ur as getWarpChainInfoLogoUrl,B as getWarpInfoFromIdentifier,N as getWarpPrimaryAction,le as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,fe as getWarpWalletExternalId,ge as getWarpWalletExternalIdFromConfig,Je as getWarpWalletExternalIdFromConfigOrFail,de as getWarpWalletMnemonic,_e as getWarpWalletMnemonicFromConfig,ue as getWarpWalletPrivateKey,Ge as getWarpWalletPrivateKeyFromConfig,kt as handleX402Payment,Br as hasInputPrefix,$n as hex,fn as initializeWalletCache,Er as isEqualWarpIdentifier,ft as isWarpActionAutoExecute,Ir as isWarpI18nText,Qe as isWarpWalletReadOnly,Dt as mergeNestedPayload,Xe as normalizeAndValidateMnemonic,he as normalizeMnemonic,On as option,be as parseOutputOutIndex,un as parseSignedMessage,j as replacePlaceholders,Ot as replacePlaceholdersInWhenExpression,tt as resolveWarpText,Et as safeWindow,fr as setCryptoProvider,Ke as setWarpWalletInConfig,Y as shiftBigintBy,ht as splitInput,Sn as string,Vn as struct,hr as testCryptoAvailability,Se as toInputPayloadValue,$t as toPreviewText,Hn as tuple,Tn as uint16,bn as uint32,En as uint64,Pn as uint8,me as validateMnemonicLength,ln as validateSignedMessage,Fn as vector,ir as withAdapterFallback};
1
+ var Ge=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},ue=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>ue(r.user?.wallets?.[t]||null),de=r=>r?typeof r=="string"?r:r.privateKey||null:null,fe=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ge=r=>r?typeof r=="string"?r:r.externalId||null:null,_e=(r,t)=>de(r.user?.wallets?.[t]||null)?.trim()||null,Je=(r,t)=>fe(r.user?.wallets?.[t]||null)?.trim()||null,he=(r,t)=>ge(r.user?.wallets?.[t]||null)?.trim()||null,Qe=(r,t)=>{let e=he(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Ke=r=>typeof r=="string",Xe=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},me=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},ye=(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`)},Ze=(r,t=24)=>{let e=me(r);return ye(e,t),e};var We=(d=>(d.Multiversx="multiversx",d.Vibechain="vibechain",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(We||{}),er=["ethereum","base","arbitrum","polygon","somnia"],l={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"}},h={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"},Et=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},U={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",l.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 ar=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var pr=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var lr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},ur=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},dr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var ut=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}},dt=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},D=null;function Rt(){if(D)return D;if(typeof window<"u"&&window.crypto)return D=new ut,D;if(typeof process<"u"&&process.versions?.node)return D=new dt,D;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function gr(r){D=r}async function Nt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Rt()).getRandomBytes(r)}function ve(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function hr(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 Bt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Nt(r/2,t);return ve(e)}async function mr(){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 Nt(16),r.randomBytes=!0}catch{}return r}function yr(){return Rt()}var Ar=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.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},Z=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],B=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","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}},ft=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=B(t);return r===e}return!0},Y=(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)},$t=(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)=>t[n]||""),Ot=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Vt=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"},tt=(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 et=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,Rr=(r,t)=>!r||!t?!1:et(r)===et(t),gt=(r,t,e)=>{let n=et(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},$=(r,t)=>{let e=t||l.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=et(n),a=i.split("?")[0],s=Ht(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:l.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,c,o]=s;if(c===l.IdentifierType.Alias||c===l.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:c,identifier:u,identifierBase:o}}}if(s.length===2){let[p,c]=s;if(p===l.IdentifierType.Alias||p===l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c;return{chain:e,type:p,identifier:o,identifierBase:c}}}if(s.length===2){let[p,c]=s;if(p!==l.IdentifierType.Alias&&p!==l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c,u=Ae(c,p)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:c}}}return{chain:e,type:l.IdentifierType.Alias,identifier:i,identifierBase:a}},_=(r,t)=>{let e=new URL(r),i=e.searchParams.get(l.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return $(a,t)},Ae=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Ce=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Ht=r=>{let t=Ce(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Ht(a);return[i,...s]},Ft=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},Ut=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},Dt=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};var ht=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},$r=r=>{let t=new Set(Object.values(h));if(!r.includes(l.ArgParamsSeparator))return!1;let e=ht(r)[0];return t.has(e)};var mt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=tt(a,e);return[i,j(s,t)]});return Object.fromEntries(n)};import xe from"qr-code-styling";var z=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!_(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,p=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(p);return U.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=$(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 c=W(t,this.adapters),o=this.build(c.chainInfo.name,e,n);return new xe({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 we="https://",Wt=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(we))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let g=j(s,{...e.vars,...i});return[{identifier:g,url:yt(t,g,r)}]}let c=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let g=j(p,{...e.vars,...i}),A=g?`${s}?${g}`:s;return[{identifier:A,url:yt(t,A,r)}]}let o=c[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let f=Array.isArray(i[d])?i[d]:[i[d]];if(f.length===0)return[];let m=c.filter(g=>g.includes(`{{${d}[]`)).map(g=>{let A=g.match(/\[\](\.[^}]+)?}}/),v=A&&A[1]||"";return{placeholder:g,field:v?v.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(g=>{let A=p;for(let{regex:T,field:O}of m){let x=O?Ie(g,O):g;if(x==null)return null;A=A.replace(T,x)}if(A.includes("{{")||A.includes("}}"))return null;let v=A?`${s}?${A}`:s;return{identifier:v,url:yt(t,v,r)}}).filter(g=>g!==null)},yt=(r,t,e)=>{let[n,i]=t.split("?"),a=$(n,e.defaultChain)||{chain:l.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 c=new URL(p);return new URLSearchParams(i).forEach((o,u)=>c.searchParams.set(u,o)),c.toString().replace(/\/\?/,"?")},Ie=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var L=class L{static debug(...t){L.isTestEnv||console.debug(...t)}static info(...t){L.isTestEnv||console.info(...t)}static warn(...t){L.isTestEnv||console.warn(...t)}static error(...t){L.isTestEnv||console.error(...t)}};L.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=L;function Se(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function jt(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=jt(e[n],t[n]):e[n]=t[n]}),e}function 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 N(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(l.Position.Payload)){let s=Se(n.input.position,i,a);e=jt(e,s)}else e[i]=a}),e}var Lt=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(l.Transform.Prefix))continue;let c=Ee(p);if(c!==null&&c!==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}},rt=async(r,t,e,n,i,a)=>{let s=(d,f)=>f.reduce((m,y)=>m&&m[y]!==void 0?m[y]:null,d),p=d=>d.length===0?t?.data||t:s(t,d),{stringValues:c,nativeValues:o,output:u}=Lt(r,e,p);return{values:{string:c,native:o,mapped:J(n,i)},output:await Mt(r,u,e,n,i,a)}},Mt=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t};return s=Te(s,r,e,n,i),s=await be(r,s,a.transform?.runner||null),s},Te=(r,t,e,n,i)=>{let a={...r},s=b(t,e)?.inputs||[];for(let[p,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let o=c.split(".")[1],u=s.findIndex(f=>f.as===o||f.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},be=async(r,t,e)=>{if(!r.output)return t;let n={...t},i=Object.entries(r.output).filter(([,a])=>a.startsWith(l.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(l.Transform.Prefix.length)}));if(i.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:a,code:s}of i)try{n[a]=await e.run(s,n)}catch(p){C.error(`Transform error for Warp '${r.name}' with output '${a}':`,p),n[a]=null}return n},zt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:c,output:o}=Lt(r,e,s),u=await Mt(r,o,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:c,mapped:J(n,i)},output:u}},Ee=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 sn=(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 Bt(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 vt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Re(r,i,e,5)}function At(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function ln(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await vt(r,e,n),p=await t(i);return At(r,p,a,s)}function un(r){let t=new Date(r).getTime();return Date.now()<t}function dn(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"}`)}}async function gn(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 mn(r,t,e){return null}import{x402Client as qt}from"@x402/core/client";import{x402HTTPClient as kt}from"@x402/core/http";async function Gt(r,t,e,n,i){let a=await Ne(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(([c,o])=>{s.set(c,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 Ne=async(r,t)=>{let e=await Be(r),i=new kt(new qt).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,p=await a.wallet.registerX402Handlers(s),c=i.accepts.find(f=>f?.network&&p[f.network]);if(!c?.network)continue;p[c.network]();let o=new kt(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 ${c.network} scheme`),d}catch{continue}return null},Be=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===h.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===h.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})${l.ArgParamsSeparator}`;let s=a.map(p=>{let[c,o]=this.getTypeAndValue(n[p]);return`(${p}${l.ArgParamsSeparator}${c})${o}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===h.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let o=c.indexOf(l.ArgParamsSeparator),u=c.substring(o+1);return a.startsWith(h.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),p=a.startsWith(h.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(p)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===h.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?h.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):h.Asset+l.ArgParamsSeparator+e.identifier+l.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+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===h.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[h.Option+l.ArgParamsSeparator+a,s||null]}if(n===h.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),c=s.startsWith(h.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(p?p.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[h.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(h.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),p=i.split(l.ArgCompositeSeparator).map((c,o)=>this.stringToNative(`${a[o]}${l.IdentifierParamSeparator}${c}`)[1]);return[n,p]}else if(n.startsWith(h.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(l.ArgListSeparator).forEach(c=>{let o=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,f]=o;p[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${f}`)[1]}}),[n,p]}else{if(n===h.String)return[n,i];if(n===h.Uint8||n===h.Uint16||n===h.Uint32)return[n,Number(i)];if(n===h.Uint64||n===h.Uint128||n===h.Uint256||n===h.Biguint)return[n,BigInt(i||0)];if(n===h.Bool)return[n,i==="true"];if(n===h.Address)return[n,i];if(n===h.Hex)return[n,i];if(n===h.Asset){let[a,s]=i.split(l.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,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[h.Uint32,t]:typeof t=="bigint"?[h.Uint64,t]:typeof t=="boolean"?[h.Bool,t]:[typeof t,t]}};var Pn=r=>new w().nativeToString(h.String,r),Tn=r=>new w().nativeToString(h.Uint8,r),bn=r=>new w().nativeToString(h.Uint16,r),En=r=>new w().nativeToString(h.Uint32,r),Rn=r=>new w().nativeToString(h.Uint64,r),Nn=r=>new w().nativeToString(h.Biguint,r),Bn=r=>new w().nativeToString(h.Bool,r),$n=r=>new w().nativeToString(h.Address,r),_t=r=>new w().nativeToString(h.Asset,r),On=r=>new w().nativeToString(h.Hex,r),Vn=(r,t)=>{if(t===null)return h.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return h.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},Hn=(...r)=>new w().nativeToString(h.Tuple,r),Fn=r=>new w().nativeToString(h.Struct,r),Un=r=>new w().nativeToString(h.Vector,r);import $e from"ajv";var Jt=class{constructor(t){this.pendingBrand={protocol:Z("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||U.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new $e,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import Oe from"ajv";var nt=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}=B(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||U.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new Oe({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 Qt=class{constructor(t){this.config=t;this.pendingWarp={protocol:Z("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 $t(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 nt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
+ `))}};import{existsSync as Ct,mkdirSync as Ve,readdirSync as He,readFileSync as Fe,unlinkSync as xt,writeFileSync as Ue}from"fs";import{join as Xt,resolve as Zt}from"path";var Kt=new w,it=(r,t)=>typeof t=="bigint"?Kt.nativeToString("biguint",t):t,q=(r,t)=>typeof t=="string"&&t.startsWith(h.Biguint+":")?Kt.stringToNative(t)[1]:t;var at=class{constructor(t,e){let n=e?.path;this.cacheDir=n?Zt(n):Zt(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){Ct(this.cacheDir)||Ve(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return Xt(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!Ct(e))return null;let n=Fe(e,"utf-8"),i=JSON.parse(n,q);return Date.now()>i.expiresAt?(xt(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);Ue(a,JSON.stringify(i,it),"utf-8")}forget(t){try{let e=this.getFilePath(t);Ct(e)&&xt(e)}catch{}}clear(){try{He(this.cacheDir).forEach(e=>{e.endsWith(".json")&&xt(Xt(this.cacheDir,e))})}catch{}}};var Q=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,q);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,it))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var F=class F{constructor(t,e){}get(t){let e=F.cache.get(t);return e?Date.now()>e.expiresAt?(F.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;F.cache.set(t,{value:e,expiresAt:i})}forget(t){F.cache.delete(t)}clear(){F.cache.clear()}};F.cache=new Map;var K=F;import{readFileSync as De}from"fs";import{resolve as Yt}from"path";var st=class{constructor(t,e){let n=e?.path?Yt(e.path):Yt(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=De(t,"utf-8");return new Map(Object.entries(JSON.parse(e,q)))}catch(e){return C.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a)}forget(t){this.cache.delete(t)}clear(){this.cache.clear()}};var te={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},wt={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`},ot=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new Q(t,e):e?.type==="memory"?new K(t,e):e?.type==="static"?new st(t,e):e?.type==="filesystem"?new at(t,e):typeof window<"u"&&window.localStorage?new Q(t,e):new K(t,e)}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var X={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},It={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},St=(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)},Pt=r=>{try{return JSON.parse(r)}catch{return null}},je=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:c,nonce:o,expiresAt:u}=await vt(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(At(n,d,o,u)).forEach(([f,m])=>s.set(f,m))}let p=St(e.resolvedInputs,X.Headers,i);if(p){let c=Pt(p);c&&typeof c=="object"&&Object.entries(c).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([c,o])=>{s.set(c,r.applyInputs(o,e.resolvedInputs,i))});return s},Le=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===It.Get){let s=St(e.resolvedInputs,X.Queries,i);if(s){let p=Pt(s);if(p&&typeof p=="object"){let c=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&c.searchParams.set(o,String(u))),a=c.toString()}}}return a},Me=(r,t,e,n,i)=>{if(r===It.Get)return;let a=St(t.resolvedInputs,X.Payload,n);if(a&&Pt(a)!==null)return a;let{[X.Payload]:s,[X.Queries]:p,...c}=e;return JSON.stringify({...c,...i})},ee=async(r,t,e,n,i,a,s,p)=>{let c=t.method||It.Get,o=await je(r,t,e,n,a,p),u=Le(r,t,e,c,a),d=Me(c,e,i,a,s);return{url:u,method:c,headers:o,body:d}};var E=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);return await this.applyGlobals(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),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(l.Vars.Query+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Query.length+1),[o,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,m=e.queries?.[o]||null||d;m&&a(s,m)}else if(p.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Env.length+1),[o,u]=c.split(l.ArgCompositeSeparator),f={...this.config.vars,...e.envs}?.[o];f&&a(s,f)}else p===l.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(l.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(l.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(l.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(l.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 c=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(c,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 c=p;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var k=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 ot(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(wt.WarpExecutable(t,e||"",n))||[];return N(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),c=new E(this.config,p,this.adapters),o=await c.apply(t,i),u=b(o,e),{action:d,index:f}=B(o),m=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(s.name,d,m,c),g=await this.getModifiedInputs(y),A=[],v=[];f===e-1?(A=y,v=g):this.requiresPayloadInputs(u)&&(A=await this.resolveActionInputs(s.name,u,n,c),v=await this.getModifiedInputs(A));let T=v.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,O=this.getDestinationFromAction(u),x=T?this.serializer.stringToNative(T)[1]:O;if(x&&(x=c.applyInputs(x,v,this.serializer,g)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let R=this.getPreparedArgs(u,v);R=R.map(I=>c.applyInputs(I,v,this.serializer,g));let V=v.find(I=>I.input.position==="value")?.value||null,P="value"in u?u.value:null,H=V?.split(l.ArgParamsSeparator)[1]||P||"0",G=c.applyInputs(H,v,this.serializer,g),ie=BigInt(G),ae=v.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),se=[...("transfers"in u?u.transfers:[])||[],...ae||[]].map(I=>{let le=c.applyInputs(I,v,this.serializer,g);return this.serializer.stringToNative(le)[1]}),oe=v.find(I=>I.input.position==="data")?.value,pe="data"in u?u.data||"":null,Tt=oe||pe||null,ce=Tt?c.applyInputs(Tt,v,this.serializer,g):null,bt={adapter:p,warp:o,chain:s,action:e,destination:x,args:R,value:ie,transfers:se,data:ce,resolvedInputs:v};return this.cache.set(wt.WarpExecutable(this.config.env,o.meta?.hash||"",e),bt.resolvedInputs,te.OneWeek),bt}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(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i){let a=e.inputs||[],s=n.map(o=>i.applyInputs(o,[],this.serializer)),p=await Promise.all(s.map(o=>this.preprocessInput(t,o))),c=(o,u)=>{if(o.source===l.Source.UserWallet){let f=S(this.config,t);return f?this.serializer.nativeToString("address",f):null}if(o.source==="hidden"){if(o.default===void 0)return null;let f=i?i.applyInputs(String(o.default),[],this.serializer):String(o.default);return this.serializer.nativeToString(o.type,f)}if(p[u])return p[u];let d=this.url.searchParams.get(o.as||o.name);return d?this.serializer.nativeToString(o.type,d):null};return a.map((o,u)=>{let d=c(o,u),f=o.default!==void 0?i?i.applyInputs(String(o.default),[],this.serializer):String(o.default):void 0;return{input:o,value:d||(f!==void 0?this.serializer.nativeToString(o.type,f):null)}})}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i){let a=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,a,i)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,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 c=Y(p,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=Y(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.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=this.buildInputContext(t,n,i),c=await s.run(a,p);if(c==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:o})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let a=0;a<e;a++){let s=t[a];if(!s.value)continue;let p=s.input.as||s.input.name,[,c]=this.serializer.stringToNative(s.value);if(i[p]=c,s.input.type==="asset"&&typeof c=="object"&&c!==null){let o=c;"identifier"in o&&"amount"in o&&(i[`${p}.token`]=String(o.identifier),i[`${p}.amount`]=String(o.amount),i[`${p}.identifier`]=String(o.identifier))}}if(n&&n.value){let a=n.input.as||n.input.name,[,s]=this.serializer.stringToNative(n.value);if(i[a]=s,n.input.type==="asset"&&typeof s=="object"&&s!==null){let p=s;"identifier"in p&&"amount"in p&&(i[`${a}.token`]=String(p.identifier),i[`${a}.amount`]=String(p.amount),i[`${a}.identifier`]=String(p.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=ht(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,c]=i.split(l.ArgCompositeSeparator);if(c)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=Y(p,o.decimals);return _t({...o,amount:u})}else return e}catch(n){throw C.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input: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,c]=this.serializer.stringToNative(s),o=c;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(c=>c.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.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 pt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new k(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...Dt(t.meta?.query??null),...n.queries},u={...n,queries:o},{action:d,index:f}=B(t);for(let m=1;m<=t.actions.length;m++){let y=b(t,m);if(!ft(y,t))continue;let{tx:g,chain:A,immediateExecution:v,executable:T}=await this.executeAction(t,m,e,u);g&&i.push(g),A&&(a=A),v&&s.push(v),T&&m===f+1&&T.resolvedInputs&&(p=N(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 m=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(m))}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):Et.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==="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(!ft(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[p],o=p+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),f={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:f})),f}let u=await i.output.getActionExecution(t,o,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:c})):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:c}=await rt(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,c)}async doHttpRequest(t,e,n,i,a){let s=new E(this.config,W(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:c,method:o,headers:u,body:d}=await ee(s,e,t,n,i,p,a,async f=>await this.callHandler(()=>this.handlers?.onSignRequest?.(f)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:o,headers:u,body:d});try{let m=await fetch(c,{method:o,headers:u,body:d});C.debug("Collect response status",{status:m.status}),m.status===402&&(m=await Gt(m,c,o,d,this.adapters));let y=await m.json();C.debug("Collect response content",{content:y});let{values:g,output:A}=await rt(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),m.ok?"success":"error",g,A,y)}catch(f){C.error("WarpActionExecutor: Error executing collect",f);let m=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=S(this.config,t.chain.name),i=b(t.warp,t.action);if(!i.destination){let m=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let y=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:y}}let p=this.factory.getSerializer(),c=new E(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,u=c.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),f={};o.headers&&Object.entries(o.headers).forEach(([m,y])=>{let g=c.applyInputs(y,t.resolvedInputs,this.factory.getSerializer());f[m]=g}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:f});try{let m=new s(new URL(u),{requestInit:{headers:f}}),y=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(m);let g={};t.resolvedInputs.forEach(({input:x,value:R})=>{if(R&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let V=x.position.replace("payload:",""),[P,H]=p.stringToNative(R);if(P==="string")g[V]=String(H);else if(P==="bool")g[V]=!!H;else if(P==="uint8"||P==="uint16"||P==="uint32"||P==="uint64"||P==="uint128"||P==="uint256"||P==="biguint"){let G=Number(H);g[V]=(Number.isInteger(G),G)}else g[V]=H}}),e&&Object.assign(g,e);let A=await y.callTool({name:d,arguments:g});await y.close();let v;if(A.content&&A.content.length>0){let x=A.content[0];if(x.type==="text")try{v=JSON.parse(x.text)}catch{v=x.text}else x.type,v=x}else v=A;let{values:T,output:O}=await rt(t.warp,v,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",T,O,A)}catch(m){C.error("WarpExecutor: Error executing MCP",m);let y=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:m},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:y}}}buildCollectResult(t,e,n,i,a,s){let p=Wt(this.config,this.adapters,t.warp,t.action,a),c=N(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:mt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}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),c=new E(this.config,p,this.adapters),o=await c.apply(t,a),u=b(o,n),{action:d}=B(o),f=this.factory.getStringTypedInputs(d,i),m=await this.factory.getResolvedInputs(s.name,d,f,c),y=await this.factory.getModifiedInputs(m),g=y;if(e.inputs&&e.inputs.length>0){let V=this.factory.getStringTypedInputs(e,i),P=await this.factory.getResolvedInputs(s.name,e,V,c);g=await this.factory.getModifiedInputs(P)}let A=c.applyInputs(u.prompt,g,this.factory.getSerializer(),y),v=N(g),T=S(this.config,s.name),O=this.factory.getSerializer(),{values:x,output:R}=await zt(o,A,n,g,O,this.config);return{status:"success",warp:o,action:n,user:T,txHash:null,tx:null,next:Wt(this.config,this.adapters,o,n,R),values:x,output:R,messages:mt(o,R,this.config),destination:null,resolvedInputs:v}}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),c=W(p.name,this.adapters),o=new E(this.config,c,this.adapters),{action:u}=B(t),d=this.factory.getStringTypedInputs(u,n),f=await this.factory.getResolvedInputs(p.name,u,d,o),m=await this.factory.getModifiedInputs(f),y;if(a)y=a;else{let v=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o);y=await this.factory.getModifiedInputs(v)}let g=o.buildInputBag(y,this.factory.getSerializer(),m),A=Ot(e.when,g);return Vt(A)}};var ct=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 lt=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!_(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,c=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?_(t,this.config.defaultChain):$(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,c=null,o=null,u=W(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?Ft(t):Ut(i.identifier);if(a==="hash"){p=await u.builder().createFromTransactionHash(s,e);let g=await u.registry.getInfoByHash(s,e);c=g.registryInfo,o=g.brand}else if(a==="alias"){let g=await u.registry.getInfoByAlias(s,e);c=g.registryInfo,o=g.brand,g.registryInfo&&(p=await u.builder().createFromTransactionHash(g.registryInfo.hash,e))}if(p&&p.meta&&(ze(p,u.chainInfo.name,c,i.identifier),p.meta.query=d),!p)return n;let f=p.chain||u.chainInfo.name,m=W(f,this.adapters),y=await new E(this.config,m,this.adapters).apply(p);return{match:!0,url:t,warp:y,chain:f,registryInfo:c,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},ze=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?gt(t,"alias",e.alias):gt(t,"hash",e?.hash??n))};var re=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new pt(this.config,this.chains,t)}async detectWarp(t,e){return new lt(this.config,this.chains).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 y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await y.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:f}=await c.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await c.evaluateOutput(p,y)},resolvedInputs:f}}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=$(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 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 k(this.config,this.chains)}get index(){return new ct(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 tt(t,this.config)}};var ne=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{ut as BrowserCryptoProvider,te as CacheTtl,er as EvmWalletChainNames,dt as NodeCryptoProvider,Ir as WARP_LANGUAGES,Jt as WarpBrandBuilder,Qt as WarpBuilder,ot as WarpCache,wt as WarpCacheKey,We as WarpChainName,re as WarpClient,U as WarpConfig,l as WarpConstants,pt as WarpExecutor,k as WarpFactory,ct as WarpIndex,h as WarpInputTypes,E as WarpInterpolator,z as WarpLinkBuilder,lt as WarpLinkDetecter,C as WarpLogger,M as WarpProtocolVersions,w as WarpSerializer,ne as WarpTypeRegistry,nt as WarpValidator,$n as address,mt as applyOutputToMessages,_t as asset,Nn as biguint,Bn as bool,J as buildMappedOutput,Se as buildNestedPayload,hr as bytesToBase64,ve as bytesToHex,et as cleanWarpIdentifier,At as createAuthHeaders,vt as createAuthMessage,yr as createCryptoProvider,mn as createDefaultWalletProvider,ln as createHttpAuthHeaders,Re as createSignableMessage,Pr as createWarpI18nText,gt as createWarpIdentifier,Mt as evaluateOutputCommon,Vt as evaluateWhenCondition,rt as extractCollectOutput,_ as extractIdentifierInfoFromUrl,zt as extractPromptOutput,Ut as extractQueryStringFromIdentifier,Ft as extractQueryStringFromUrl,N as extractResolvedInputValues,Ar as extractWarpSecrets,W as findWarpAdapterForChain,Rt as getCryptoProvider,pr as getEventNameFromWarp,Z as getLatestProtocolIdentifier,Wt as getNextInfo,sn as getProviderConfig,Nt as getRandomBytes,Bt as getRandomHex,Ge as getWalletFromConfigOrFail,b as getWarpActionByIndex,lr as getWarpBrandLogoUrl,ur as getWarpChainAssetLogoUrl,dr as getWarpChainInfoLogoUrl,$ as getWarpInfoFromIdentifier,B as getWarpPrimaryAction,ue as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,ge as getWarpWalletExternalId,he as getWarpWalletExternalIdFromConfig,Qe as getWarpWalletExternalIdFromConfigOrFail,fe as getWarpWalletMnemonic,Je as getWarpWalletMnemonicFromConfig,de as getWarpWalletPrivateKey,_e as getWarpWalletPrivateKeyFromConfig,Gt as handleX402Payment,$r as hasInputPrefix,On as hex,gn as initializeWalletCache,Rr as isEqualWarpIdentifier,ft as isWarpActionAutoExecute,Sr as isWarpI18nText,Ke as isWarpWalletReadOnly,jt as mergeNestedPayload,Ze as normalizeAndValidateMnemonic,me as normalizeMnemonic,Vn as option,Ee as parseOutputOutIndex,dn as parseSignedMessage,Dt as parseWarpQueryStringToObject,j as replacePlaceholders,Ot as replacePlaceholdersInWhenExpression,tt as resolveWarpText,Et as safeWindow,gr as setCryptoProvider,Xe as setWarpWalletInConfig,Y as shiftBigintBy,ht as splitInput,Pn as string,Fn as struct,mr as testCryptoAvailability,Pe as toInputPayloadValue,$t as toPreviewText,Hn as tuple,bn as uint16,En as uint32,Rn as uint64,Tn as uint8,ye as validateMnemonicLength,un as validateSignedMessage,Un as vector,ar as withAdapterFallback};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joai/warps",
3
- "version": "3.0.0-beta.203",
3
+ "version": "3.0.0-beta.205",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",