@vleap/warps 3.0.0-beta.175 → 3.0.0-beta.176

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
@@ -650,7 +650,7 @@ declare const WarpInputTypes: {
650
650
  };
651
651
  declare const safeWindow: Window;
652
652
 
653
- declare const withAdapter: (factory: ChainAdapterFactory, fallbackFactory: ChainAdapterFactory) => ChainAdapterFactory;
653
+ declare const withAdapterFallback: (factory: ChainAdapterFactory, fallbackFactory: ChainAdapterFactory) => ChainAdapterFactory;
654
654
 
655
655
  declare const getEventNameFromWarp: (warp: Warp, alertName: string) => string | null;
656
656
 
@@ -1233,4 +1233,4 @@ declare class WarpValidator {
1233
1233
  private validateSchema;
1234
1234
  }
1235
1235
 
1236
- export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, getWarpWalletProviderId, getWarpWalletProviderIdFromConfig, getWarpWalletProviderIdFromConfigOrFail, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, mergeNestedPayload, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateSignedMessage, vector, withAdapter };
1236
+ export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, getWarpWalletProviderId, getWarpWalletProviderIdFromConfig, getWarpWalletProviderIdFromConfigOrFail, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, mergeNestedPayload, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateSignedMessage, vector, withAdapterFallback };
package/dist/index.d.ts CHANGED
@@ -650,7 +650,7 @@ declare const WarpInputTypes: {
650
650
  };
651
651
  declare const safeWindow: Window;
652
652
 
653
- declare const withAdapter: (factory: ChainAdapterFactory, fallbackFactory: ChainAdapterFactory) => ChainAdapterFactory;
653
+ declare const withAdapterFallback: (factory: ChainAdapterFactory, fallbackFactory: ChainAdapterFactory) => ChainAdapterFactory;
654
654
 
655
655
  declare const getEventNameFromWarp: (warp: Warp, alertName: string) => string | null;
656
656
 
@@ -1233,4 +1233,4 @@ declare class WarpValidator {
1233
1233
  private validateSchema;
1234
1234
  }
1235
1235
 
1236
- export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, getWarpWalletProviderId, getWarpWalletProviderIdFromConfig, getWarpWalletProviderIdFromConfigOrFail, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, mergeNestedPayload, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateSignedMessage, vector, withAdapter };
1236
+ export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, getWarpWalletProviderId, getWarpWalletProviderIdFromConfig, getWarpWalletProviderIdFromConfigOrFail, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, mergeNestedPayload, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateSignedMessage, vector, withAdapterFallback };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var ur=Object.create;var ot=Object.defineProperty;var dr=Object.getOwnPropertyDescriptor;var fr=Object.getOwnPropertyNames;var gr=Object.getPrototypeOf,hr=Object.prototype.hasOwnProperty;var mr=(n,t)=>{for(var r in t)ot(n,r,{get:t[r],enumerable:!0})},Lt=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of fr(t))!hr.call(n,i)&&i!==r&&ot(n,i,{get:()=>t[i],enumerable:!(e=dr(t,i))||e.enumerable});return n};var z=(n,t,r)=>(r=n!=null?ur(gr(n)):{},Lt(t||!n||!n.__esModule?ot(r,"default",{value:n,enumerable:!0}):r,n)),yr=n=>Lt(ot({},"__esModule",{value:!0}),n);var ue={};mr(ue,{BrowserCryptoProvider:()=>pt,CacheTtl:()=>Ft,NodeCryptoProvider:()=>ct,WARP_LANGUAGES:()=>Pr,WarpBrandBuilder:()=>Vt,WarpBuilder:()=>Ot,WarpCache:()=>nt,WarpCacheKey:()=>ht,WarpChainName:()=>Dt,WarpClient:()=>Ht,WarpConfig:()=>F,WarpConstants:()=>l,WarpExecutor:()=>it,WarpFactory:()=>k,WarpIndex:()=>at,WarpInputTypes:()=>g,WarpInterpolator:()=>b,WarpLinkBuilder:()=>L,WarpLinkDetecter:()=>st,WarpLogger:()=>x,WarpProtocolVersions:()=>U,WarpSerializer:()=>w,WarpTypeRegistry:()=>Nt,WarpValidator:()=>tt,address:()=>ee,applyOutputToMessages:()=>St,asset:()=>$t,biguint:()=>te,bool:()=>re,buildMappedOutput:()=>Z,buildNestedPayload:()=>zt,bytesToBase64:()=>Cr,bytesToHex:()=>kt,cleanWarpIdentifier:()=>X,createAuthHeaders:()=>gt,createAuthMessage:()=>ft,createCryptoProvider:()=>Ir,createDefaultWalletProvider:()=>Gr,createHttpAuthHeaders:()=>Ur,createSignableMessage:()=>Kt,createWarpI18nText:()=>br,createWarpIdentifier:()=>ut,evaluateOutputCommon:()=>Jt,evaluateWhenCondition:()=>Ct,extractCollectOutput:()=>Y,extractIdentifierInfoFromUrl:()=>G,extractQueryStringFromIdentifier:()=>It,extractQueryStringFromUrl:()=>wt,extractResolvedInputValues:()=>B,extractWarpSecrets:()=>Sr,findWarpAdapterForChain:()=>m,getCryptoProvider:()=>yt,getEventNameFromWarp:()=>vr,getLatestProtocolIdentifier:()=>_,getNextInfo:()=>Tt,getProviderConfig:()=>Nr,getRandomBytes:()=>Wt,getRandomHex:()=>vt,getWalletFromConfigOrFail:()=>Dr,getWarpActionByIndex:()=>T,getWarpBrandLogoUrl:()=>Ar,getWarpInfoFromIdentifier:()=>R,getWarpPrimaryAction:()=>V,getWarpWalletAddress:()=>Qt,getWarpWalletAddressFromConfig:()=>S,getWarpWalletMnemonic:()=>Zt,getWarpWalletMnemonicFromConfig:()=>Mr,getWarpWalletPrivateKey:()=>Xt,getWarpWalletPrivateKeyFromConfig:()=>kr,getWarpWalletProviderId:()=>Yt,getWarpWalletProviderIdFromConfig:()=>tr,getWarpWalletProviderIdFromConfigOrFail:()=>qr,handleX402Payment:()=>Bt,hasInputPrefix:()=>$r,hex:()=>ne,initializeWalletCache:()=>zr,isEqualWarpIdentifier:()=>Er,isWarpActionAutoExecute:()=>lt,isWarpI18nText:()=>Tr,mergeNestedPayload:()=>bt,option:()=>ie,parseOutputOutIndex:()=>_t,parseSignedMessage:()=>Lr,replacePlaceholders:()=>H,replacePlaceholdersInWhenExpression:()=>xt,resolveWarpText:()=>Q,safeWindow:()=>mt,setCryptoProvider:()=>xr,shiftBigintBy:()=>K,splitInput:()=>dt,string:()=>Kr,struct:()=>se,testCryptoAvailability:()=>wr,toInputPayloadValue:()=>Gt,toPreviewText:()=>At,tuple:()=>ae,uint16:()=>Xr,uint32:()=>Zr,uint64:()=>Yr,uint8:()=>Qr,validateSignedMessage:()=>jr,vector:()=>oe,withAdapter:()=>Wr});module.exports=yr(ue);var Dt=(u=>(u.Multiversx="multiversx",u.Vibechain="vibechain",u.Sui="sui",u.Ethereum="ethereum",u.Base="base",u.Arbitrum="arbitrum",u.Somnia="somnia",u.Fastset="fastset",u.Solana="solana",u.Near="near",u))(Dt||{}),l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:n=>{if(!n.adapter.wallet)return null;try{return n.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},g={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},mt=typeof window<"u"?window:{open:()=>{}};var U={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},F={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${U.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${U.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="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 Wr=(n,t)=>(r,e)=>{let i=t(r,e);return n(r,i)};var vr=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!r.trigger.startsWith(e))return null;let i=r.trigger.replace(e,"");return i||null};var Ar=(n,t)=>typeof n.logo=="string"?n.logo:n.logo[t?.scheme??"light"];var pt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let r=new Uint8Array(t);return window.crypto.getRandomValues(r),r}},ct=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let r=await import("crypto");return new Uint8Array(r.randomBytes(t))}catch(r){throw new Error(`Node.js crypto not available: ${r instanceof Error?r.message:"Unknown error"}`)}}},j=null;function yt(){if(j)return j;if(typeof window<"u"&&window.crypto)return j=new pt,j;if(typeof process<"u"&&process.versions?.node)return j=new ct,j;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function xr(n){j=n}async function Wt(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||yt()).getRandomBytes(n)}function kt(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(n.length*2);for(let r=0;r<n.length;r++){let e=n[r];t[r*2]=(e>>>4).toString(16),t[r*2+1]=(e&15).toString(16)}return t.join("")}function Cr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(n).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(n));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function vt(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await Wt(n/2,t);return kt(r)}async function wr(){let n={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?n.environment="browser":typeof process<"u"&&process.versions?.node&&(n.environment="nodejs"),await Wt(16),n.randomBytes=!0}catch{}return n}function Ir(){return yt()}var Sr=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let r=t.replace(`${l.Vars.Env}:`,"").trim(),[e,i]=r.split(l.ArgCompositeSeparator);return{key:e,description:i||null}});var m=(n,t)=>{let r=t.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},_=n=>{if(n==="warp")return`warp:${U.Warp}`;if(n==="brand")return`brand:${U.Brand}`;if(n==="abi")return`abi:${U.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},T=(n,t)=>n?.actions[t-1],V=n=>{if(n.actions.length===0)throw new Error(`Warp has no primary action: ${n.meta?.identifier}`);let t=n.actions.find(s=>s.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let r=["transfer","contract","query","collect","mcp"],e=n.actions.find(s=>r.includes(s.type));return e?{action:e,index:n.actions.indexOf(e)}:{action:n.actions[0],index:0}},lt=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=V(t);return n===r}return!0},K=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(s,"0"));if(t<0){let a=e+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},At=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},H=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),xt=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>{let i=t[e];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Ct=n=>{if(!n||typeof n!="string")return!0;try{return!!new Function(`return ${n}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${n}. Error: ${t}`)}};var Pr={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},Q=(n,t)=>{let r=t?.preferences?.locale||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(r in n)return n[r];if("en"in n)return n.en;let e=Object.keys(n);if(e.length>0)return n[e[0]]}return""},Tr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,br=n=>n;var X=n=>n.startsWith(l.IdentifierAliasMarker)?n.replace(l.IdentifierAliasMarker,""):n,Er=(n,t)=>!n||!t?!1:X(n)===X(t),ut=(n,t,r)=>{let e=X(r);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+n+l.IdentifierParamSeparator+e:n+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+e},R=n=>{let t=decodeURIComponent(n).trim(),r=X(t),e=r.split("?")[0],i=Mt(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:r,identifierBase:e};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,o]=i;if(a===l.IdentifierType.Alias||a===l.IdentifierType.Hash){let p=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:p,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===l.IdentifierType.Alias||s===l.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:l.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==l.IdentifierType.Alias&&s!==l.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,p=Rr(a,s)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:s,type:p,identifier:o,identifierBase:a}}}return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:r,identifierBase:e}},G=n=>{let t=new URL(n),e=t.searchParams.get(l.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return R(i)},Rr=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Br=n=>{let t=l.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},Mt=n=>{let t=Br(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=Mt(s);return[i,...a]},wt=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(l.IdentifierParamName),r.toString()||null}catch{return null}},It=n=>{let t=n.indexOf("?");if(t===-1||t===n.length-1)return null;let r=n.substring(t+1);return r.length>0?r:null};var dt=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},$r=n=>{let t=new Set(Object.values(g));if(!n.includes(l.ArgParamsSeparator))return!1;let r=dt(n)[0];return t.has(r)};var St=(n,t,r)=>{let e=Object.entries(n.messages||{}).map(([i,s])=>{let a=Q(s,r);return[i,H(a,t)]});return Object.fromEntries(e)};var qt=z(require("qr-code-styling"),1);var L=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!G(t):!1}build(t,r,e){let i=this.config.clientUrl||F.DefaultClientUrl(this.config.env),s=m(t,this.adapters),a=r===l.IdentifierType.Alias?e:r+l.IdentifierParamSeparator+e,o=s.chainInfo.name+l.IdentifierParamSeparator+a,p=encodeURIComponent(o);return F.SuperClientUrls.includes(i)?`${i}/${p}`:`${i}?${l.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let r=R(t);if(!r)return null;let e=m(r.chain,this.adapters);return e?this.build(e.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,e,i=512,s="white",a="black",o="#23F7DD"){let p=m(t,this.adapters),c=this.build(p.chainInfo.name,r,e);return new qt.default({type:"svg",width:i,height:i,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Vr="https://",Tt=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Vr))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let f=H(a,{...r.vars,...i});return[{identifier:f,url:Pt(t,f,n)}]}let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let f=H(o,{...r.vars,...i}),v=f?`${a}?${f}`:a;return[{identifier:v,url:Pt(t,v,n)}]}let c=p[0];if(!c)return[];let u=c.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 y=p.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let v=o;for(let{regex:E,field:$}of y){let C=$?Or(f,$):f;if(C==null)return null;v=v.replace(E,C)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${a}?${v}`:a;return{identifier:A,url:Pt(t,A,n)}}).filter(f=>f!==null)},Pt=(n,t,r)=>{let[e,i]=t.split("?"),s=R(e)||{chain:l.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=m(s.chain,n);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let o=new L(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let p=new URL(o);return new URLSearchParams(i).forEach((c,u)=>p.searchParams.set(u,c)),p.toString().replace(/\/\?/,"?")},Or=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);var D=class D{static debug(...t){D.isTestEnv||console.debug(...t)}static info(...t){D.isTestEnv||console.info(...t)}static warn(...t){D.isTestEnv||console.warn(...t)}static error(...t){D.isTestEnv||console.error(...t)}};D.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=D;function zt(n,t,r){return n.startsWith(l.Position.Payload)?n.slice(l.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function bt(n,t){if(!n)return{...t};if(!t)return{...n};let r={...n};return Object.keys(t).forEach(e=>{r[e]&&typeof r[e]=="object"&&typeof t[e]=="object"?r[e]=bt(r[e],t[e]):r[e]=t[e]}),r}function Gt(n,t){if(!n.value)return null;let r=t.stringToNative(n.value)[1];if(n.input.type==="biguint")return r.toString();if(n.input.type==="asset"){let{identifier:e,amount:i}=r;return{identifier:e,amount:i.toString()}}else return r}function B(n){return n.map(t=>t.value).filter(t=>t!=null&&t!=="")}function Z(n,t){let r={};return n.forEach(e=>{let i=e.input.as||e.input.name,s=Gt(e,t);if(e.input.position&&typeof e.input.position=="string"&&e.input.position.startsWith(l.Position.Payload)){let a=zt(e.input.position,i,s);r=bt(r,a)}else r[i]=s}),r}var Y=async(n,t,r,e,i,s)=>{let a=[],o=[],p={};for(let[u,d]of Object.entries(n.output||{})){if(d.startsWith(l.Transform.Prefix))continue;let h=_t(d);if(h!==null&&h!==r){p[u]=null;continue}let[y,...W]=d.split("."),f=(v,A)=>A.reduce((E,$)=>E&&E[$]!==void 0?E[$]:null,v);if(y==="out"||y.startsWith("out[")){let v=W.length===0?t?.data||t:f(t,W);a.push(String(v)),o.push(v),p[u]=v}else p[u]=d}let c=Z(e,i);return{values:{string:a,native:o,mapped:c},output:await Jt(n,p,r,e,i,s)}},Jt=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=Fr(a,n,r,e,i),a=await Hr(n,a,s.transform?.runner||null),a},Fr=(n,t,r,e,i)=>{let s={...n},a=T(t,r)?.inputs||[];for(let[o,p]of Object.entries(s))if(typeof p=="string"&&p.startsWith("in.")){let c=p.split(".")[1],u=a.findIndex(h=>h.as===c||h.name===c),d=u!==-1?e[u]?.value:null;s[o]=d?i.stringToNative(d)[1]:null}return s},Hr=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(l.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(l.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:a}of i)try{e[s]=await r.run(a,e)}catch(o){x.error(`Transform error for output '${s}':`,o),e[s]=null}return e},_t=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};var Nr=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};async function Kt(n,t,r,e=5){let i=await vt(64,r),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function ft(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return Kt(n,i,r,5)}function gt(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function Ur(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await ft(n,r,e),o=await t(i);return gt(n,o,s,a)}function jr(n){let t=new Date(n).getTime();return Date.now()<t}function Lr(n){try{let t=JSON.parse(n);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var Dr=(n,t)=>{let r=n.user?.wallets?.[t]||null;if(!r)throw new Error(`No wallet configured for chain ${t}`);return r},Qt=n=>n?typeof n=="string"?n:n.address:null,S=(n,t)=>Qt(n.user?.wallets?.[t]||null),Xt=n=>n?typeof n=="string"?n:n.privateKey||null:null,Zt=n=>n?typeof n=="string"?n:n.mnemonic||null:null,Yt=n=>n?typeof n=="string"?n:n.providerId||null:null,kr=(n,t)=>Xt(n.user?.wallets?.[t]||null)?.trim()||null,Mr=(n,t)=>Zt(n.user?.wallets?.[t]||null)?.trim()||null,tr=(n,t)=>Yt(n.user?.wallets?.[t]||null)?.trim()||null,qr=(n,t)=>{let r=tr(n,t);if(!r)throw new Error(`No provider ID configured for wallet onchain ${t}`);return r};async function zr(n){let t={address:null,publicKey:null};if(!n)return t;try{t.address=await n.getAddress()}catch{}try{t.publicKey=await n.getPublicKey()}catch{}return t}function Gr(n,t,r){return null}var Et=require("@x402/core/client"),Rt=require("@x402/core/http");async function Bt(n,t,r,e,i){let s=await Jr(n,i);if(!s)return n;let a=new Headers;e&&a.set("Content-Type","application/json"),a.set("Accept","application/json"),Object.entries(s).forEach(([p,c])=>{a.set(p,c)}),x.debug("WarpExecutor: Retrying request with payment headers");let o=await fetch(t,{method:r,headers:a,body:e});return x.debug("WarpExecutor: Payment processed, new response status",{status:o.status}),o}var Jr=async(n,t)=>{let r=await _r(n),i=new Rt.x402HTTPClient(new Et.x402Client).getPaymentRequiredResponse(s=>n.headers.get(s),r);if(!i?.accepts?.length)return null;for(let s of t)if(s.wallet.registerX402Handlers)try{let a=new Et.x402Client,o=await s.wallet.registerX402Handlers(a),p=i.accepts.find(h=>h?.network&&o[h.network]);if(!p?.network)continue;o[p.network]();let c=new Rt.x402HTTPClient(a),u=await c.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=c.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return x.debug(`WarpExecutor: x402 payment processed with ${s.chainInfo.name} adapter using ${p.network} scheme`),d}catch{continue}return null},_r=async n=>{try{let t=await n.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===g.Tuple&&Array.isArray(r)){if(r.length===0)return t+l.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(l.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+r.join(l.ArgListSeparator)}if(t===g.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let e=r;if(!e._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=e._name,s=Object.keys(e).filter(o=>o!=="_name");if(s.length===0)return`${t}(${i})${l.ArgParamsSeparator}`;let a=s.map(o=>{let[p,c]=this.getTypeAndValue(e[o]);return`(${o}${l.ArgParamsSeparator}${p})${c}`});return`${t}(${i})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}if(t===g.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${l.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(l.ArgParamsSeparator))){let e=r[0],i=e.indexOf(l.ArgParamsSeparator),s=e.substring(0,i),a=r.map(p=>{let c=p.indexOf(l.ArgParamsSeparator),u=p.substring(c+1);return s.startsWith(g.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),o=s.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+s+l.ArgParamsSeparator+a.join(o)}return t+l.ArgParamsSeparator+r.join(l.ArgListSeparator)}if(t===g.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?g.Asset+l.ArgParamsSeparator+r.identifier+l.ArgCompositeSeparator+String(r.amount)+l.ArgCompositeSeparator+String(r.decimals):g.Asset+l.ArgParamsSeparator+r.identifier+l.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let e=this.typeRegistry.getHandler(t);if(e)return e.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+l.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(l.ArgParamsSeparator),e=r[0],i=r.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e===g.Option){let[s,a]=i.split(l.ArgParamsSeparator);return[g.Option+l.ArgParamsSeparator+s,a||null]}if(e===g.Vector){let s=i.indexOf(l.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),p=a.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(o?o.split(p):[]).map(d=>this.stringToNative(a+l.ArgParamsSeparator+d)[1]);return[g.Vector+l.ArgParamsSeparator+a,u]}else if(e.startsWith(g.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=i.split(l.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${s[c]}${l.IdentifierParamSeparator}${p}`)[1]);return[e,o]}else if(e.startsWith(g.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:s[1]};return i&&i.split(l.ArgListSeparator).forEach(p=>{let c=p.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(c){let[,u,d,h]=c;o[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[1]}}),[e,o]}else{if(e===g.String)return[e,i];if(e===g.Uint8||e===g.Uint16||e===g.Uint32)return[e,Number(i)];if(e===g.Uint64||e===g.Uint128||e===g.Uint256||e===g.Biguint)return[e,BigInt(i||0)];if(e===g.Bool)return[e,i==="true"];if(e===g.Address)return[e,i];if(e===g.Hex)return[e,i];if(e===g.Asset){let[s,a]=i.split(l.ArgCompositeSeparator),o={identifier:s,amount:BigInt(a)};return[e,o]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let o=s.stringToNative(i);return[e,o]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[o,p]=this.stringToNative(`${a}:${i}`);return[e,p]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[r,e]=t.split(l.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[g.Uint32,t]:typeof t=="bigint"?[g.Uint64,t]:typeof t=="boolean"?[g.Bool,t]:[typeof t,t]}};var Kr=n=>new w().nativeToString(g.String,n),Qr=n=>new w().nativeToString(g.Uint8,n),Xr=n=>new w().nativeToString(g.Uint16,n),Zr=n=>new w().nativeToString(g.Uint32,n),Yr=n=>new w().nativeToString(g.Uint64,n),te=n=>new w().nativeToString(g.Biguint,n),re=n=>new w().nativeToString(g.Bool,n),ee=n=>new w().nativeToString(g.Address,n),$t=n=>new w().nativeToString(g.Asset,n),ne=n=>new w().nativeToString(g.Hex,n),ie=(n,t)=>{if(t===null)return g.Option+l.ArgParamsSeparator;let r=n(t),e=r.indexOf(l.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return g.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+s},ae=(...n)=>new w().nativeToString(g.Tuple,n),se=n=>new w().nativeToString(g.Struct,n),oe=n=>new w().nativeToString(g.Vector,n);var rr=z(require("ajv"),1);var Vt=class{constructor(t){this.pendingBrand={protocol:_("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}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,r){if(!t)throw new Error(`Warp: ${r}`)}ensureWarpText(t,r){if(!t)throw new Error(`Warp: ${r}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||F.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new rr.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var er=z(require("ajv"),1);var tt=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validatePrimaryAction(t)),r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validatePrimaryAction(t){try{let{action:r}=V(t);return r?[]:["Primary action is required"]}catch(r){return[r instanceof Error?r.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),e=t.actions.some(a=>a.type==="query");if(!r&&!e)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||F.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new er.default({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var Ot=class{constructor(t){this.config=t;this.pendingWarp={protocol:_("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}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,r=100){return At(t,r)}ensure(t,r){if(!t)throw new Error(r)}ensureWarpText(t,r){if(!t)throw new Error(r);if(typeof t=="object"&&!t.en)throw new Error(r)}async validate(t){let e=await new tt(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
- `))}};var rt=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let e=JSON.parse(r,ce);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let i={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,pe))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r?.startsWith(this.prefix)&&localStorage.removeItem(r)}}},nr=new w,pe=(n,t)=>typeof t=="bigint"?nr.nativeToString("biguint",t):t,ce=(n,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?nr.stringToNative(t)[1]:t;var N=class N{get(t){let r=N.cache.get(t);return r?Date.now()>r.expiresAt?(N.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;N.cache.set(t,{value:r,expiresAt:i})}forget(t){N.cache.delete(t)}clear(){N.cache.clear()}};N.cache=new Map;var et=N;var Ft={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},ht={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,Asset:(n,t,r)=>`asset:${n}:${t}:${r}`},nt=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new rt:t==="memory"?new et:typeof window<"u"&&window.localStorage?new rt:new et}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var b=class{constructor(t,r,e){this.config=t;this.adapter=r;this.adapters=e}async apply(t,r={}){let e=this.applyVars(t,r);return await this.applyGlobals(e)}async applyGlobals(t){let r={...t};return r.actions=await Promise.all((r.actions||[]).map(async e=>await this.applyActionGlobals(e))),r=await this.applyRootGlobals(r),r}applyVars(t,r={}){if(!t?.vars)return t;let e=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),s=(a,o)=>{i=i.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o!="string")s(a,o);else if(o.startsWith(l.Vars.Query+l.ArgParamsSeparator)){let p=o.slice(l.Vars.Query.length+1),[c,u]=p.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(c):null,y=r.queries?.[c]||null||d;y&&s(a,y)}else if(o.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let p=o.slice(l.Vars.Env.length+1),[c,u]=p.split(l.ArgCompositeSeparator),h={...this.config.vars,...r.envs}?.[c];h&&s(a,h)}else o===l.Source.UserWallet&&e?s(a,e):s(a,o)}),JSON.parse(i)}async applyRootGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),r=this.replacePlaceholdersWithChain(r,i.Placeholder,e,i.Accessor)}),JSON.parse(r)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),r=this.replacePlaceholdersWithChain(r,i.Placeholder,e,i.Accessor)}),JSON.parse(r)}applyInputs(t,r,e,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(r,e,i);return H(s,a)}applyGlobalsToText(t){if(!Object.values(l.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)||t.includes(`{{${a}:`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString())),s=this.replacePlaceholdersWithChain(s,a.Placeholder,i,a.Accessor)}),s}replacePlaceholdersWithChain(t,r,e,i){let s=new RegExp(`\\{\\{${r}:([^}]+)\\}\\}`,"g");return t.replace(s,(a,o)=>{let p=o.trim().toLowerCase();if(!this.adapters)return a;try{let c=m(p,this.adapters),u={config:this.config,adapter:c},d=i(u);return d!=null?d.toString():a}catch{return a}})}buildInputBag(t,r,e){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);i[a]=String(o)}),e&&e.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);if(i[`primary.${a}`]=String(o),s.input.type==="asset"&&typeof s.input.position=="object"){let p=o;p&&typeof p=="object"&&"identifier"in p&&"amount"in p&&(i[`primary.${a}.token`]=String(p.identifier),i[`primary.${a}.amount`]=String(p.amount))}}),i}};var k=class{constructor(t,r){this.config=t;this.adapters=r;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new nt(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,r,e){let i=this.cache.get(ht.WarpExecutable(t,r||"",e))||[];return B(i)}async createExecutable(t,r,e,i={}){let s=T(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=m(a.name,this.adapters),p=new b(this.config,o,this.adapters),c=await p.apply(t,i),u=T(c,r),{action:d,index:h}=V(c),y=this.getStringTypedInputs(d,e),W=await this.getResolvedInputs(a.name,d,y,p),f=await this.getModifiedInputs(W),v=[],A=[];h===r-1?(v=W,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(a.name,u,e,p),A=await this.getModifiedInputs(v));let E=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,$=this.getDestinationFromAction(u),C=E?this.serializer.stringToNative(E)[1]:$;if(C&&(C=p.applyInputs(C,A,this.serializer,f)),!C&&s.type!=="collect"&&s.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let M=this.getPreparedArgs(u,A);M=M.map(I=>p.applyInputs(I,A,this.serializer,f));let q=A.find(I=>I.input.position==="value")?.value||null,P="value"in u?u.value:null,O=q?.split(l.ArgParamsSeparator)[1]||P||"0",J=p.applyInputs(O,A,this.serializer,f),ir=BigInt(J),ar=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),sr=[...("transfers"in u?u.transfers:[])||[],...ar||[]].map(I=>{let lr=p.applyInputs(I,A,this.serializer,f);return this.serializer.stringToNative(lr)[1]}),or=A.find(I=>I.input.position==="data")?.value,pr="data"in u?u.data||"":null,Ut=or||pr||null,cr=Ut?p.applyInputs(Ut,A,this.serializer,f):null,jt={adapter:o,warp:c,chain:a,action:r,destination:C,args:M,value:ir,transfers:sr,data:cr,resolvedInputs:A};return this.cache.set(ht.WarpExecutable(this.config.env,c.meta?.hash||"",r),jt.resolvedInputs,Ft.OneWeek),jt}async getChainInfoForWarp(t,r){if(t.chain)return m(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let e=t.inputs||[];return r.map((i,s)=>{let a=e[s];return!a||i.includes(l.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(p=>this.preprocessInput(t,p))),o=(p,c)=>{if(p.source==="query"){let u=this.url.searchParams.get(p.name);return u?this.serializer.nativeToString(p.type,u):null}else if(p.source===l.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(p.source==="hidden"){if(p.default===void 0)return null;let u=i?i.applyInputs(String(p.default),[],this.serializer):String(p.default);return this.serializer.nativeToString(p.type,u)}else return a[c]||null};return s.map((p,c)=>{let u=o(p,c),d=p.default!==void 0?i?i.applyInputs(String(p.default),[],this.serializer):String(p.default):void 0;return{input:p,value:u||(d!==void 0?this.serializer.nativeToString(p.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(r=>typeof r.position=="string"&&r.position.startsWith("payload:"))??!1}async resolveActionInputs(t,r,e,i){let s=this.getStringTypedInputs(r,e);return await this.getResolvedInputs(t,r,s,i)}async getModifiedInputs(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];if(i.input.modifier?.startsWith("scale:")){let[,s]=i.input.modifier.split(":");if(isNaN(Number(s))){let a=Number(t.find(c=>c.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let p=K(o,+a);r.push({...i,value:`${i.input.type}:${p}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=K(a,+s);r.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let s=i.input.modifier.substring(l.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let o=this.buildInputContext(t,e,i),p=await a.run(s,o);if(p==null)r.push(i);else{let c=this.serializer.nativeToString(i.input.type,p);r.push({...i,value:c})}}else r.push(i)}return r}buildInputContext(t,r,e){let i={};for(let s=0;s<r;s++){let a=t[s];if(!a.value)continue;let o=a.input.as||a.input.name,[,p]=this.serializer.stringToNative(a.value);if(i[o]=p,a.input.type==="asset"&&typeof p=="object"&&p!==null){let c=p;"identifier"in c&&"amount"in c&&(i[`${o}.token`]=String(c.identifier),i[`${o}.amount`]=String(c.amount),i[`${o}.identifier`]=String(c.identifier))}}if(e&&e.value){let s=e.input.as||e.input.name,[,a]=this.serializer.stringToNative(e.value);if(i[s]=a,e.input.type==="asset"&&typeof a=="object"&&a!==null){let o=a;"identifier"in o&&"amount"in o&&(i[`${s}.token`]=String(o.identifier),i[`${s}.amount`]=String(o.amount),i[`${s}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,r){try{let[e,i]=dt(r),s=m(t,this.adapters);if(e==="asset"){let[a,o,p]=i.split(l.ArgCompositeSeparator);if(p)return r;let c=await s.dataLoader.getAsset(a);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=K(o,c.decimals);return $t({...c,amount:u})}else return r}catch(e){throw x.warn("WarpFactory: Preprocess input failed",e),e}}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,r){let e="args"in t?t.args||[]:[],i=[];return r.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[o,p]=this.serializer.stringToNative(a),c=p;if(!c||typeof c!="object"||!("identifier"in c)||!("amount"in c))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,d=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",c.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",c.amount)})}else if(s.position.startsWith("arg:")){let o=Number(s.position.split(":")[1])-1;i.push({index:o,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;e.length<=s;)e.push(void 0);e[s]=a}),e.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,r){let e=t.actions.find(p=>p.inputs?.some(c=>c.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(p=>p.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return m(a,this.adapters).chainInfo}};var it=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new k(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],o=[],{action:p,index:c}=V(t);for(let u=1;u<=t.actions.length;u++){let d=T(t,u);if(!lt(d,t))continue;let{tx:h,chain:y,immediateExecution:W,executable:f}=await this.executeAction(t,u,r,e);h&&i.push(h),y&&(s=y),W&&a.push(W),f&&u===c+1&&f.resolvedInputs&&(o=B(f.resolvedInputs))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:o}}async executeAction(t,r,e,i={}){let s=T(t,r);if(s.type==="link")return s.when&&!await this.evaluateWhenCondition(t,s,e,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let c=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(c):mt.open(c,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});let a=await this.factory.createExecutable(t,r,e,i);if(s.when&&!await this.evaluateWhenCondition(t,s,e,i,a.resolvedInputs,a.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(s.type==="collect"){let c=await this.executeCollect(a);return c.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):c.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(c.output._DATA),result:c}),{tx:null,chain:null,immediateExecution:null,executable:a})}if(s.type==="mcp"){let c=await this.executeMcp(a);return c.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):c.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(c.output._DATA),result:c}),{tx:null,chain:null,immediateExecution:c,executable:a})}let o=m(a.chain.name,this.adapters);if(s.type==="query"){let c=await o.executor.executeQuery(a);return c.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:c,tx:null})):this.handlers?.onError?.({message:JSON.stringify(c.output._DATA),result:c}),{tx:null,chain:a.chain,immediateExecution:c,executable:a}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=m(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,o)=>{if(!lt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let p=r[o],c=o+1;if(!p){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,c),h={status:"error",warp:t,action:c,user:S(this.config,e.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 ${c} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,c,p);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:c,chain:e,execution:u,tx:p})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else{let a=s.find(o=>o.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s)}`,result:a}))}}async executeCollect(t,r){let e=S(this.config,t.chain.name),i=T(t.warp,t.action),s=this.factory.getSerializer(),a=Z(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,e,a,r);let{values:o,output:p}=await Y(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",o,p)}async doHttpRequest(t,r,e,i,s){let a=new b(this.config,m(t.chain.name,this.adapters),this.adapters),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:d,nonce:h,expiresAt:y}=await ft(e,`${t.chain.name}-adapter`),W=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:d,chain:t.chain}));if(W){let f=gt(e,W,h,y);Object.entries(f).forEach(([v,A])=>o.set(v,A))}}r.headers&&Object.entries(r.headers).forEach(([d,h])=>{let y=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(d,y)});let p=r.method||"GET",c=p==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());x.debug("WarpExecutor: Executing HTTP collect",{url:u,method:p,headers:o,body:c});try{let h=await fetch(u,{method:p,headers:o,body:c});x.debug("Collect response status",{status:h.status}),h.status===402&&(h=await Bt(h,u,p,c,this.adapters));let y=await h.json();x.debug("Collect response content",{content:y});let{values:W,output:f}=await Y(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),h.ok?"success":"error",W,f,y)}catch(d){x.error("WarpActionExecutor: Error executing collect",d);let h=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:d},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(e=>e.input.position==="receiver"||e.input.position==="destination")?.value||t.destination}async executeMcp(t,r){let e=S(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let y=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,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:y}}let s,a;try{s=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,a=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let W=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}let o=this.factory.getSerializer(),p=new b(this.config,m(t.chain.name,this.adapters),this.adapters),c=i.destination,u=p.applyInputs(c.url,t.resolvedInputs,this.factory.getSerializer()),d=p.applyInputs(c.tool,t.resolvedInputs,this.factory.getSerializer()),h={};c.headers&&Object.entries(c.headers).forEach(([y,W])=>{let f=p.applyInputs(W,t.resolvedInputs,this.factory.getSerializer());h[y]=f}),x.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let y=new a(new URL(u),{requestInit:{headers:h}}),W=new s({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await W.connect(y);let f={};t.resolvedInputs.forEach(({input:C,value:M})=>{if(M&&C.position&&typeof C.position=="string"&&C.position.startsWith("payload:")){let q=C.position.replace("payload:",""),[P,O]=o.stringToNative(M);if(P==="string")f[q]=String(O);else if(P==="bool")f[q]=!!O;else if(P==="uint8"||P==="uint16"||P==="uint32"||P==="uint64"||P==="uint128"||P==="uint256"||P==="biguint"){let J=Number(O);f[q]=(Number.isInteger(J),J)}else f[q]=O}}),r&&Object.assign(f,r);let v=await W.callTool({name:d,arguments:f});await W.close();let A;if(v.content&&v.content.length>0){let C=v.content[0];if(C.type==="text")try{A=JSON.parse(C.text)}catch{A=C.text}else C.type,A=C}else A=v;let{values:E,output:$}=await Y(t.warp,A,t.action,t.resolvedInputs,o,this.config);return this.buildCollectResult(t,e,"success",E,$,v)}catch(y){x.error("WarpExecutor: Error executing MCP",y);let W=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:y},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}}buildCollectResult(t,r,e,i,s,a){let o=Tt(this.config,this.adapters,t.warp,t.action,s),p=B(t.resolvedInputs);return{status:e,warp:t.warp,action:t.action,user:r||S(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:St(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:p}}async callHandler(t){if(t)return await t()}async evaluateWhenCondition(t,r,e,i,s,a){if(!r.when)return!0;let o=a?{name:a}:await this.factory.getChainInfoForWarp(t,e),p=m(o.name,this.adapters),c=new b(this.config,p,this.adapters),{action:u}=V(t),d=this.factory.getStringTypedInputs(u,e),h=await this.factory.getResolvedInputs(o.name,u,d,c),y=await this.factory.getModifiedInputs(h),W;if(s)W=s;else{let A=await this.factory.getResolvedInputs(o.name,r,this.factory.getStringTypedInputs(r,e),c);W=await this.factory.getModifiedInputs(A)}let f=c.buildInputBag(W,this.factory.getSerializer(),y),v=xt(r.when,f);return Ct(v)}};var at=class{constructor(t){this.config=t}async search(t,r,e){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}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw x.error("WarpIndex: Error searching for warps: ",i),i}}};var st=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!G(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),o=a.length>0,p=a.map(c=>({url:c.url,warp:c.warp}));return{match:o,output:p}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?G(t):R(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,p=null,c=null,u=m(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?wt(t):It(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let f=await u.registry.getInfoByHash(a,r);p=f.registryInfo,c=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(a,r);p=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,r))}if(o&&o.meta&&(le(o,u.chainInfo.name,p,i.identifier),o.meta.query=d),!o)return e;let h=o.chain||u.chainInfo.name,y=m(h,this.adapters),W=await new b(this.config,y,this.adapters).apply(o);return{match:!0,url:t,warp:W,chain:h,registryInfo:p,brand:c}}catch(s){return x.error("Error detecting warp link",s),e}}},le=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?ut(t,"alias",r.alias):ut(t,"hash",r?.hash??e))};var Ht=class{constructor(t,r){this.config=t;this.options=r;this.chains=r.chains.map(e=>e(this.config))}getConfig(){return this.config}createExecutor(t){return new it(this.config,this.chains,t)}async detectWarp(t,r){return new st(this.config,this.chains).detect(t,r)}async executeWarp(t,r,e,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),o=s?t:null;if(!o&&a){let W=await fetch(t);if(!W.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await W.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let p=this.createExecutor(e),{txs:c,chain:u,immediateExecutions:d,resolvedInputs:h}=await p.execute(o,r,{queries:i.queries});return{txs:c,chain:u,immediateExecutions:d,evaluateOutput:async W=>{await p.evaluateOutput(o,W)},resolvedInputs:h}}async createInscriptionTransaction(t,r){return await m(t,this.chains).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return m(t,this.chains).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=R(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return m(e.chain,this.chains).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return m(t,this.chains).wallet.signMessage(r)}async getActions(t,r,e=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(t){return m(t,this.chains).explorer}getOutput(t){return m(t,this.chains).output}async getRegistry(t){let r=m(t,this.chains).registry;return await r.init(),r}getDataLoader(t){return m(t,this.chains).dataLoader}getWallet(t){return m(t,this.chains).wallet}get factory(){return new k(this.config,this.chains)}get index(){return new at(this.config)}get linkBuilder(){return new L(this.config,this.chains)}createBuilder(t){return m(t,this.chains).builder()}createAbiBuilder(t){return m(t,this.chains).abiBuilder()}createBrandBuilder(t){return m(t,this.chains).brandBuilder()}createSerializer(t){return m(t,this.chains).serializer}resolveText(t){return Q(t,this.config)}};var Nt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,getWarpWalletProviderId,getWarpWalletProviderIdFromConfig,getWarpWalletProviderIdFromConfigOrFail,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isWarpActionAutoExecute,isWarpI18nText,mergeNestedPayload,option,parseOutputOutIndex,parseSignedMessage,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveWarpText,safeWindow,setCryptoProvider,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateSignedMessage,vector,withAdapter});
1
+ "use strict";var ur=Object.create;var ot=Object.defineProperty;var dr=Object.getOwnPropertyDescriptor;var fr=Object.getOwnPropertyNames;var gr=Object.getPrototypeOf,hr=Object.prototype.hasOwnProperty;var mr=(n,t)=>{for(var r in t)ot(n,r,{get:t[r],enumerable:!0})},Lt=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of fr(t))!hr.call(n,i)&&i!==r&&ot(n,i,{get:()=>t[i],enumerable:!(e=dr(t,i))||e.enumerable});return n};var z=(n,t,r)=>(r=n!=null?ur(gr(n)):{},Lt(t||!n||!n.__esModule?ot(r,"default",{value:n,enumerable:!0}):r,n)),yr=n=>Lt(ot({},"__esModule",{value:!0}),n);var ue={};mr(ue,{BrowserCryptoProvider:()=>pt,CacheTtl:()=>Ft,NodeCryptoProvider:()=>ct,WARP_LANGUAGES:()=>Pr,WarpBrandBuilder:()=>Vt,WarpBuilder:()=>Ot,WarpCache:()=>nt,WarpCacheKey:()=>ht,WarpChainName:()=>Dt,WarpClient:()=>Ht,WarpConfig:()=>F,WarpConstants:()=>l,WarpExecutor:()=>it,WarpFactory:()=>k,WarpIndex:()=>at,WarpInputTypes:()=>g,WarpInterpolator:()=>b,WarpLinkBuilder:()=>L,WarpLinkDetecter:()=>st,WarpLogger:()=>x,WarpProtocolVersions:()=>U,WarpSerializer:()=>w,WarpTypeRegistry:()=>Nt,WarpValidator:()=>tt,address:()=>ee,applyOutputToMessages:()=>St,asset:()=>$t,biguint:()=>te,bool:()=>re,buildMappedOutput:()=>Z,buildNestedPayload:()=>zt,bytesToBase64:()=>Cr,bytesToHex:()=>kt,cleanWarpIdentifier:()=>X,createAuthHeaders:()=>gt,createAuthMessage:()=>ft,createCryptoProvider:()=>Ir,createDefaultWalletProvider:()=>Gr,createHttpAuthHeaders:()=>Ur,createSignableMessage:()=>Kt,createWarpI18nText:()=>br,createWarpIdentifier:()=>ut,evaluateOutputCommon:()=>Jt,evaluateWhenCondition:()=>Ct,extractCollectOutput:()=>Y,extractIdentifierInfoFromUrl:()=>G,extractQueryStringFromIdentifier:()=>It,extractQueryStringFromUrl:()=>wt,extractResolvedInputValues:()=>B,extractWarpSecrets:()=>Sr,findWarpAdapterForChain:()=>m,getCryptoProvider:()=>yt,getEventNameFromWarp:()=>vr,getLatestProtocolIdentifier:()=>_,getNextInfo:()=>Tt,getProviderConfig:()=>Nr,getRandomBytes:()=>Wt,getRandomHex:()=>vt,getWalletFromConfigOrFail:()=>Dr,getWarpActionByIndex:()=>T,getWarpBrandLogoUrl:()=>Ar,getWarpInfoFromIdentifier:()=>R,getWarpPrimaryAction:()=>V,getWarpWalletAddress:()=>Qt,getWarpWalletAddressFromConfig:()=>S,getWarpWalletMnemonic:()=>Zt,getWarpWalletMnemonicFromConfig:()=>Mr,getWarpWalletPrivateKey:()=>Xt,getWarpWalletPrivateKeyFromConfig:()=>kr,getWarpWalletProviderId:()=>Yt,getWarpWalletProviderIdFromConfig:()=>tr,getWarpWalletProviderIdFromConfigOrFail:()=>qr,handleX402Payment:()=>Bt,hasInputPrefix:()=>$r,hex:()=>ne,initializeWalletCache:()=>zr,isEqualWarpIdentifier:()=>Er,isWarpActionAutoExecute:()=>lt,isWarpI18nText:()=>Tr,mergeNestedPayload:()=>bt,option:()=>ie,parseOutputOutIndex:()=>_t,parseSignedMessage:()=>Lr,replacePlaceholders:()=>H,replacePlaceholdersInWhenExpression:()=>xt,resolveWarpText:()=>Q,safeWindow:()=>mt,setCryptoProvider:()=>xr,shiftBigintBy:()=>K,splitInput:()=>dt,string:()=>Kr,struct:()=>se,testCryptoAvailability:()=>wr,toInputPayloadValue:()=>Gt,toPreviewText:()=>At,tuple:()=>ae,uint16:()=>Xr,uint32:()=>Zr,uint64:()=>Yr,uint8:()=>Qr,validateSignedMessage:()=>jr,vector:()=>oe,withAdapterFallback:()=>Wr});module.exports=yr(ue);var Dt=(u=>(u.Multiversx="multiversx",u.Vibechain="vibechain",u.Sui="sui",u.Ethereum="ethereum",u.Base="base",u.Arbitrum="arbitrum",u.Somnia="somnia",u.Fastset="fastset",u.Solana="solana",u.Near="near",u))(Dt||{}),l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:n=>{if(!n.adapter.wallet)return null;try{return n.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},g={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},mt=typeof window<"u"?window:{open:()=>{}};var U={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},F={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${U.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${U.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="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 Wr=(n,t)=>(r,e)=>{let i=t(r,e);return n(r,i)};var vr=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!r.trigger.startsWith(e))return null;let i=r.trigger.replace(e,"");return i||null};var Ar=(n,t)=>typeof n.logo=="string"?n.logo:n.logo[t?.scheme??"light"];var pt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let r=new Uint8Array(t);return window.crypto.getRandomValues(r),r}},ct=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let r=await import("crypto");return new Uint8Array(r.randomBytes(t))}catch(r){throw new Error(`Node.js crypto not available: ${r instanceof Error?r.message:"Unknown error"}`)}}},j=null;function yt(){if(j)return j;if(typeof window<"u"&&window.crypto)return j=new pt,j;if(typeof process<"u"&&process.versions?.node)return j=new ct,j;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function xr(n){j=n}async function Wt(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||yt()).getRandomBytes(n)}function kt(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(n.length*2);for(let r=0;r<n.length;r++){let e=n[r];t[r*2]=(e>>>4).toString(16),t[r*2+1]=(e&15).toString(16)}return t.join("")}function Cr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(n).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(n));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function vt(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await Wt(n/2,t);return kt(r)}async function wr(){let n={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?n.environment="browser":typeof process<"u"&&process.versions?.node&&(n.environment="nodejs"),await Wt(16),n.randomBytes=!0}catch{}return n}function Ir(){return yt()}var Sr=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let r=t.replace(`${l.Vars.Env}:`,"").trim(),[e,i]=r.split(l.ArgCompositeSeparator);return{key:e,description:i||null}});var m=(n,t)=>{let r=t.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},_=n=>{if(n==="warp")return`warp:${U.Warp}`;if(n==="brand")return`brand:${U.Brand}`;if(n==="abi")return`abi:${U.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},T=(n,t)=>n?.actions[t-1],V=n=>{if(n.actions.length===0)throw new Error(`Warp has no primary action: ${n.meta?.identifier}`);let t=n.actions.find(s=>s.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let r=["transfer","contract","query","collect","mcp"],e=n.actions.find(s=>r.includes(s.type));return e?{action:e,index:n.actions.indexOf(e)}:{action:n.actions[0],index:0}},lt=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=V(t);return n===r}return!0},K=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(s,"0"));if(t<0){let a=e+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},At=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},H=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),xt=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>{let i=t[e];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Ct=n=>{if(!n||typeof n!="string")return!0;try{return!!new Function(`return ${n}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${n}. Error: ${t}`)}};var Pr={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},Q=(n,t)=>{let r=t?.preferences?.locale||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(r in n)return n[r];if("en"in n)return n.en;let e=Object.keys(n);if(e.length>0)return n[e[0]]}return""},Tr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,br=n=>n;var X=n=>n.startsWith(l.IdentifierAliasMarker)?n.replace(l.IdentifierAliasMarker,""):n,Er=(n,t)=>!n||!t?!1:X(n)===X(t),ut=(n,t,r)=>{let e=X(r);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+n+l.IdentifierParamSeparator+e:n+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+e},R=n=>{let t=decodeURIComponent(n).trim(),r=X(t),e=r.split("?")[0],i=Mt(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:r,identifierBase:e};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,o]=i;if(a===l.IdentifierType.Alias||a===l.IdentifierType.Hash){let p=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:p,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===l.IdentifierType.Alias||s===l.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:l.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==l.IdentifierType.Alias&&s!==l.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,p=Rr(a,s)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:s,type:p,identifier:o,identifierBase:a}}}return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:r,identifierBase:e}},G=n=>{let t=new URL(n),e=t.searchParams.get(l.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return R(i)},Rr=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Br=n=>{let t=l.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},Mt=n=>{let t=Br(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=Mt(s);return[i,...a]},wt=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(l.IdentifierParamName),r.toString()||null}catch{return null}},It=n=>{let t=n.indexOf("?");if(t===-1||t===n.length-1)return null;let r=n.substring(t+1);return r.length>0?r:null};var dt=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},$r=n=>{let t=new Set(Object.values(g));if(!n.includes(l.ArgParamsSeparator))return!1;let r=dt(n)[0];return t.has(r)};var St=(n,t,r)=>{let e=Object.entries(n.messages||{}).map(([i,s])=>{let a=Q(s,r);return[i,H(a,t)]});return Object.fromEntries(e)};var qt=z(require("qr-code-styling"),1);var L=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!G(t):!1}build(t,r,e){let i=this.config.clientUrl||F.DefaultClientUrl(this.config.env),s=m(t,this.adapters),a=r===l.IdentifierType.Alias?e:r+l.IdentifierParamSeparator+e,o=s.chainInfo.name+l.IdentifierParamSeparator+a,p=encodeURIComponent(o);return F.SuperClientUrls.includes(i)?`${i}/${p}`:`${i}?${l.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let r=R(t);if(!r)return null;let e=m(r.chain,this.adapters);return e?this.build(e.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,e,i=512,s="white",a="black",o="#23F7DD"){let p=m(t,this.adapters),c=this.build(p.chainInfo.name,r,e);return new qt.default({type:"svg",width:i,height:i,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Vr="https://",Tt=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Vr))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let f=H(a,{...r.vars,...i});return[{identifier:f,url:Pt(t,f,n)}]}let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let f=H(o,{...r.vars,...i}),v=f?`${a}?${f}`:a;return[{identifier:v,url:Pt(t,v,n)}]}let c=p[0];if(!c)return[];let u=c.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 y=p.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let v=o;for(let{regex:E,field:$}of y){let C=$?Or(f,$):f;if(C==null)return null;v=v.replace(E,C)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${a}?${v}`:a;return{identifier:A,url:Pt(t,A,n)}}).filter(f=>f!==null)},Pt=(n,t,r)=>{let[e,i]=t.split("?"),s=R(e)||{chain:l.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=m(s.chain,n);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let o=new L(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let p=new URL(o);return new URLSearchParams(i).forEach((c,u)=>p.searchParams.set(u,c)),p.toString().replace(/\/\?/,"?")},Or=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);var D=class D{static debug(...t){D.isTestEnv||console.debug(...t)}static info(...t){D.isTestEnv||console.info(...t)}static warn(...t){D.isTestEnv||console.warn(...t)}static error(...t){D.isTestEnv||console.error(...t)}};D.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=D;function zt(n,t,r){return n.startsWith(l.Position.Payload)?n.slice(l.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function bt(n,t){if(!n)return{...t};if(!t)return{...n};let r={...n};return Object.keys(t).forEach(e=>{r[e]&&typeof r[e]=="object"&&typeof t[e]=="object"?r[e]=bt(r[e],t[e]):r[e]=t[e]}),r}function Gt(n,t){if(!n.value)return null;let r=t.stringToNative(n.value)[1];if(n.input.type==="biguint")return r.toString();if(n.input.type==="asset"){let{identifier:e,amount:i}=r;return{identifier:e,amount:i.toString()}}else return r}function B(n){return n.map(t=>t.value).filter(t=>t!=null&&t!=="")}function Z(n,t){let r={};return n.forEach(e=>{let i=e.input.as||e.input.name,s=Gt(e,t);if(e.input.position&&typeof e.input.position=="string"&&e.input.position.startsWith(l.Position.Payload)){let a=zt(e.input.position,i,s);r=bt(r,a)}else r[i]=s}),r}var Y=async(n,t,r,e,i,s)=>{let a=[],o=[],p={};for(let[u,d]of Object.entries(n.output||{})){if(d.startsWith(l.Transform.Prefix))continue;let h=_t(d);if(h!==null&&h!==r){p[u]=null;continue}let[y,...W]=d.split("."),f=(v,A)=>A.reduce((E,$)=>E&&E[$]!==void 0?E[$]:null,v);if(y==="out"||y.startsWith("out[")){let v=W.length===0?t?.data||t:f(t,W);a.push(String(v)),o.push(v),p[u]=v}else p[u]=d}let c=Z(e,i);return{values:{string:a,native:o,mapped:c},output:await Jt(n,p,r,e,i,s)}},Jt=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=Fr(a,n,r,e,i),a=await Hr(n,a,s.transform?.runner||null),a},Fr=(n,t,r,e,i)=>{let s={...n},a=T(t,r)?.inputs||[];for(let[o,p]of Object.entries(s))if(typeof p=="string"&&p.startsWith("in.")){let c=p.split(".")[1],u=a.findIndex(h=>h.as===c||h.name===c),d=u!==-1?e[u]?.value:null;s[o]=d?i.stringToNative(d)[1]:null}return s},Hr=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(l.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(l.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:a}of i)try{e[s]=await r.run(a,e)}catch(o){x.error(`Transform error for output '${s}':`,o),e[s]=null}return e},_t=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};var Nr=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};async function Kt(n,t,r,e=5){let i=await vt(64,r),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function ft(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return Kt(n,i,r,5)}function gt(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function Ur(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await ft(n,r,e),o=await t(i);return gt(n,o,s,a)}function jr(n){let t=new Date(n).getTime();return Date.now()<t}function Lr(n){try{let t=JSON.parse(n);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var Dr=(n,t)=>{let r=n.user?.wallets?.[t]||null;if(!r)throw new Error(`No wallet configured for chain ${t}`);return r},Qt=n=>n?typeof n=="string"?n:n.address:null,S=(n,t)=>Qt(n.user?.wallets?.[t]||null),Xt=n=>n?typeof n=="string"?n:n.privateKey||null:null,Zt=n=>n?typeof n=="string"?n:n.mnemonic||null:null,Yt=n=>n?typeof n=="string"?n:n.providerId||null:null,kr=(n,t)=>Xt(n.user?.wallets?.[t]||null)?.trim()||null,Mr=(n,t)=>Zt(n.user?.wallets?.[t]||null)?.trim()||null,tr=(n,t)=>Yt(n.user?.wallets?.[t]||null)?.trim()||null,qr=(n,t)=>{let r=tr(n,t);if(!r)throw new Error(`No provider ID configured for wallet onchain ${t}`);return r};async function zr(n){let t={address:null,publicKey:null};if(!n)return t;try{t.address=await n.getAddress()}catch{}try{t.publicKey=await n.getPublicKey()}catch{}return t}function Gr(n,t,r){return null}var Et=require("@x402/core/client"),Rt=require("@x402/core/http");async function Bt(n,t,r,e,i){let s=await Jr(n,i);if(!s)return n;let a=new Headers;e&&a.set("Content-Type","application/json"),a.set("Accept","application/json"),Object.entries(s).forEach(([p,c])=>{a.set(p,c)}),x.debug("WarpExecutor: Retrying request with payment headers");let o=await fetch(t,{method:r,headers:a,body:e});return x.debug("WarpExecutor: Payment processed, new response status",{status:o.status}),o}var Jr=async(n,t)=>{let r=await _r(n),i=new Rt.x402HTTPClient(new Et.x402Client).getPaymentRequiredResponse(s=>n.headers.get(s),r);if(!i?.accepts?.length)return null;for(let s of t)if(s.wallet.registerX402Handlers)try{let a=new Et.x402Client,o=await s.wallet.registerX402Handlers(a),p=i.accepts.find(h=>h?.network&&o[h.network]);if(!p?.network)continue;o[p.network]();let c=new Rt.x402HTTPClient(a),u=await c.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=c.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return x.debug(`WarpExecutor: x402 payment processed with ${s.chainInfo.name} adapter using ${p.network} scheme`),d}catch{continue}return null},_r=async n=>{try{let t=await n.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===g.Tuple&&Array.isArray(r)){if(r.length===0)return t+l.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(l.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+r.join(l.ArgListSeparator)}if(t===g.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let e=r;if(!e._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=e._name,s=Object.keys(e).filter(o=>o!=="_name");if(s.length===0)return`${t}(${i})${l.ArgParamsSeparator}`;let a=s.map(o=>{let[p,c]=this.getTypeAndValue(e[o]);return`(${o}${l.ArgParamsSeparator}${p})${c}`});return`${t}(${i})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}if(t===g.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${l.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(l.ArgParamsSeparator))){let e=r[0],i=e.indexOf(l.ArgParamsSeparator),s=e.substring(0,i),a=r.map(p=>{let c=p.indexOf(l.ArgParamsSeparator),u=p.substring(c+1);return s.startsWith(g.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),o=s.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+s+l.ArgParamsSeparator+a.join(o)}return t+l.ArgParamsSeparator+r.join(l.ArgListSeparator)}if(t===g.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?g.Asset+l.ArgParamsSeparator+r.identifier+l.ArgCompositeSeparator+String(r.amount)+l.ArgCompositeSeparator+String(r.decimals):g.Asset+l.ArgParamsSeparator+r.identifier+l.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let e=this.typeRegistry.getHandler(t);if(e)return e.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+l.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(l.ArgParamsSeparator),e=r[0],i=r.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e===g.Option){let[s,a]=i.split(l.ArgParamsSeparator);return[g.Option+l.ArgParamsSeparator+s,a||null]}if(e===g.Vector){let s=i.indexOf(l.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),p=a.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(o?o.split(p):[]).map(d=>this.stringToNative(a+l.ArgParamsSeparator+d)[1]);return[g.Vector+l.ArgParamsSeparator+a,u]}else if(e.startsWith(g.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=i.split(l.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${s[c]}${l.IdentifierParamSeparator}${p}`)[1]);return[e,o]}else if(e.startsWith(g.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:s[1]};return i&&i.split(l.ArgListSeparator).forEach(p=>{let c=p.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(c){let[,u,d,h]=c;o[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[1]}}),[e,o]}else{if(e===g.String)return[e,i];if(e===g.Uint8||e===g.Uint16||e===g.Uint32)return[e,Number(i)];if(e===g.Uint64||e===g.Uint128||e===g.Uint256||e===g.Biguint)return[e,BigInt(i||0)];if(e===g.Bool)return[e,i==="true"];if(e===g.Address)return[e,i];if(e===g.Hex)return[e,i];if(e===g.Asset){let[s,a]=i.split(l.ArgCompositeSeparator),o={identifier:s,amount:BigInt(a)};return[e,o]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let o=s.stringToNative(i);return[e,o]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[o,p]=this.stringToNative(`${a}:${i}`);return[e,p]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[r,e]=t.split(l.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[g.Uint32,t]:typeof t=="bigint"?[g.Uint64,t]:typeof t=="boolean"?[g.Bool,t]:[typeof t,t]}};var Kr=n=>new w().nativeToString(g.String,n),Qr=n=>new w().nativeToString(g.Uint8,n),Xr=n=>new w().nativeToString(g.Uint16,n),Zr=n=>new w().nativeToString(g.Uint32,n),Yr=n=>new w().nativeToString(g.Uint64,n),te=n=>new w().nativeToString(g.Biguint,n),re=n=>new w().nativeToString(g.Bool,n),ee=n=>new w().nativeToString(g.Address,n),$t=n=>new w().nativeToString(g.Asset,n),ne=n=>new w().nativeToString(g.Hex,n),ie=(n,t)=>{if(t===null)return g.Option+l.ArgParamsSeparator;let r=n(t),e=r.indexOf(l.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return g.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+s},ae=(...n)=>new w().nativeToString(g.Tuple,n),se=n=>new w().nativeToString(g.Struct,n),oe=n=>new w().nativeToString(g.Vector,n);var rr=z(require("ajv"),1);var Vt=class{constructor(t){this.pendingBrand={protocol:_("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}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,r){if(!t)throw new Error(`Warp: ${r}`)}ensureWarpText(t,r){if(!t)throw new Error(`Warp: ${r}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||F.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new rr.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var er=z(require("ajv"),1);var tt=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validatePrimaryAction(t)),r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validatePrimaryAction(t){try{let{action:r}=V(t);return r?[]:["Primary action is required"]}catch(r){return[r instanceof Error?r.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),e=t.actions.some(a=>a.type==="query");if(!r&&!e)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||F.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new er.default({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var Ot=class{constructor(t){this.config=t;this.pendingWarp={protocol:_("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}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,r=100){return At(t,r)}ensure(t,r){if(!t)throw new Error(r)}ensureWarpText(t,r){if(!t)throw new Error(r);if(typeof t=="object"&&!t.en)throw new Error(r)}async validate(t){let e=await new tt(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
+ `))}};var rt=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let e=JSON.parse(r,ce);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let i={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,pe))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r?.startsWith(this.prefix)&&localStorage.removeItem(r)}}},nr=new w,pe=(n,t)=>typeof t=="bigint"?nr.nativeToString("biguint",t):t,ce=(n,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?nr.stringToNative(t)[1]:t;var N=class N{get(t){let r=N.cache.get(t);return r?Date.now()>r.expiresAt?(N.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;N.cache.set(t,{value:r,expiresAt:i})}forget(t){N.cache.delete(t)}clear(){N.cache.clear()}};N.cache=new Map;var et=N;var Ft={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},ht={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,Asset:(n,t,r)=>`asset:${n}:${t}:${r}`},nt=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new rt:t==="memory"?new et:typeof window<"u"&&window.localStorage?new rt:new et}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var b=class{constructor(t,r,e){this.config=t;this.adapter=r;this.adapters=e}async apply(t,r={}){let e=this.applyVars(t,r);return await this.applyGlobals(e)}async applyGlobals(t){let r={...t};return r.actions=await Promise.all((r.actions||[]).map(async e=>await this.applyActionGlobals(e))),r=await this.applyRootGlobals(r),r}applyVars(t,r={}){if(!t?.vars)return t;let e=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),s=(a,o)=>{i=i.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o!="string")s(a,o);else if(o.startsWith(l.Vars.Query+l.ArgParamsSeparator)){let p=o.slice(l.Vars.Query.length+1),[c,u]=p.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(c):null,y=r.queries?.[c]||null||d;y&&s(a,y)}else if(o.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let p=o.slice(l.Vars.Env.length+1),[c,u]=p.split(l.ArgCompositeSeparator),h={...this.config.vars,...r.envs}?.[c];h&&s(a,h)}else o===l.Source.UserWallet&&e?s(a,e):s(a,o)}),JSON.parse(i)}async applyRootGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),r=this.replacePlaceholdersWithChain(r,i.Placeholder,e,i.Accessor)}),JSON.parse(r)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),r=this.replacePlaceholdersWithChain(r,i.Placeholder,e,i.Accessor)}),JSON.parse(r)}applyInputs(t,r,e,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(r,e,i);return H(s,a)}applyGlobalsToText(t){if(!Object.values(l.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)||t.includes(`{{${a}:`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString())),s=this.replacePlaceholdersWithChain(s,a.Placeholder,i,a.Accessor)}),s}replacePlaceholdersWithChain(t,r,e,i){let s=new RegExp(`\\{\\{${r}:([^}]+)\\}\\}`,"g");return t.replace(s,(a,o)=>{let p=o.trim().toLowerCase();if(!this.adapters)return a;try{let c=m(p,this.adapters),u={config:this.config,adapter:c},d=i(u);return d!=null?d.toString():a}catch{return a}})}buildInputBag(t,r,e){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);i[a]=String(o)}),e&&e.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);if(i[`primary.${a}`]=String(o),s.input.type==="asset"&&typeof s.input.position=="object"){let p=o;p&&typeof p=="object"&&"identifier"in p&&"amount"in p&&(i[`primary.${a}.token`]=String(p.identifier),i[`primary.${a}.amount`]=String(p.amount))}}),i}};var k=class{constructor(t,r){this.config=t;this.adapters=r;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new nt(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,r,e){let i=this.cache.get(ht.WarpExecutable(t,r||"",e))||[];return B(i)}async createExecutable(t,r,e,i={}){let s=T(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=m(a.name,this.adapters),p=new b(this.config,o,this.adapters),c=await p.apply(t,i),u=T(c,r),{action:d,index:h}=V(c),y=this.getStringTypedInputs(d,e),W=await this.getResolvedInputs(a.name,d,y,p),f=await this.getModifiedInputs(W),v=[],A=[];h===r-1?(v=W,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(a.name,u,e,p),A=await this.getModifiedInputs(v));let E=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,$=this.getDestinationFromAction(u),C=E?this.serializer.stringToNative(E)[1]:$;if(C&&(C=p.applyInputs(C,A,this.serializer,f)),!C&&s.type!=="collect"&&s.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let M=this.getPreparedArgs(u,A);M=M.map(I=>p.applyInputs(I,A,this.serializer,f));let q=A.find(I=>I.input.position==="value")?.value||null,P="value"in u?u.value:null,O=q?.split(l.ArgParamsSeparator)[1]||P||"0",J=p.applyInputs(O,A,this.serializer,f),ir=BigInt(J),ar=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),sr=[...("transfers"in u?u.transfers:[])||[],...ar||[]].map(I=>{let lr=p.applyInputs(I,A,this.serializer,f);return this.serializer.stringToNative(lr)[1]}),or=A.find(I=>I.input.position==="data")?.value,pr="data"in u?u.data||"":null,Ut=or||pr||null,cr=Ut?p.applyInputs(Ut,A,this.serializer,f):null,jt={adapter:o,warp:c,chain:a,action:r,destination:C,args:M,value:ir,transfers:sr,data:cr,resolvedInputs:A};return this.cache.set(ht.WarpExecutable(this.config.env,c.meta?.hash||"",r),jt.resolvedInputs,Ft.OneWeek),jt}async getChainInfoForWarp(t,r){if(t.chain)return m(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let e=t.inputs||[];return r.map((i,s)=>{let a=e[s];return!a||i.includes(l.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(p=>this.preprocessInput(t,p))),o=(p,c)=>{if(p.source==="query"){let u=this.url.searchParams.get(p.name);return u?this.serializer.nativeToString(p.type,u):null}else if(p.source===l.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(p.source==="hidden"){if(p.default===void 0)return null;let u=i?i.applyInputs(String(p.default),[],this.serializer):String(p.default);return this.serializer.nativeToString(p.type,u)}else return a[c]||null};return s.map((p,c)=>{let u=o(p,c),d=p.default!==void 0?i?i.applyInputs(String(p.default),[],this.serializer):String(p.default):void 0;return{input:p,value:u||(d!==void 0?this.serializer.nativeToString(p.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(r=>typeof r.position=="string"&&r.position.startsWith("payload:"))??!1}async resolveActionInputs(t,r,e,i){let s=this.getStringTypedInputs(r,e);return await this.getResolvedInputs(t,r,s,i)}async getModifiedInputs(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];if(i.input.modifier?.startsWith("scale:")){let[,s]=i.input.modifier.split(":");if(isNaN(Number(s))){let a=Number(t.find(c=>c.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let p=K(o,+a);r.push({...i,value:`${i.input.type}:${p}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=K(a,+s);r.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let s=i.input.modifier.substring(l.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let o=this.buildInputContext(t,e,i),p=await a.run(s,o);if(p==null)r.push(i);else{let c=this.serializer.nativeToString(i.input.type,p);r.push({...i,value:c})}}else r.push(i)}return r}buildInputContext(t,r,e){let i={};for(let s=0;s<r;s++){let a=t[s];if(!a.value)continue;let o=a.input.as||a.input.name,[,p]=this.serializer.stringToNative(a.value);if(i[o]=p,a.input.type==="asset"&&typeof p=="object"&&p!==null){let c=p;"identifier"in c&&"amount"in c&&(i[`${o}.token`]=String(c.identifier),i[`${o}.amount`]=String(c.amount),i[`${o}.identifier`]=String(c.identifier))}}if(e&&e.value){let s=e.input.as||e.input.name,[,a]=this.serializer.stringToNative(e.value);if(i[s]=a,e.input.type==="asset"&&typeof a=="object"&&a!==null){let o=a;"identifier"in o&&"amount"in o&&(i[`${s}.token`]=String(o.identifier),i[`${s}.amount`]=String(o.amount),i[`${s}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,r){try{let[e,i]=dt(r),s=m(t,this.adapters);if(e==="asset"){let[a,o,p]=i.split(l.ArgCompositeSeparator);if(p)return r;let c=await s.dataLoader.getAsset(a);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=K(o,c.decimals);return $t({...c,amount:u})}else return r}catch(e){throw x.warn("WarpFactory: Preprocess input failed",e),e}}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,r){let e="args"in t?t.args||[]:[],i=[];return r.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[o,p]=this.serializer.stringToNative(a),c=p;if(!c||typeof c!="object"||!("identifier"in c)||!("amount"in c))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,d=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",c.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",c.amount)})}else if(s.position.startsWith("arg:")){let o=Number(s.position.split(":")[1])-1;i.push({index:o,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;e.length<=s;)e.push(void 0);e[s]=a}),e.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,r){let e=t.actions.find(p=>p.inputs?.some(c=>c.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(p=>p.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return m(a,this.adapters).chainInfo}};var it=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new k(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],o=[],{action:p,index:c}=V(t);for(let u=1;u<=t.actions.length;u++){let d=T(t,u);if(!lt(d,t))continue;let{tx:h,chain:y,immediateExecution:W,executable:f}=await this.executeAction(t,u,r,e);h&&i.push(h),y&&(s=y),W&&a.push(W),f&&u===c+1&&f.resolvedInputs&&(o=B(f.resolvedInputs))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:o}}async executeAction(t,r,e,i={}){let s=T(t,r);if(s.type==="link")return s.when&&!await this.evaluateWhenCondition(t,s,e,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let c=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(c):mt.open(c,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});let a=await this.factory.createExecutable(t,r,e,i);if(s.when&&!await this.evaluateWhenCondition(t,s,e,i,a.resolvedInputs,a.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(s.type==="collect"){let c=await this.executeCollect(a);return c.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):c.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(c.output._DATA),result:c}),{tx:null,chain:null,immediateExecution:null,executable:a})}if(s.type==="mcp"){let c=await this.executeMcp(a);return c.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):c.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(c.output._DATA),result:c}),{tx:null,chain:null,immediateExecution:c,executable:a})}let o=m(a.chain.name,this.adapters);if(s.type==="query"){let c=await o.executor.executeQuery(a);return c.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:c,tx:null})):this.handlers?.onError?.({message:JSON.stringify(c.output._DATA),result:c}),{tx:null,chain:a.chain,immediateExecution:c,executable:a}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=m(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,o)=>{if(!lt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let p=r[o],c=o+1;if(!p){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,c),h={status:"error",warp:t,action:c,user:S(this.config,e.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 ${c} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,c,p);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:c,chain:e,execution:u,tx:p})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else{let a=s.find(o=>o.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s)}`,result:a}))}}async executeCollect(t,r){let e=S(this.config,t.chain.name),i=T(t.warp,t.action),s=this.factory.getSerializer(),a=Z(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,e,a,r);let{values:o,output:p}=await Y(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",o,p)}async doHttpRequest(t,r,e,i,s){let a=new b(this.config,m(t.chain.name,this.adapters),this.adapters),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:d,nonce:h,expiresAt:y}=await ft(e,`${t.chain.name}-adapter`),W=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:d,chain:t.chain}));if(W){let f=gt(e,W,h,y);Object.entries(f).forEach(([v,A])=>o.set(v,A))}}r.headers&&Object.entries(r.headers).forEach(([d,h])=>{let y=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(d,y)});let p=r.method||"GET",c=p==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());x.debug("WarpExecutor: Executing HTTP collect",{url:u,method:p,headers:o,body:c});try{let h=await fetch(u,{method:p,headers:o,body:c});x.debug("Collect response status",{status:h.status}),h.status===402&&(h=await Bt(h,u,p,c,this.adapters));let y=await h.json();x.debug("Collect response content",{content:y});let{values:W,output:f}=await Y(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),h.ok?"success":"error",W,f,y)}catch(d){x.error("WarpActionExecutor: Error executing collect",d);let h=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:d},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(e=>e.input.position==="receiver"||e.input.position==="destination")?.value||t.destination}async executeMcp(t,r){let e=S(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let y=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,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:y}}let s,a;try{s=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,a=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let W=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}let o=this.factory.getSerializer(),p=new b(this.config,m(t.chain.name,this.adapters),this.adapters),c=i.destination,u=p.applyInputs(c.url,t.resolvedInputs,this.factory.getSerializer()),d=p.applyInputs(c.tool,t.resolvedInputs,this.factory.getSerializer()),h={};c.headers&&Object.entries(c.headers).forEach(([y,W])=>{let f=p.applyInputs(W,t.resolvedInputs,this.factory.getSerializer());h[y]=f}),x.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let y=new a(new URL(u),{requestInit:{headers:h}}),W=new s({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await W.connect(y);let f={};t.resolvedInputs.forEach(({input:C,value:M})=>{if(M&&C.position&&typeof C.position=="string"&&C.position.startsWith("payload:")){let q=C.position.replace("payload:",""),[P,O]=o.stringToNative(M);if(P==="string")f[q]=String(O);else if(P==="bool")f[q]=!!O;else if(P==="uint8"||P==="uint16"||P==="uint32"||P==="uint64"||P==="uint128"||P==="uint256"||P==="biguint"){let J=Number(O);f[q]=(Number.isInteger(J),J)}else f[q]=O}}),r&&Object.assign(f,r);let v=await W.callTool({name:d,arguments:f});await W.close();let A;if(v.content&&v.content.length>0){let C=v.content[0];if(C.type==="text")try{A=JSON.parse(C.text)}catch{A=C.text}else C.type,A=C}else A=v;let{values:E,output:$}=await Y(t.warp,A,t.action,t.resolvedInputs,o,this.config);return this.buildCollectResult(t,e,"success",E,$,v)}catch(y){x.error("WarpExecutor: Error executing MCP",y);let W=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:y},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}}buildCollectResult(t,r,e,i,s,a){let o=Tt(this.config,this.adapters,t.warp,t.action,s),p=B(t.resolvedInputs);return{status:e,warp:t.warp,action:t.action,user:r||S(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:St(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:p}}async callHandler(t){if(t)return await t()}async evaluateWhenCondition(t,r,e,i,s,a){if(!r.when)return!0;let o=a?{name:a}:await this.factory.getChainInfoForWarp(t,e),p=m(o.name,this.adapters),c=new b(this.config,p,this.adapters),{action:u}=V(t),d=this.factory.getStringTypedInputs(u,e),h=await this.factory.getResolvedInputs(o.name,u,d,c),y=await this.factory.getModifiedInputs(h),W;if(s)W=s;else{let A=await this.factory.getResolvedInputs(o.name,r,this.factory.getStringTypedInputs(r,e),c);W=await this.factory.getModifiedInputs(A)}let f=c.buildInputBag(W,this.factory.getSerializer(),y),v=xt(r.when,f);return Ct(v)}};var at=class{constructor(t){this.config=t}async search(t,r,e){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}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw x.error("WarpIndex: Error searching for warps: ",i),i}}};var st=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!G(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),o=a.length>0,p=a.map(c=>({url:c.url,warp:c.warp}));return{match:o,output:p}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?G(t):R(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,p=null,c=null,u=m(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?wt(t):It(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let f=await u.registry.getInfoByHash(a,r);p=f.registryInfo,c=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(a,r);p=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,r))}if(o&&o.meta&&(le(o,u.chainInfo.name,p,i.identifier),o.meta.query=d),!o)return e;let h=o.chain||u.chainInfo.name,y=m(h,this.adapters),W=await new b(this.config,y,this.adapters).apply(o);return{match:!0,url:t,warp:W,chain:h,registryInfo:p,brand:c}}catch(s){return x.error("Error detecting warp link",s),e}}},le=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?ut(t,"alias",r.alias):ut(t,"hash",r?.hash??e))};var Ht=class{constructor(t,r){this.config=t;this.options=r;this.chains=r.chains.map(e=>e(this.config))}getConfig(){return this.config}createExecutor(t){return new it(this.config,this.chains,t)}async detectWarp(t,r){return new st(this.config,this.chains).detect(t,r)}async executeWarp(t,r,e,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),o=s?t:null;if(!o&&a){let W=await fetch(t);if(!W.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await W.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let p=this.createExecutor(e),{txs:c,chain:u,immediateExecutions:d,resolvedInputs:h}=await p.execute(o,r,{queries:i.queries});return{txs:c,chain:u,immediateExecutions:d,evaluateOutput:async W=>{await p.evaluateOutput(o,W)},resolvedInputs:h}}async createInscriptionTransaction(t,r){return await m(t,this.chains).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return m(t,this.chains).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=R(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return m(e.chain,this.chains).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return m(t,this.chains).wallet.signMessage(r)}async getActions(t,r,e=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(t){return m(t,this.chains).explorer}getOutput(t){return m(t,this.chains).output}async getRegistry(t){let r=m(t,this.chains).registry;return await r.init(),r}getDataLoader(t){return m(t,this.chains).dataLoader}getWallet(t){return m(t,this.chains).wallet}get factory(){return new k(this.config,this.chains)}get index(){return new at(this.config)}get linkBuilder(){return new L(this.config,this.chains)}createBuilder(t){return m(t,this.chains).builder()}createAbiBuilder(t){return m(t,this.chains).abiBuilder()}createBrandBuilder(t){return m(t,this.chains).brandBuilder()}createSerializer(t){return m(t,this.chains).serializer}resolveText(t){return Q(t,this.config)}};var Nt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,getWarpWalletProviderId,getWarpWalletProviderIdFromConfig,getWarpWalletProviderIdFromConfigOrFail,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isWarpActionAutoExecute,isWarpI18nText,mergeNestedPayload,option,parseOutputOutIndex,parseSignedMessage,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveWarpText,safeWindow,setCryptoProvider,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateSignedMessage,vector,withAdapterFallback});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  var Jt=(u=>(u.Multiversx="multiversx",u.Vibechain="vibechain",u.Sui="sui",u.Ethereum="ethereum",u.Base="base",u.Arbitrum="arbitrum",u.Somnia="somnia",u.Fastset="fastset",u.Solana="solana",u.Near="near",u))(Jt||{}),l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:n=>{if(!n.adapter.wallet)return null;try{return n.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.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"},yt=typeof window<"u"?window:{open:()=>{}};var k={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},H={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${k.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${k.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="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=(n,t)=>(r,e)=>{let i=t(r,e);return n(r,i)};var Tr=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!r.trigger.startsWith(e))return null;let i=r.trigger.replace(e,"");return i||null};var Er=(n,t)=>typeof n.logo=="string"?n.logo:n.logo[t?.scheme??"light"];var st=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let r=new Uint8Array(t);return window.crypto.getRandomValues(r),r}},ot=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let r=await import("crypto");return new Uint8Array(r.randomBytes(t))}catch(r){throw new Error(`Node.js crypto not available: ${r instanceof Error?r.message:"Unknown error"}`)}}},N=null;function Wt(){if(N)return N;if(typeof window<"u"&&window.crypto)return N=new st,N;if(typeof process<"u"&&process.versions?.node)return N=new ot,N;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Br(n){N=n}async function vt(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||Wt()).getRandomBytes(n)}function _t(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(n.length*2);for(let r=0;r<n.length;r++){let e=n[r];t[r*2]=(e>>>4).toString(16),t[r*2+1]=(e&15).toString(16)}return t.join("")}function $r(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(n).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(n));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function At(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await vt(n/2,t);return _t(r)}async function Vr(){let n={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?n.environment="browser":typeof process<"u"&&process.versions?.node&&(n.environment="nodejs"),await vt(16),n.randomBytes=!0}catch{}return n}function Or(){return Wt()}var Nr=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let r=t.replace(`${l.Vars.Env}:`,"").trim(),[e,i]=r.split(l.ArgCompositeSeparator);return{key:e,description:i||null}});var W=(n,t)=>{let r=t.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},K=n=>{if(n==="warp")return`warp:${k.Warp}`;if(n==="brand")return`brand:${k.Brand}`;if(n==="abi")return`abi:${k.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},b=(n,t)=>n?.actions[t-1],O=n=>{if(n.actions.length===0)throw new Error(`Warp has no primary action: ${n.meta?.identifier}`);let t=n.actions.find(s=>s.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let r=["transfer","contract","query","collect","mcp"],e=n.actions.find(s=>r.includes(s.type));return e?{action:e,index:n.actions.indexOf(e)}:{action:n.actions[0],index:0}},pt=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=O(t);return n===r}return!0},Q=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(s,"0"));if(t<0){let a=e+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},xt=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},U=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),Ct=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>{let i=t[e];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),wt=n=>{if(!n||typeof n!="string")return!0;try{return!!new Function(`return ${n}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${n}. Error: ${t}`)}};var Dr={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},X=(n,t)=>{let r=t?.preferences?.locale||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(r in n)return n[r];if("en"in n)return n.en;let e=Object.keys(n);if(e.length>0)return n[e[0]]}return""},kr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,Mr=n=>n;var Z=n=>n.startsWith(l.IdentifierAliasMarker)?n.replace(l.IdentifierAliasMarker,""):n,Gr=(n,t)=>!n||!t?!1:Z(n)===Z(t),ct=(n,t,r)=>{let e=Z(r);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+n+l.IdentifierParamSeparator+e:n+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+e},B=n=>{let t=decodeURIComponent(n).trim(),r=Z(t),e=r.split("?")[0],i=It(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:r,identifierBase:e};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,o]=i;if(a===l.IdentifierType.Alias||a===l.IdentifierType.Hash){let p=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:p,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===l.IdentifierType.Alias||s===l.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:l.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==l.IdentifierType.Alias&&s!==l.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,p=Kt(a,s)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:s,type:p,identifier:o,identifierBase:a}}}return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:r,identifierBase:e}},G=n=>{let t=new URL(n),e=t.searchParams.get(l.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return B(i)},Kt=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Qt=n=>{let t=l.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},It=n=>{let t=Qt(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=It(s);return[i,...a]},St=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(l.IdentifierParamName),r.toString()||null}catch{return null}},Pt=n=>{let t=n.indexOf("?");if(t===-1||t===n.length-1)return null;let r=n.substring(t+1);return r.length>0?r:null};var lt=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},Kr=n=>{let t=new Set(Object.values(g));if(!n.includes(l.ArgParamsSeparator))return!1;let r=lt(n)[0];return t.has(r)};var Tt=(n,t,r)=>{let e=Object.entries(n.messages||{}).map(([i,s])=>{let a=X(s,r);return[i,U(a,t)]});return Object.fromEntries(e)};import Xt from"qr-code-styling";var M=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!G(t):!1}build(t,r,e){let i=this.config.clientUrl||H.DefaultClientUrl(this.config.env),s=W(t,this.adapters),a=r===l.IdentifierType.Alias?e:r+l.IdentifierParamSeparator+e,o=s.chainInfo.name+l.IdentifierParamSeparator+a,p=encodeURIComponent(o);return H.SuperClientUrls.includes(i)?`${i}/${p}`:`${i}?${l.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let r=B(t);if(!r)return null;let e=W(r.chain,this.adapters);return e?this.build(e.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,e,i=512,s="white",a="black",o="#23F7DD"){let p=W(t,this.adapters),c=this.build(p.chainInfo.name,r,e);return new Xt({type:"svg",width:i,height:i,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Zt="https://",bt=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Zt))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let f=U(a,{...r.vars,...i});return[{identifier:f,url:ut(t,f,n)}]}let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let f=U(o,{...r.vars,...i}),v=f?`${a}?${f}`:a;return[{identifier:v,url:ut(t,v,n)}]}let c=p[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let m=p.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let v=o;for(let{regex:T,field:R}of m){let x=R?Yt(f,R):f;if(x==null)return null;v=v.replace(T,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${a}?${v}`:a;return{identifier:A,url:ut(t,A,n)}}).filter(f=>f!==null)},ut=(n,t,r)=>{let[e,i]=t.split("?"),s=B(e)||{chain:l.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=W(s.chain,n);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let o=new M(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let p=new URL(o);return new URLSearchParams(i).forEach((c,u)=>p.searchParams.set(u,c)),p.toString().replace(/\/\?/,"?")},Yt=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);var j=class j{static debug(...t){j.isTestEnv||console.debug(...t)}static info(...t){j.isTestEnv||console.info(...t)}static warn(...t){j.isTestEnv||console.warn(...t)}static error(...t){j.isTestEnv||console.error(...t)}};j.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=j;function tr(n,t,r){return n.startsWith(l.Position.Payload)?n.slice(l.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function Et(n,t){if(!n)return{...t};if(!t)return{...n};let r={...n};return Object.keys(t).forEach(e=>{r[e]&&typeof r[e]=="object"&&typeof t[e]=="object"?r[e]=Et(r[e],t[e]):r[e]=t[e]}),r}function rr(n,t){if(!n.value)return null;let r=t.stringToNative(n.value)[1];if(n.input.type==="biguint")return r.toString();if(n.input.type==="asset"){let{identifier:e,amount:i}=r;return{identifier:e,amount:i.toString()}}else return r}function $(n){return n.map(t=>t.value).filter(t=>t!=null&&t!=="")}function Y(n,t){let r={};return n.forEach(e=>{let i=e.input.as||e.input.name,s=rr(e,t);if(e.input.position&&typeof e.input.position=="string"&&e.input.position.startsWith(l.Position.Payload)){let a=tr(e.input.position,i,s);r=Et(r,a)}else r[i]=s}),r}var tt=async(n,t,r,e,i,s)=>{let a=[],o=[],p={};for(let[u,d]of Object.entries(n.output||{})){if(d.startsWith(l.Transform.Prefix))continue;let h=ar(d);if(h!==null&&h!==r){p[u]=null;continue}let[m,...y]=d.split("."),f=(v,A)=>A.reduce((T,R)=>T&&T[R]!==void 0?T[R]:null,v);if(m==="out"||m.startsWith("out[")){let v=y.length===0?t?.data||t:f(t,y);a.push(String(v)),o.push(v),p[u]=v}else p[u]=d}let c=Y(e,i);return{values:{string:a,native:o,mapped:c},output:await er(n,p,r,e,i,s)}},er=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=nr(a,n,r,e,i),a=await ir(n,a,s.transform?.runner||null),a},nr=(n,t,r,e,i)=>{let s={...n},a=b(t,r)?.inputs||[];for(let[o,p]of Object.entries(s))if(typeof p=="string"&&p.startsWith("in.")){let c=p.split(".")[1],u=a.findIndex(h=>h.as===c||h.name===c),d=u!==-1?e[u]?.value:null;s[o]=d?i.stringToNative(d)[1]:null}return s},ir=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(l.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(l.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:a}of i)try{e[s]=await r.run(a,e)}catch(o){C.error(`Transform error for output '${s}':`,o),e[s]=null}return e},ar=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};var ve=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};async function sr(n,t,r,e=5){let i=await At(64,r),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function dt(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return sr(n,i,r,5)}function ft(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function we(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await dt(n,r,e),o=await t(i);return ft(n,o,s,a)}function Ie(n){let t=new Date(n).getTime();return Date.now()<t}function Se(n){try{let t=JSON.parse(n);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var Te=(n,t)=>{let r=n.user?.wallets?.[t]||null;if(!r)throw new Error(`No wallet configured for chain ${t}`);return r},or=n=>n?typeof n=="string"?n:n.address:null,S=(n,t)=>or(n.user?.wallets?.[t]||null),pr=n=>n?typeof n=="string"?n:n.privateKey||null:null,cr=n=>n?typeof n=="string"?n:n.mnemonic||null:null,lr=n=>n?typeof n=="string"?n:n.providerId||null:null,be=(n,t)=>pr(n.user?.wallets?.[t]||null)?.trim()||null,Ee=(n,t)=>cr(n.user?.wallets?.[t]||null)?.trim()||null,ur=(n,t)=>lr(n.user?.wallets?.[t]||null)?.trim()||null,Re=(n,t)=>{let r=ur(n,t);if(!r)throw new Error(`No provider ID configured for wallet onchain ${t}`);return r};async function $e(n){let t={address:null,publicKey:null};if(!n)return t;try{t.address=await n.getAddress()}catch{}try{t.publicKey=await n.getPublicKey()}catch{}return t}function Oe(n,t,r){return null}import{x402Client as Rt}from"@x402/core/client";import{x402HTTPClient as Bt}from"@x402/core/http";async function $t(n,t,r,e,i){let s=await dr(n,i);if(!s)return n;let a=new Headers;e&&a.set("Content-Type","application/json"),a.set("Accept","application/json"),Object.entries(s).forEach(([p,c])=>{a.set(p,c)}),C.debug("WarpExecutor: Retrying request with payment headers");let o=await fetch(t,{method:r,headers:a,body:e});return C.debug("WarpExecutor: Payment processed, new response status",{status:o.status}),o}var dr=async(n,t)=>{let r=await fr(n),i=new Bt(new Rt).getPaymentRequiredResponse(s=>n.headers.get(s),r);if(!i?.accepts?.length)return null;for(let s of t)if(s.wallet.registerX402Handlers)try{let a=new Rt,o=await s.wallet.registerX402Handlers(a),p=i.accepts.find(h=>h?.network&&o[h.network]);if(!p?.network)continue;o[p.network]();let c=new Bt(a),u=await c.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=c.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${s.chainInfo.name} adapter using ${p.network} scheme`),d}catch{continue}return null},fr=async n=>{try{let t=await n.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===g.Tuple&&Array.isArray(r)){if(r.length===0)return t+l.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(l.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+r.join(l.ArgListSeparator)}if(t===g.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let e=r;if(!e._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=e._name,s=Object.keys(e).filter(o=>o!=="_name");if(s.length===0)return`${t}(${i})${l.ArgParamsSeparator}`;let a=s.map(o=>{let[p,c]=this.getTypeAndValue(e[o]);return`(${o}${l.ArgParamsSeparator}${p})${c}`});return`${t}(${i})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}if(t===g.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${l.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(l.ArgParamsSeparator))){let e=r[0],i=e.indexOf(l.ArgParamsSeparator),s=e.substring(0,i),a=r.map(p=>{let c=p.indexOf(l.ArgParamsSeparator),u=p.substring(c+1);return s.startsWith(g.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),o=s.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+s+l.ArgParamsSeparator+a.join(o)}return t+l.ArgParamsSeparator+r.join(l.ArgListSeparator)}if(t===g.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?g.Asset+l.ArgParamsSeparator+r.identifier+l.ArgCompositeSeparator+String(r.amount)+l.ArgCompositeSeparator+String(r.decimals):g.Asset+l.ArgParamsSeparator+r.identifier+l.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let e=this.typeRegistry.getHandler(t);if(e)return e.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+l.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(l.ArgParamsSeparator),e=r[0],i=r.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e===g.Option){let[s,a]=i.split(l.ArgParamsSeparator);return[g.Option+l.ArgParamsSeparator+s,a||null]}if(e===g.Vector){let s=i.indexOf(l.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),p=a.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(o?o.split(p):[]).map(d=>this.stringToNative(a+l.ArgParamsSeparator+d)[1]);return[g.Vector+l.ArgParamsSeparator+a,u]}else if(e.startsWith(g.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=i.split(l.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${s[c]}${l.IdentifierParamSeparator}${p}`)[1]);return[e,o]}else if(e.startsWith(g.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:s[1]};return i&&i.split(l.ArgListSeparator).forEach(p=>{let c=p.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(c){let[,u,d,h]=c;o[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[1]}}),[e,o]}else{if(e===g.String)return[e,i];if(e===g.Uint8||e===g.Uint16||e===g.Uint32)return[e,Number(i)];if(e===g.Uint64||e===g.Uint128||e===g.Uint256||e===g.Biguint)return[e,BigInt(i||0)];if(e===g.Bool)return[e,i==="true"];if(e===g.Address)return[e,i];if(e===g.Hex)return[e,i];if(e===g.Asset){let[s,a]=i.split(l.ArgCompositeSeparator),o={identifier:s,amount:BigInt(a)};return[e,o]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let o=s.stringToNative(i);return[e,o]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[o,p]=this.stringToNative(`${a}:${i}`);return[e,p]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[r,e]=t.split(l.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[g.Uint32,t]:typeof t=="bigint"?[g.Uint64,t]:typeof t=="boolean"?[g.Bool,t]:[typeof t,t]}};var qe=n=>new w().nativeToString(g.String,n),ze=n=>new w().nativeToString(g.Uint8,n),Ge=n=>new w().nativeToString(g.Uint16,n),Je=n=>new w().nativeToString(g.Uint32,n),_e=n=>new w().nativeToString(g.Uint64,n),Ke=n=>new w().nativeToString(g.Biguint,n),Qe=n=>new w().nativeToString(g.Bool,n),Xe=n=>new w().nativeToString(g.Address,n),Vt=n=>new w().nativeToString(g.Asset,n),Ze=n=>new w().nativeToString(g.Hex,n),Ye=(n,t)=>{if(t===null)return g.Option+l.ArgParamsSeparator;let r=n(t),e=r.indexOf(l.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return g.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+s},tn=(...n)=>new w().nativeToString(g.Tuple,n),rn=n=>new w().nativeToString(g.Struct,n),en=n=>new w().nativeToString(g.Vector,n);import gr from"ajv";var Ot=class{constructor(t){this.pendingBrand={protocol:K("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}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,r){if(!t)throw new Error(`Warp: ${r}`)}ensureWarpText(t,r){if(!t)throw new Error(`Warp: ${r}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||H.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new gr,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import hr from"ajv";var rt=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validatePrimaryAction(t)),r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validatePrimaryAction(t){try{let{action:r}=O(t);return r?[]:["Primary action is required"]}catch(r){return[r instanceof Error?r.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),e=t.actions.some(a=>a.type==="query");if(!r&&!e)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||H.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new hr({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var Ft=class{constructor(t){this.config=t;this.pendingWarp={protocol:K("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}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,r=100){return xt(t,r)}ensure(t,r){if(!t)throw new Error(r)}ensureWarpText(t,r){if(!t)throw new Error(r);if(typeof t=="object"&&!t.en)throw new Error(r)}async validate(t){let e=await new rt(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
- `))}};var J=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let e=JSON.parse(r,yr);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let i={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,mr))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r?.startsWith(this.prefix)&&localStorage.removeItem(r)}}},Ht=new w,mr=(n,t)=>typeof t=="bigint"?Ht.nativeToString("biguint",t):t,yr=(n,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?Ht.stringToNative(t)[1]:t;var F=class F{get(t){let r=F.cache.get(t);return r?Date.now()>r.expiresAt?(F.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;F.cache.set(t,{value:r,expiresAt:i})}forget(t){F.cache.delete(t)}clear(){F.cache.clear()}};F.cache=new Map;var _=F;var Nt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},gt={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,Asset:(n,t,r)=>`asset:${n}:${t}:${r}`},et=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new J:t==="memory"?new _:typeof window<"u"&&window.localStorage?new J:new _}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var E=class{constructor(t,r,e){this.config=t;this.adapter=r;this.adapters=e}async apply(t,r={}){let e=this.applyVars(t,r);return await this.applyGlobals(e)}async applyGlobals(t){let r={...t};return r.actions=await Promise.all((r.actions||[]).map(async e=>await this.applyActionGlobals(e))),r=await this.applyRootGlobals(r),r}applyVars(t,r={}){if(!t?.vars)return t;let e=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),s=(a,o)=>{i=i.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o!="string")s(a,o);else if(o.startsWith(l.Vars.Query+l.ArgParamsSeparator)){let p=o.slice(l.Vars.Query.length+1),[c,u]=p.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(c):null,m=r.queries?.[c]||null||d;m&&s(a,m)}else if(o.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let p=o.slice(l.Vars.Env.length+1),[c,u]=p.split(l.ArgCompositeSeparator),h={...this.config.vars,...r.envs}?.[c];h&&s(a,h)}else o===l.Source.UserWallet&&e?s(a,e):s(a,o)}),JSON.parse(i)}async applyRootGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),r=this.replacePlaceholdersWithChain(r,i.Placeholder,e,i.Accessor)}),JSON.parse(r)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),r=this.replacePlaceholdersWithChain(r,i.Placeholder,e,i.Accessor)}),JSON.parse(r)}applyInputs(t,r,e,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(r,e,i);return U(s,a)}applyGlobalsToText(t){if(!Object.values(l.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)||t.includes(`{{${a}:`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString())),s=this.replacePlaceholdersWithChain(s,a.Placeholder,i,a.Accessor)}),s}replacePlaceholdersWithChain(t,r,e,i){let s=new RegExp(`\\{\\{${r}:([^}]+)\\}\\}`,"g");return t.replace(s,(a,o)=>{let p=o.trim().toLowerCase();if(!this.adapters)return a;try{let c=W(p,this.adapters),u={config:this.config,adapter:c},d=i(u);return d!=null?d.toString():a}catch{return a}})}buildInputBag(t,r,e){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);i[a]=String(o)}),e&&e.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);if(i[`primary.${a}`]=String(o),s.input.type==="asset"&&typeof s.input.position=="object"){let p=o;p&&typeof p=="object"&&"identifier"in p&&"amount"in p&&(i[`primary.${a}.token`]=String(p.identifier),i[`primary.${a}.amount`]=String(p.amount))}}),i}};var q=class{constructor(t,r){this.config=t;this.adapters=r;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new et(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,r,e){let i=this.cache.get(gt.WarpExecutable(t,r||"",e))||[];return $(i)}async createExecutable(t,r,e,i={}){let s=b(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=W(a.name,this.adapters),p=new E(this.config,o,this.adapters),c=await p.apply(t,i),u=b(c,r),{action:d,index:h}=O(c),m=this.getStringTypedInputs(d,e),y=await this.getResolvedInputs(a.name,d,m,p),f=await this.getModifiedInputs(y),v=[],A=[];h===r-1?(v=y,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(a.name,u,e,p),A=await this.getModifiedInputs(v));let T=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,R=this.getDestinationFromAction(u),x=T?this.serializer.stringToNative(T)[1]:R;if(x&&(x=p.applyInputs(x,A,this.serializer,f)),!x&&s.type!=="collect"&&s.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let L=this.getPreparedArgs(u,A);L=L.map(I=>p.applyInputs(I,A,this.serializer,f));let D=A.find(I=>I.input.position==="value")?.value||null,P="value"in u?u.value:null,V=D?.split(l.ArgParamsSeparator)[1]||P||"0",z=p.applyInputs(V,A,this.serializer,f),Lt=BigInt(z),Dt=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),kt=[...("transfers"in u?u.transfers:[])||[],...Dt||[]].map(I=>{let Gt=p.applyInputs(I,A,this.serializer,f);return this.serializer.stringToNative(Gt)[1]}),Mt=A.find(I=>I.input.position==="data")?.value,qt="data"in u?u.data||"":null,ht=Mt||qt||null,zt=ht?p.applyInputs(ht,A,this.serializer,f):null,mt={adapter:o,warp:c,chain:a,action:r,destination:x,args:L,value:Lt,transfers:kt,data:zt,resolvedInputs:A};return this.cache.set(gt.WarpExecutable(this.config.env,c.meta?.hash||"",r),mt.resolvedInputs,Nt.OneWeek),mt}async getChainInfoForWarp(t,r){if(t.chain)return W(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let e=t.inputs||[];return r.map((i,s)=>{let a=e[s];return!a||i.includes(l.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(p=>this.preprocessInput(t,p))),o=(p,c)=>{if(p.source==="query"){let u=this.url.searchParams.get(p.name);return u?this.serializer.nativeToString(p.type,u):null}else if(p.source===l.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(p.source==="hidden"){if(p.default===void 0)return null;let u=i?i.applyInputs(String(p.default),[],this.serializer):String(p.default);return this.serializer.nativeToString(p.type,u)}else return a[c]||null};return s.map((p,c)=>{let u=o(p,c),d=p.default!==void 0?i?i.applyInputs(String(p.default),[],this.serializer):String(p.default):void 0;return{input:p,value:u||(d!==void 0?this.serializer.nativeToString(p.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(r=>typeof r.position=="string"&&r.position.startsWith("payload:"))??!1}async resolveActionInputs(t,r,e,i){let s=this.getStringTypedInputs(r,e);return await this.getResolvedInputs(t,r,s,i)}async getModifiedInputs(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];if(i.input.modifier?.startsWith("scale:")){let[,s]=i.input.modifier.split(":");if(isNaN(Number(s))){let a=Number(t.find(c=>c.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let p=Q(o,+a);r.push({...i,value:`${i.input.type}:${p}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=Q(a,+s);r.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let s=i.input.modifier.substring(l.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let o=this.buildInputContext(t,e,i),p=await a.run(s,o);if(p==null)r.push(i);else{let c=this.serializer.nativeToString(i.input.type,p);r.push({...i,value:c})}}else r.push(i)}return r}buildInputContext(t,r,e){let i={};for(let s=0;s<r;s++){let a=t[s];if(!a.value)continue;let o=a.input.as||a.input.name,[,p]=this.serializer.stringToNative(a.value);if(i[o]=p,a.input.type==="asset"&&typeof p=="object"&&p!==null){let c=p;"identifier"in c&&"amount"in c&&(i[`${o}.token`]=String(c.identifier),i[`${o}.amount`]=String(c.amount),i[`${o}.identifier`]=String(c.identifier))}}if(e&&e.value){let s=e.input.as||e.input.name,[,a]=this.serializer.stringToNative(e.value);if(i[s]=a,e.input.type==="asset"&&typeof a=="object"&&a!==null){let o=a;"identifier"in o&&"amount"in o&&(i[`${s}.token`]=String(o.identifier),i[`${s}.amount`]=String(o.amount),i[`${s}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,r){try{let[e,i]=lt(r),s=W(t,this.adapters);if(e==="asset"){let[a,o,p]=i.split(l.ArgCompositeSeparator);if(p)return r;let c=await s.dataLoader.getAsset(a);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=Q(o,c.decimals);return Vt({...c,amount:u})}else return r}catch(e){throw C.warn("WarpFactory: Preprocess input failed",e),e}}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,r){let e="args"in t?t.args||[]:[],i=[];return r.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[o,p]=this.serializer.stringToNative(a),c=p;if(!c||typeof c!="object"||!("identifier"in c)||!("amount"in c))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,d=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",c.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",c.amount)})}else if(s.position.startsWith("arg:")){let o=Number(s.position.split(":")[1])-1;i.push({index:o,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;e.length<=s;)e.push(void 0);e[s]=a}),e.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,r){let e=t.actions.find(p=>p.inputs?.some(c=>c.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(p=>p.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return W(a,this.adapters).chainInfo}};var nt=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new q(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],o=[],{action:p,index:c}=O(t);for(let u=1;u<=t.actions.length;u++){let d=b(t,u);if(!pt(d,t))continue;let{tx:h,chain:m,immediateExecution:y,executable:f}=await this.executeAction(t,u,r,e);h&&i.push(h),m&&(s=m),y&&a.push(y),f&&u===c+1&&f.resolvedInputs&&(o=$(f.resolvedInputs))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:o}}async executeAction(t,r,e,i={}){let s=b(t,r);if(s.type==="link")return s.when&&!await this.evaluateWhenCondition(t,s,e,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let c=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(c):yt.open(c,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});let a=await this.factory.createExecutable(t,r,e,i);if(s.when&&!await this.evaluateWhenCondition(t,s,e,i,a.resolvedInputs,a.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(s.type==="collect"){let c=await this.executeCollect(a);return c.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):c.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(c.output._DATA),result:c}),{tx:null,chain:null,immediateExecution:null,executable:a})}if(s.type==="mcp"){let c=await this.executeMcp(a);return c.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):c.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(c.output._DATA),result:c}),{tx:null,chain:null,immediateExecution:c,executable:a})}let o=W(a.chain.name,this.adapters);if(s.type==="query"){let c=await o.executor.executeQuery(a);return c.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:c,tx:null})):this.handlers?.onError?.({message:JSON.stringify(c.output._DATA),result:c}),{tx:null,chain:a.chain,immediateExecution:c,executable:a}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=W(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,o)=>{if(!pt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let p=r[o],c=o+1;if(!p){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,c),h={status:"error",warp:t,action:c,user:S(this.config,e.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 ${c} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,c,p);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:c,chain:e,execution:u,tx:p})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else{let a=s.find(o=>o.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s)}`,result:a}))}}async executeCollect(t,r){let e=S(this.config,t.chain.name),i=b(t.warp,t.action),s=this.factory.getSerializer(),a=Y(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,e,a,r);let{values:o,output:p}=await tt(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",o,p)}async doHttpRequest(t,r,e,i,s){let a=new E(this.config,W(t.chain.name,this.adapters),this.adapters),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:d,nonce:h,expiresAt:m}=await dt(e,`${t.chain.name}-adapter`),y=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:d,chain:t.chain}));if(y){let f=ft(e,y,h,m);Object.entries(f).forEach(([v,A])=>o.set(v,A))}}r.headers&&Object.entries(r.headers).forEach(([d,h])=>{let m=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(d,m)});let p=r.method||"GET",c=p==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());C.debug("WarpExecutor: Executing HTTP collect",{url:u,method:p,headers:o,body:c});try{let h=await fetch(u,{method:p,headers:o,body:c});C.debug("Collect response status",{status:h.status}),h.status===402&&(h=await $t(h,u,p,c,this.adapters));let m=await h.json();C.debug("Collect response content",{content:m});let{values:y,output:f}=await tt(t.warp,m,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),h.ok?"success":"error",y,f,m)}catch(d){C.error("WarpActionExecutor: Error executing collect",d);let h=$(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:d},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(e=>e.input.position==="receiver"||e.input.position==="destination")?.value||t.destination}async executeMcp(t,r){let e=S(this.config,t.chain.name),i=b(t.warp,t.action);if(!i.destination){let m=$(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let s,a;try{s=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,a=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let y=$(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:y}}let o=this.factory.getSerializer(),p=new E(this.config,W(t.chain.name,this.adapters),this.adapters),c=i.destination,u=p.applyInputs(c.url,t.resolvedInputs,this.factory.getSerializer()),d=p.applyInputs(c.tool,t.resolvedInputs,this.factory.getSerializer()),h={};c.headers&&Object.entries(c.headers).forEach(([m,y])=>{let f=p.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 a(new URL(u),{requestInit:{headers:h}}),y=new s({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(m);let f={};t.resolvedInputs.forEach(({input:x,value:L})=>{if(L&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let D=x.position.replace("payload:",""),[P,V]=o.stringToNative(L);if(P==="string")f[D]=String(V);else if(P==="bool")f[D]=!!V;else if(P==="uint8"||P==="uint16"||P==="uint32"||P==="uint64"||P==="uint128"||P==="uint256"||P==="biguint"){let z=Number(V);f[D]=(Number.isInteger(z),z)}else f[D]=V}}),r&&Object.assign(f,r);let v=await y.callTool({name:d,arguments:f});await y.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:T,output:R}=await tt(t.warp,A,t.action,t.resolvedInputs,o,this.config);return this.buildCollectResult(t,e,"success",T,R,v)}catch(m){C.error("WarpExecutor: Error executing MCP",m);let y=$(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:m},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:y}}}buildCollectResult(t,r,e,i,s,a){let o=bt(this.config,this.adapters,t.warp,t.action,s),p=$(t.resolvedInputs);return{status:e,warp:t.warp,action:t.action,user:r||S(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:Tt(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:p}}async callHandler(t){if(t)return await t()}async evaluateWhenCondition(t,r,e,i,s,a){if(!r.when)return!0;let o=a?{name:a}:await this.factory.getChainInfoForWarp(t,e),p=W(o.name,this.adapters),c=new E(this.config,p,this.adapters),{action:u}=O(t),d=this.factory.getStringTypedInputs(u,e),h=await this.factory.getResolvedInputs(o.name,u,d,c),m=await this.factory.getModifiedInputs(h),y;if(s)y=s;else{let A=await this.factory.getResolvedInputs(o.name,r,this.factory.getStringTypedInputs(r,e),c);y=await this.factory.getModifiedInputs(A)}let f=c.buildInputBag(y,this.factory.getSerializer(),m),v=Ct(r.when,f);return wt(v)}};var it=class{constructor(t){this.config=t}async search(t,r,e){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}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw C.error("WarpIndex: Error searching for warps: ",i),i}}};var at=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!G(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),o=a.length>0,p=a.map(c=>({url:c.url,warp:c.warp}));return{match:o,output:p}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?G(t):B(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,p=null,c=null,u=W(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?St(t):Pt(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let f=await u.registry.getInfoByHash(a,r);p=f.registryInfo,c=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(a,r);p=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,r))}if(o&&o.meta&&(Wr(o,u.chainInfo.name,p,i.identifier),o.meta.query=d),!o)return e;let h=o.chain||u.chainInfo.name,m=W(h,this.adapters),y=await new E(this.config,m,this.adapters).apply(o);return{match:!0,url:t,warp:y,chain:h,registryInfo:p,brand:c}}catch(s){return C.error("Error detecting warp link",s),e}}},Wr=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?ct(t,"alias",r.alias):ct(t,"hash",r?.hash??e))};var Ut=class{constructor(t,r){this.config=t;this.options=r;this.chains=r.chains.map(e=>e(this.config))}getConfig(){return this.config}createExecutor(t){return new nt(this.config,this.chains,t)}async detectWarp(t,r){return new at(this.config,this.chains).detect(t,r)}async executeWarp(t,r,e,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),o=s?t:null;if(!o&&a){let y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await y.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let p=this.createExecutor(e),{txs:c,chain:u,immediateExecutions:d,resolvedInputs:h}=await p.execute(o,r,{queries:i.queries});return{txs:c,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await p.evaluateOutput(o,y)},resolvedInputs:h}}async createInscriptionTransaction(t,r){return await W(t,this.chains).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return W(t,this.chains).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=B(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return W(e.chain,this.chains).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(t,this.chains).wallet.signMessage(r)}async getActions(t,r,e=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(t){return W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getRegistry(t){let r=W(t,this.chains).registry;return await r.init(),r}getDataLoader(t){return W(t,this.chains).dataLoader}getWallet(t){return W(t,this.chains).wallet}get factory(){return new q(this.config,this.chains)}get index(){return new it(this.config)}get linkBuilder(){return new M(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 X(t,this.config)}};var jt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{st as BrowserCryptoProvider,Nt as CacheTtl,ot as NodeCryptoProvider,Dr as WARP_LANGUAGES,Ot as WarpBrandBuilder,Ft as WarpBuilder,et as WarpCache,gt as WarpCacheKey,Jt as WarpChainName,Ut as WarpClient,H as WarpConfig,l as WarpConstants,nt as WarpExecutor,q as WarpFactory,it as WarpIndex,g as WarpInputTypes,E as WarpInterpolator,M as WarpLinkBuilder,at as WarpLinkDetecter,C as WarpLogger,k as WarpProtocolVersions,w as WarpSerializer,jt as WarpTypeRegistry,rt as WarpValidator,Xe as address,Tt as applyOutputToMessages,Vt as asset,Ke as biguint,Qe as bool,Y as buildMappedOutput,tr as buildNestedPayload,$r as bytesToBase64,_t as bytesToHex,Z as cleanWarpIdentifier,ft as createAuthHeaders,dt as createAuthMessage,Or as createCryptoProvider,Oe as createDefaultWalletProvider,we as createHttpAuthHeaders,sr as createSignableMessage,Mr as createWarpI18nText,ct as createWarpIdentifier,er as evaluateOutputCommon,wt as evaluateWhenCondition,tt as extractCollectOutput,G as extractIdentifierInfoFromUrl,Pt as extractQueryStringFromIdentifier,St as extractQueryStringFromUrl,$ as extractResolvedInputValues,Nr as extractWarpSecrets,W as findWarpAdapterForChain,Wt as getCryptoProvider,Tr as getEventNameFromWarp,K as getLatestProtocolIdentifier,bt as getNextInfo,ve as getProviderConfig,vt as getRandomBytes,At as getRandomHex,Te as getWalletFromConfigOrFail,b as getWarpActionByIndex,Er as getWarpBrandLogoUrl,B as getWarpInfoFromIdentifier,O as getWarpPrimaryAction,or as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,cr as getWarpWalletMnemonic,Ee as getWarpWalletMnemonicFromConfig,pr as getWarpWalletPrivateKey,be as getWarpWalletPrivateKeyFromConfig,lr as getWarpWalletProviderId,ur as getWarpWalletProviderIdFromConfig,Re as getWarpWalletProviderIdFromConfigOrFail,$t as handleX402Payment,Kr as hasInputPrefix,Ze as hex,$e as initializeWalletCache,Gr as isEqualWarpIdentifier,pt as isWarpActionAutoExecute,kr as isWarpI18nText,Et as mergeNestedPayload,Ye as option,ar as parseOutputOutIndex,Se as parseSignedMessage,U as replacePlaceholders,Ct as replacePlaceholdersInWhenExpression,X as resolveWarpText,yt as safeWindow,Br as setCryptoProvider,Q as shiftBigintBy,lt as splitInput,qe as string,rn as struct,Vr as testCryptoAvailability,rr as toInputPayloadValue,xt as toPreviewText,tn as tuple,Ge as uint16,Je as uint32,_e as uint64,ze as uint8,Ie as validateSignedMessage,en as vector,Ir as withAdapter};
2
+ `))}};var J=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let e=JSON.parse(r,yr);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let i={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,mr))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r?.startsWith(this.prefix)&&localStorage.removeItem(r)}}},Ht=new w,mr=(n,t)=>typeof t=="bigint"?Ht.nativeToString("biguint",t):t,yr=(n,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?Ht.stringToNative(t)[1]:t;var F=class F{get(t){let r=F.cache.get(t);return r?Date.now()>r.expiresAt?(F.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;F.cache.set(t,{value:r,expiresAt:i})}forget(t){F.cache.delete(t)}clear(){F.cache.clear()}};F.cache=new Map;var _=F;var Nt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},gt={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,Asset:(n,t,r)=>`asset:${n}:${t}:${r}`},et=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new J:t==="memory"?new _:typeof window<"u"&&window.localStorage?new J:new _}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var E=class{constructor(t,r,e){this.config=t;this.adapter=r;this.adapters=e}async apply(t,r={}){let e=this.applyVars(t,r);return await this.applyGlobals(e)}async applyGlobals(t){let r={...t};return r.actions=await Promise.all((r.actions||[]).map(async e=>await this.applyActionGlobals(e))),r=await this.applyRootGlobals(r),r}applyVars(t,r={}){if(!t?.vars)return t;let e=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),s=(a,o)=>{i=i.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o!="string")s(a,o);else if(o.startsWith(l.Vars.Query+l.ArgParamsSeparator)){let p=o.slice(l.Vars.Query.length+1),[c,u]=p.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(c):null,m=r.queries?.[c]||null||d;m&&s(a,m)}else if(o.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let p=o.slice(l.Vars.Env.length+1),[c,u]=p.split(l.ArgCompositeSeparator),h={...this.config.vars,...r.envs}?.[c];h&&s(a,h)}else o===l.Source.UserWallet&&e?s(a,e):s(a,o)}),JSON.parse(i)}async applyRootGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),r=this.replacePlaceholdersWithChain(r,i.Placeholder,e,i.Accessor)}),JSON.parse(r)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString())),r=this.replacePlaceholdersWithChain(r,i.Placeholder,e,i.Accessor)}),JSON.parse(r)}applyInputs(t,r,e,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(r,e,i);return U(s,a)}applyGlobalsToText(t){if(!Object.values(l.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)||t.includes(`{{${a}:`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString())),s=this.replacePlaceholdersWithChain(s,a.Placeholder,i,a.Accessor)}),s}replacePlaceholdersWithChain(t,r,e,i){let s=new RegExp(`\\{\\{${r}:([^}]+)\\}\\}`,"g");return t.replace(s,(a,o)=>{let p=o.trim().toLowerCase();if(!this.adapters)return a;try{let c=W(p,this.adapters),u={config:this.config,adapter:c},d=i(u);return d!=null?d.toString():a}catch{return a}})}buildInputBag(t,r,e){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);i[a]=String(o)}),e&&e.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);if(i[`primary.${a}`]=String(o),s.input.type==="asset"&&typeof s.input.position=="object"){let p=o;p&&typeof p=="object"&&"identifier"in p&&"amount"in p&&(i[`primary.${a}.token`]=String(p.identifier),i[`primary.${a}.amount`]=String(p.amount))}}),i}};var q=class{constructor(t,r){this.config=t;this.adapters=r;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new et(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,r,e){let i=this.cache.get(gt.WarpExecutable(t,r||"",e))||[];return $(i)}async createExecutable(t,r,e,i={}){let s=b(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=W(a.name,this.adapters),p=new E(this.config,o,this.adapters),c=await p.apply(t,i),u=b(c,r),{action:d,index:h}=O(c),m=this.getStringTypedInputs(d,e),y=await this.getResolvedInputs(a.name,d,m,p),f=await this.getModifiedInputs(y),v=[],A=[];h===r-1?(v=y,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(a.name,u,e,p),A=await this.getModifiedInputs(v));let T=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,R=this.getDestinationFromAction(u),x=T?this.serializer.stringToNative(T)[1]:R;if(x&&(x=p.applyInputs(x,A,this.serializer,f)),!x&&s.type!=="collect"&&s.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let L=this.getPreparedArgs(u,A);L=L.map(I=>p.applyInputs(I,A,this.serializer,f));let D=A.find(I=>I.input.position==="value")?.value||null,P="value"in u?u.value:null,V=D?.split(l.ArgParamsSeparator)[1]||P||"0",z=p.applyInputs(V,A,this.serializer,f),Lt=BigInt(z),Dt=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),kt=[...("transfers"in u?u.transfers:[])||[],...Dt||[]].map(I=>{let Gt=p.applyInputs(I,A,this.serializer,f);return this.serializer.stringToNative(Gt)[1]}),Mt=A.find(I=>I.input.position==="data")?.value,qt="data"in u?u.data||"":null,ht=Mt||qt||null,zt=ht?p.applyInputs(ht,A,this.serializer,f):null,mt={adapter:o,warp:c,chain:a,action:r,destination:x,args:L,value:Lt,transfers:kt,data:zt,resolvedInputs:A};return this.cache.set(gt.WarpExecutable(this.config.env,c.meta?.hash||"",r),mt.resolvedInputs,Nt.OneWeek),mt}async getChainInfoForWarp(t,r){if(t.chain)return W(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let e=t.inputs||[];return r.map((i,s)=>{let a=e[s];return!a||i.includes(l.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(p=>this.preprocessInput(t,p))),o=(p,c)=>{if(p.source==="query"){let u=this.url.searchParams.get(p.name);return u?this.serializer.nativeToString(p.type,u):null}else if(p.source===l.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(p.source==="hidden"){if(p.default===void 0)return null;let u=i?i.applyInputs(String(p.default),[],this.serializer):String(p.default);return this.serializer.nativeToString(p.type,u)}else return a[c]||null};return s.map((p,c)=>{let u=o(p,c),d=p.default!==void 0?i?i.applyInputs(String(p.default),[],this.serializer):String(p.default):void 0;return{input:p,value:u||(d!==void 0?this.serializer.nativeToString(p.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(r=>typeof r.position=="string"&&r.position.startsWith("payload:"))??!1}async resolveActionInputs(t,r,e,i){let s=this.getStringTypedInputs(r,e);return await this.getResolvedInputs(t,r,s,i)}async getModifiedInputs(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];if(i.input.modifier?.startsWith("scale:")){let[,s]=i.input.modifier.split(":");if(isNaN(Number(s))){let a=Number(t.find(c=>c.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let p=Q(o,+a);r.push({...i,value:`${i.input.type}:${p}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=Q(a,+s);r.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let s=i.input.modifier.substring(l.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let o=this.buildInputContext(t,e,i),p=await a.run(s,o);if(p==null)r.push(i);else{let c=this.serializer.nativeToString(i.input.type,p);r.push({...i,value:c})}}else r.push(i)}return r}buildInputContext(t,r,e){let i={};for(let s=0;s<r;s++){let a=t[s];if(!a.value)continue;let o=a.input.as||a.input.name,[,p]=this.serializer.stringToNative(a.value);if(i[o]=p,a.input.type==="asset"&&typeof p=="object"&&p!==null){let c=p;"identifier"in c&&"amount"in c&&(i[`${o}.token`]=String(c.identifier),i[`${o}.amount`]=String(c.amount),i[`${o}.identifier`]=String(c.identifier))}}if(e&&e.value){let s=e.input.as||e.input.name,[,a]=this.serializer.stringToNative(e.value);if(i[s]=a,e.input.type==="asset"&&typeof a=="object"&&a!==null){let o=a;"identifier"in o&&"amount"in o&&(i[`${s}.token`]=String(o.identifier),i[`${s}.amount`]=String(o.amount),i[`${s}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,r){try{let[e,i]=lt(r),s=W(t,this.adapters);if(e==="asset"){let[a,o,p]=i.split(l.ArgCompositeSeparator);if(p)return r;let c=await s.dataLoader.getAsset(a);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=Q(o,c.decimals);return Vt({...c,amount:u})}else return r}catch(e){throw C.warn("WarpFactory: Preprocess input failed",e),e}}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,r){let e="args"in t?t.args||[]:[],i=[];return r.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[o,p]=this.serializer.stringToNative(a),c=p;if(!c||typeof c!="object"||!("identifier"in c)||!("amount"in c))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,d=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",c.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",c.amount)})}else if(s.position.startsWith("arg:")){let o=Number(s.position.split(":")[1])-1;i.push({index:o,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;e.length<=s;)e.push(void 0);e[s]=a}),e.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,r){let e=t.actions.find(p=>p.inputs?.some(c=>c.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(p=>p.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return W(a,this.adapters).chainInfo}};var nt=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new q(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],o=[],{action:p,index:c}=O(t);for(let u=1;u<=t.actions.length;u++){let d=b(t,u);if(!pt(d,t))continue;let{tx:h,chain:m,immediateExecution:y,executable:f}=await this.executeAction(t,u,r,e);h&&i.push(h),m&&(s=m),y&&a.push(y),f&&u===c+1&&f.resolvedInputs&&(o=$(f.resolvedInputs))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:o}}async executeAction(t,r,e,i={}){let s=b(t,r);if(s.type==="link")return s.when&&!await this.evaluateWhenCondition(t,s,e,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let c=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(c):yt.open(c,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});let a=await this.factory.createExecutable(t,r,e,i);if(s.when&&!await this.evaluateWhenCondition(t,s,e,i,a.resolvedInputs,a.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(s.type==="collect"){let c=await this.executeCollect(a);return c.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):c.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(c.output._DATA),result:c}),{tx:null,chain:null,immediateExecution:null,executable:a})}if(s.type==="mcp"){let c=await this.executeMcp(a);return c.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):c.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(c.output._DATA),result:c}),{tx:null,chain:null,immediateExecution:c,executable:a})}let o=W(a.chain.name,this.adapters);if(s.type==="query"){let c=await o.executor.executeQuery(a);return c.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:c,tx:null})):this.handlers?.onError?.({message:JSON.stringify(c.output._DATA),result:c}),{tx:null,chain:a.chain,immediateExecution:c,executable:a}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=W(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,o)=>{if(!pt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let p=r[o],c=o+1;if(!p){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,c),h={status:"error",warp:t,action:c,user:S(this.config,e.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 ${c} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,c,p);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:c,chain:e,execution:u,tx:p})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else{let a=s.find(o=>o.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s)}`,result:a}))}}async executeCollect(t,r){let e=S(this.config,t.chain.name),i=b(t.warp,t.action),s=this.factory.getSerializer(),a=Y(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,e,a,r);let{values:o,output:p}=await tt(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",o,p)}async doHttpRequest(t,r,e,i,s){let a=new E(this.config,W(t.chain.name,this.adapters),this.adapters),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:d,nonce:h,expiresAt:m}=await dt(e,`${t.chain.name}-adapter`),y=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:d,chain:t.chain}));if(y){let f=ft(e,y,h,m);Object.entries(f).forEach(([v,A])=>o.set(v,A))}}r.headers&&Object.entries(r.headers).forEach(([d,h])=>{let m=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(d,m)});let p=r.method||"GET",c=p==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());C.debug("WarpExecutor: Executing HTTP collect",{url:u,method:p,headers:o,body:c});try{let h=await fetch(u,{method:p,headers:o,body:c});C.debug("Collect response status",{status:h.status}),h.status===402&&(h=await $t(h,u,p,c,this.adapters));let m=await h.json();C.debug("Collect response content",{content:m});let{values:y,output:f}=await tt(t.warp,m,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),h.ok?"success":"error",y,f,m)}catch(d){C.error("WarpActionExecutor: Error executing collect",d);let h=$(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:d},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(e=>e.input.position==="receiver"||e.input.position==="destination")?.value||t.destination}async executeMcp(t,r){let e=S(this.config,t.chain.name),i=b(t.warp,t.action);if(!i.destination){let m=$(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let s,a;try{s=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,a=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let y=$(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:y}}let o=this.factory.getSerializer(),p=new E(this.config,W(t.chain.name,this.adapters),this.adapters),c=i.destination,u=p.applyInputs(c.url,t.resolvedInputs,this.factory.getSerializer()),d=p.applyInputs(c.tool,t.resolvedInputs,this.factory.getSerializer()),h={};c.headers&&Object.entries(c.headers).forEach(([m,y])=>{let f=p.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 a(new URL(u),{requestInit:{headers:h}}),y=new s({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(m);let f={};t.resolvedInputs.forEach(({input:x,value:L})=>{if(L&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let D=x.position.replace("payload:",""),[P,V]=o.stringToNative(L);if(P==="string")f[D]=String(V);else if(P==="bool")f[D]=!!V;else if(P==="uint8"||P==="uint16"||P==="uint32"||P==="uint64"||P==="uint128"||P==="uint256"||P==="biguint"){let z=Number(V);f[D]=(Number.isInteger(z),z)}else f[D]=V}}),r&&Object.assign(f,r);let v=await y.callTool({name:d,arguments:f});await y.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:T,output:R}=await tt(t.warp,A,t.action,t.resolvedInputs,o,this.config);return this.buildCollectResult(t,e,"success",T,R,v)}catch(m){C.error("WarpExecutor: Error executing MCP",m);let y=$(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:m},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:y}}}buildCollectResult(t,r,e,i,s,a){let o=bt(this.config,this.adapters,t.warp,t.action,s),p=$(t.resolvedInputs);return{status:e,warp:t.warp,action:t.action,user:r||S(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:Tt(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:p}}async callHandler(t){if(t)return await t()}async evaluateWhenCondition(t,r,e,i,s,a){if(!r.when)return!0;let o=a?{name:a}:await this.factory.getChainInfoForWarp(t,e),p=W(o.name,this.adapters),c=new E(this.config,p,this.adapters),{action:u}=O(t),d=this.factory.getStringTypedInputs(u,e),h=await this.factory.getResolvedInputs(o.name,u,d,c),m=await this.factory.getModifiedInputs(h),y;if(s)y=s;else{let A=await this.factory.getResolvedInputs(o.name,r,this.factory.getStringTypedInputs(r,e),c);y=await this.factory.getModifiedInputs(A)}let f=c.buildInputBag(y,this.factory.getSerializer(),m),v=Ct(r.when,f);return wt(v)}};var it=class{constructor(t){this.config=t}async search(t,r,e){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}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw C.error("WarpIndex: Error searching for warps: ",i),i}}};var at=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!G(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),o=a.length>0,p=a.map(c=>({url:c.url,warp:c.warp}));return{match:o,output:p}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?G(t):B(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,p=null,c=null,u=W(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?St(t):Pt(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let f=await u.registry.getInfoByHash(a,r);p=f.registryInfo,c=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(a,r);p=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,r))}if(o&&o.meta&&(Wr(o,u.chainInfo.name,p,i.identifier),o.meta.query=d),!o)return e;let h=o.chain||u.chainInfo.name,m=W(h,this.adapters),y=await new E(this.config,m,this.adapters).apply(o);return{match:!0,url:t,warp:y,chain:h,registryInfo:p,brand:c}}catch(s){return C.error("Error detecting warp link",s),e}}},Wr=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?ct(t,"alias",r.alias):ct(t,"hash",r?.hash??e))};var Ut=class{constructor(t,r){this.config=t;this.options=r;this.chains=r.chains.map(e=>e(this.config))}getConfig(){return this.config}createExecutor(t){return new nt(this.config,this.chains,t)}async detectWarp(t,r){return new at(this.config,this.chains).detect(t,r)}async executeWarp(t,r,e,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),o=s?t:null;if(!o&&a){let y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await y.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let p=this.createExecutor(e),{txs:c,chain:u,immediateExecutions:d,resolvedInputs:h}=await p.execute(o,r,{queries:i.queries});return{txs:c,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await p.evaluateOutput(o,y)},resolvedInputs:h}}async createInscriptionTransaction(t,r){return await W(t,this.chains).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return W(t,this.chains).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=B(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return W(e.chain,this.chains).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(t,this.chains).wallet.signMessage(r)}async getActions(t,r,e=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(t){return W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getRegistry(t){let r=W(t,this.chains).registry;return await r.init(),r}getDataLoader(t){return W(t,this.chains).dataLoader}getWallet(t){return W(t,this.chains).wallet}get factory(){return new q(this.config,this.chains)}get index(){return new it(this.config)}get linkBuilder(){return new M(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 X(t,this.config)}};var jt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{st as BrowserCryptoProvider,Nt as CacheTtl,ot as NodeCryptoProvider,Dr as WARP_LANGUAGES,Ot as WarpBrandBuilder,Ft as WarpBuilder,et as WarpCache,gt as WarpCacheKey,Jt as WarpChainName,Ut as WarpClient,H as WarpConfig,l as WarpConstants,nt as WarpExecutor,q as WarpFactory,it as WarpIndex,g as WarpInputTypes,E as WarpInterpolator,M as WarpLinkBuilder,at as WarpLinkDetecter,C as WarpLogger,k as WarpProtocolVersions,w as WarpSerializer,jt as WarpTypeRegistry,rt as WarpValidator,Xe as address,Tt as applyOutputToMessages,Vt as asset,Ke as biguint,Qe as bool,Y as buildMappedOutput,tr as buildNestedPayload,$r as bytesToBase64,_t as bytesToHex,Z as cleanWarpIdentifier,ft as createAuthHeaders,dt as createAuthMessage,Or as createCryptoProvider,Oe as createDefaultWalletProvider,we as createHttpAuthHeaders,sr as createSignableMessage,Mr as createWarpI18nText,ct as createWarpIdentifier,er as evaluateOutputCommon,wt as evaluateWhenCondition,tt as extractCollectOutput,G as extractIdentifierInfoFromUrl,Pt as extractQueryStringFromIdentifier,St as extractQueryStringFromUrl,$ as extractResolvedInputValues,Nr as extractWarpSecrets,W as findWarpAdapterForChain,Wt as getCryptoProvider,Tr as getEventNameFromWarp,K as getLatestProtocolIdentifier,bt as getNextInfo,ve as getProviderConfig,vt as getRandomBytes,At as getRandomHex,Te as getWalletFromConfigOrFail,b as getWarpActionByIndex,Er as getWarpBrandLogoUrl,B as getWarpInfoFromIdentifier,O as getWarpPrimaryAction,or as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,cr as getWarpWalletMnemonic,Ee as getWarpWalletMnemonicFromConfig,pr as getWarpWalletPrivateKey,be as getWarpWalletPrivateKeyFromConfig,lr as getWarpWalletProviderId,ur as getWarpWalletProviderIdFromConfig,Re as getWarpWalletProviderIdFromConfigOrFail,$t as handleX402Payment,Kr as hasInputPrefix,Ze as hex,$e as initializeWalletCache,Gr as isEqualWarpIdentifier,pt as isWarpActionAutoExecute,kr as isWarpI18nText,Et as mergeNestedPayload,Ye as option,ar as parseOutputOutIndex,Se as parseSignedMessage,U as replacePlaceholders,Ct as replacePlaceholdersInWhenExpression,X as resolveWarpText,yt as safeWindow,Br as setCryptoProvider,Q as shiftBigintBy,lt as splitInput,qe as string,rn as struct,Vr as testCryptoAvailability,rr as toInputPayloadValue,xt as toPreviewText,tn as tuple,Ge as uint16,Je as uint32,_e as uint64,ze as uint8,Ie as validateSignedMessage,en as vector,Ir as withAdapterFallback};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "3.0.0-beta.175",
3
+ "version": "3.0.0-beta.176",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",
@@ -40,7 +40,7 @@
40
40
  "dependencies": {
41
41
  "@x402/core": "^2.0.0",
42
42
  "ajv": "^8.17.1",
43
- "protobufjs": "^7.5.4",
43
+ "protobufjs": "^8.0.0",
44
44
  "qr-code-styling": "^1.9.2"
45
45
  }
46
46
  }