@vleap/warps 3.0.0-beta.167 → 3.0.0-beta.169

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
@@ -362,9 +362,9 @@ type WarpMeta = {
362
362
  creator: string;
363
363
  createdAt: string;
364
364
  };
365
- type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpLinkAction;
365
+ type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpLinkAction | WarpMcpAction;
366
366
  type WarpActionIndex = number;
367
- type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link';
367
+ type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link' | 'mcp';
368
368
  type WarpTransferAction = {
369
369
  type: WarpActionType;
370
370
  label: WarpText;
@@ -437,6 +437,22 @@ type WarpLinkAction = {
437
437
  auto?: boolean;
438
438
  when?: string;
439
439
  };
440
+ type WarpMcpAction = {
441
+ type: WarpActionType;
442
+ label: WarpText;
443
+ description?: WarpText | null;
444
+ destination?: WarpMcpDestination;
445
+ inputs?: WarpActionInput[];
446
+ primary?: boolean;
447
+ auto?: boolean;
448
+ next?: string;
449
+ when?: string;
450
+ };
451
+ type WarpMcpDestination = {
452
+ url: string;
453
+ tool: string;
454
+ headers?: Record<string, string>;
455
+ };
440
456
  type WarpActionInputSource = 'field' | 'query' | 'user:wallet' | 'hidden';
441
457
  type BaseWarpActionInputType = 'string' | 'uint8' | 'uint16' | 'uint32' | 'uint64' | 'uint128' | 'uint256' | 'biguint' | 'bool' | 'address' | 'hex' | string;
442
458
  type WarpActionInputType = string;
@@ -930,6 +946,7 @@ type ExecutionHandlers = {
930
946
  onExecuted?: (result: WarpActionExecutionResult) => void | Promise<void>;
931
947
  onError?: (params: {
932
948
  message: string;
949
+ result: WarpActionExecutionResult;
933
950
  }) => void;
934
951
  onSignRequest?: (params: {
935
952
  message: string;
@@ -976,6 +993,7 @@ declare class WarpExecutor {
976
993
  private executeCollect;
977
994
  private doHttpRequest;
978
995
  private getDestinationFromResolvedInputs;
996
+ private executeMcp;
979
997
  private buildCollectResult;
980
998
  private callHandler;
981
999
  private evaluateWhenCondition;
@@ -1019,6 +1037,8 @@ declare class WarpFactory {
1019
1037
  getChainInfoForWarp(warp: Warp, inputs?: string[]): Promise<WarpChainInfo>;
1020
1038
  getStringTypedInputs(action: WarpAction, inputs: string[]): string[];
1021
1039
  getResolvedInputs(chain: WarpChain, action: WarpAction, inputArgs: string[], interpolator?: WarpInterpolator): Promise<ResolvedInput[]>;
1040
+ private requiresPayloadInputs;
1041
+ private resolveActionInputs;
1022
1042
  getModifiedInputs(inputs: ResolvedInput[]): Promise<ResolvedInput[]>;
1023
1043
  /**
1024
1044
  * Builds a context object containing all previous evaluated inputs for use in transform modifiers.
@@ -1174,4 +1194,4 @@ declare class WarpValidator {
1174
1194
  private validateSchema;
1175
1195
  }
1176
1196
 
1177
- export { type Adapter, type AdapterFactory, 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 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 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 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, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, 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 };
1197
+ export { type Adapter, type AdapterFactory, 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 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 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, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, 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 };
package/dist/index.d.ts CHANGED
@@ -362,9 +362,9 @@ type WarpMeta = {
362
362
  creator: string;
363
363
  createdAt: string;
364
364
  };
365
- type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpLinkAction;
365
+ type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpLinkAction | WarpMcpAction;
366
366
  type WarpActionIndex = number;
367
- type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link';
367
+ type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link' | 'mcp';
368
368
  type WarpTransferAction = {
369
369
  type: WarpActionType;
370
370
  label: WarpText;
@@ -437,6 +437,22 @@ type WarpLinkAction = {
437
437
  auto?: boolean;
438
438
  when?: string;
439
439
  };
440
+ type WarpMcpAction = {
441
+ type: WarpActionType;
442
+ label: WarpText;
443
+ description?: WarpText | null;
444
+ destination?: WarpMcpDestination;
445
+ inputs?: WarpActionInput[];
446
+ primary?: boolean;
447
+ auto?: boolean;
448
+ next?: string;
449
+ when?: string;
450
+ };
451
+ type WarpMcpDestination = {
452
+ url: string;
453
+ tool: string;
454
+ headers?: Record<string, string>;
455
+ };
440
456
  type WarpActionInputSource = 'field' | 'query' | 'user:wallet' | 'hidden';
441
457
  type BaseWarpActionInputType = 'string' | 'uint8' | 'uint16' | 'uint32' | 'uint64' | 'uint128' | 'uint256' | 'biguint' | 'bool' | 'address' | 'hex' | string;
442
458
  type WarpActionInputType = string;
@@ -930,6 +946,7 @@ type ExecutionHandlers = {
930
946
  onExecuted?: (result: WarpActionExecutionResult) => void | Promise<void>;
931
947
  onError?: (params: {
932
948
  message: string;
949
+ result: WarpActionExecutionResult;
933
950
  }) => void;
934
951
  onSignRequest?: (params: {
935
952
  message: string;
@@ -976,6 +993,7 @@ declare class WarpExecutor {
976
993
  private executeCollect;
977
994
  private doHttpRequest;
978
995
  private getDestinationFromResolvedInputs;
996
+ private executeMcp;
979
997
  private buildCollectResult;
980
998
  private callHandler;
981
999
  private evaluateWhenCondition;
@@ -1019,6 +1037,8 @@ declare class WarpFactory {
1019
1037
  getChainInfoForWarp(warp: Warp, inputs?: string[]): Promise<WarpChainInfo>;
1020
1038
  getStringTypedInputs(action: WarpAction, inputs: string[]): string[];
1021
1039
  getResolvedInputs(chain: WarpChain, action: WarpAction, inputArgs: string[], interpolator?: WarpInterpolator): Promise<ResolvedInput[]>;
1040
+ private requiresPayloadInputs;
1041
+ private resolveActionInputs;
1022
1042
  getModifiedInputs(inputs: ResolvedInput[]): Promise<ResolvedInput[]>;
1023
1043
  /**
1024
1044
  * Builds a context object containing all previous evaluated inputs for use in transform modifiers.
@@ -1174,4 +1194,4 @@ declare class WarpValidator {
1174
1194
  private validateSchema;
1175
1195
  }
1176
1196
 
1177
- export { type Adapter, type AdapterFactory, 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 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 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 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, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, 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 };
1197
+ export { type Adapter, type AdapterFactory, 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 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 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, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, 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 };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var sr=Object.create;var tt=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var pr=Object.getOwnPropertyNames;var cr=Object.getPrototypeOf,lr=Object.prototype.hasOwnProperty;var ur=(n,t)=>{for(var r in t)tt(n,r,{get:t[r],enumerable:!0})},Vt=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of pr(t))!lr.call(n,i)&&i!==r&&tt(n,i,{get:()=>t[i],enumerable:!(e=or(t,i))||e.enumerable});return n};var rt=(n,t,r)=>(r=n!=null?sr(cr(n)):{},Vt(t||!n||!n.__esModule?tt(r,"default",{value:n,enumerable:!0}):r,n)),dr=n=>Vt(tt({},"__esModule",{value:!0}),n);var Yr={};ur(Yr,{BrowserCryptoProvider:()=>et,CacheTtl:()=>Pt,NodeCryptoProvider:()=>nt,WARP_LANGUAGES:()=>Ar,WarpBrandBuilder:()=>bt,WarpBuilder:()=>Tt,WarpCache:()=>_,WarpCacheKey:()=>lt,WarpChainName:()=>Ot,WarpClient:()=>Et,WarpConfig:()=>B,WarpConstants:()=>p,WarpExecutor:()=>X,WarpFactory:()=>j,WarpIndex:()=>Z,WarpInputTypes:()=>f,WarpInterpolator:()=>T,WarpLinkBuilder:()=>U,WarpLinkDetecter:()=>Y,WarpLogger:()=>C,WarpProtocolVersions:()=>N,WarpSerializer:()=>x,WarpTypeRegistry:()=>Rt,WarpValidator:()=>J,address:()=>zr,applyOutputToMessages:()=>xt,asset:()=>St,biguint:()=>kr,bool:()=>qr,buildMappedOutput:()=>G,buildNestedPayload:()=>Ht,bytesToBase64:()=>mr,bytesToHex:()=>Nt,cleanWarpIdentifier:()=>M,createAuthHeaders:()=>ct,createAuthMessage:()=>pt,createCryptoProvider:()=>yr,createHttpAuthHeaders:()=>$r,createSignableMessage:()=>kt,createWarpI18nText:()=>Cr,createWarpIdentifier:()=>at,evaluateOutputCommon:()=>jt,evaluateWhenCondition:()=>yt,extractCollectOutput:()=>ot,extractIdentifierInfoFromUrl:()=>D,extractQueryStringFromIdentifier:()=>At,extractQueryStringFromUrl:()=>vt,extractResolvedInputValues:()=>H,extractWarpSecrets:()=>vr,findWarpAdapterForChain:()=>m,getCryptoProvider:()=>ft,getEventNameFromWarp:()=>fr,getLatestProtocolIdentifier:()=>k,getNextInfo:()=>It,getProviderConfig:()=>Er,getRandomBytes:()=>gt,getRandomHex:()=>ht,getWarpActionByIndex:()=>S,getWarpBrandLogoUrl:()=>gr,getWarpInfoFromIdentifier:()=>b,getWarpPrimaryAction:()=>E,getWarpWalletAddress:()=>qt,getWarpWalletAddressFromConfig:()=>w,getWarpWalletMnemonic:()=>Mt,getWarpWalletMnemonicFromConfig:()=>Fr,getWarpWalletPrivateKey:()=>zt,getWarpWalletPrivateKeyFromConfig:()=>Nr,hasInputPrefix:()=>br,hex:()=>Mr,isEqualWarpIdentifier:()=>Ir,isWarpActionAutoExecute:()=>it,isWarpI18nText:()=>xr,mergeNestedPayload:()=>wt,option:()=>Gr,parseOutputOutIndex:()=>Dt,parseSignedMessage:()=>Or,replacePlaceholders:()=>$,replacePlaceholdersInWhenExpression:()=>Wt,resolveWarpText:()=>z,safeWindow:()=>dt,setCryptoProvider:()=>hr,shiftBigintBy:()=>q,splitInput:()=>st,string:()=>Ur,struct:()=>Qr,testCryptoAvailability:()=>Wr,toInputPayloadValue:()=>Lt,toPreviewText:()=>mt,tuple:()=>Jr,uint16:()=>Lr,uint32:()=>jr,uint64:()=>Dr,uint8:()=>Hr,validateSignedMessage:()=>Vr,vector:()=>Kr});module.exports=dr(Yr);var Ot=(l=>(l.Multiversx="multiversx",l.Vibechain="vibechain",l.Sui="sui",l.Ethereum="ethereum",l.Base="base",l.Arbitrum="arbitrum",l.Somnia="somnia",l.Fastset="fastset",l.Solana="solana",l))(Ot||{}),p={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"}},f={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},dt=typeof window<"u"?window:{open:()=>{}};var N={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},B={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${N.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${N.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",p.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var fr=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=p.Alerts.TriggerEventPrefix+p.ArgParamsSeparator;if(!r.trigger.startsWith(e))return null;let i=r.trigger.replace(e,"");return i||null};var gr=(n,t)=>typeof n.logo=="string"?n.logo:n.logo[t?.scheme??"light"];var et=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}},nt=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"}`)}}},F=null;function ft(){if(F)return F;if(typeof window<"u"&&window.crypto)return F=new et,F;if(typeof process<"u"&&process.versions?.node)return F=new nt,F;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function hr(n){F=n}async function gt(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||ft()).getRandomBytes(n)}function Nt(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 mr(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 ht(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await gt(n/2,t);return Nt(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 gt(16),n.randomBytes=!0}catch{}return n}function yr(){return ft()}var vr=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${p.Vars.Env}:`)).map(t=>{let r=t.replace(`${p.Vars.Env}:`,"").trim(),[e,i]=r.split(p.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},k=n=>{if(n==="warp")return`warp:${N.Warp}`;if(n==="brand")return`brand:${N.Brand}`;if(n==="abi")return`abi:${N.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},S=(n,t)=>n?.actions[t-1],E=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"],e=n.actions.find(s=>r.includes(s.type));return e?{action:e,index:n.actions.indexOf(e)}:{action:n.actions[0],index:0}},it=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=E(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)},mt=(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},$=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),Wt=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>{let i=t[e];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),yt=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 Ar={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"},z=(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""},xr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,Cr=n=>n;var M=n=>n.startsWith(p.IdentifierAliasMarker)?n.replace(p.IdentifierAliasMarker,""):n,Ir=(n,t)=>!n||!t?!1:M(n)===M(t),at=(n,t,r)=>{let e=M(r);return t===p.IdentifierType.Alias?p.IdentifierAliasMarker+n+p.IdentifierParamSeparator+e:n+p.IdentifierParamSeparator+t+p.IdentifierParamSeparator+e},b=n=>{let t=decodeURIComponent(n).trim(),r=M(t),e=r.split("?")[0],i=Ft(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:p.IdentifierChainDefault,type:p.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===p.IdentifierType.Alias||a===p.IdentifierType.Hash){let c=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:c,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===p.IdentifierType.Alias||s===p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:p.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==p.IdentifierType.Alias&&s!==p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,c=wr(a,s)?p.IdentifierType.Hash:p.IdentifierType.Alias;return{chain:s,type:c,identifier:o,identifierBase:a}}}return{chain:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:e}},D=n=>{let t=new URL(n),e=t.searchParams.get(p.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return b(i)},wr=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Sr=n=>{let t=p.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},Ft=n=>{let t=Sr(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=Ft(s);return[i,...a]},vt=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(p.IdentifierParamName),r.toString()||null}catch{return null}},At=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 st=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},br=n=>{let t=new Set(Object.values(f));if(!n.includes(p.ArgParamsSeparator))return!1;let r=st(n)[0];return t.has(r)};var xt=(n,t,r)=>{let e=Object.entries(n.messages||{}).map(([i,s])=>{let a=z(s,r);return[i,$(a,t)]});return Object.fromEntries(e)};var Ut=rt(require("qr-code-styling"),1);var U=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!D(t):!1}build(t,r,e){let i=this.config.clientUrl||B.DefaultClientUrl(this.config.env),s=m(t,this.adapters),a=r===p.IdentifierType.Alias?e:r+p.IdentifierParamSeparator+e,o=s.chainInfo.name+p.IdentifierParamSeparator+a,c=encodeURIComponent(o);return B.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${p.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let r=b(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 c=m(t,this.adapters),l=this.build(c.chainInfo.name,r,e);return new Ut.default({type:"svg",width:i,height:i,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Tr="https://",It=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Tr))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let g=$(a,{...r.vars,...i});return[{identifier:g,url:Ct(t,g,n)}]}let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let g=$(o,{...r.vars,...i}),y=g?`${a}?${g}`:a;return[{identifier:y,url:Ct(t,y,n)}]}let l=c[0];if(!l)return[];let u=l.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let A=c.filter(g=>g.includes(`{{${d}[]`)).map(g=>{let y=g.match(/\[\](\.[^}]+)?}}/),v=y&&y[1]||"";return{placeholder:g,field:v?v.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(g=>{let y=o;for(let{regex:R,field:O}of A){let P=O?Pr(g,O):g;if(P==null)return null;y=y.replace(R,P)}if(y.includes("{{")||y.includes("}}"))return null;let v=y?`${a}?${y}`:a;return{identifier:v,url:Ct(t,v,n)}}).filter(g=>g!==null)},Ct=(n,t,r)=>{let[e,i]=t.split("?"),s=b(e)||{chain:p.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 U(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let c=new URL(o);return new URLSearchParams(i).forEach((l,u)=>c.searchParams.set(u,l)),c.toString().replace(/\/\?/,"?")},Pr=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function Ht(n,t,r){return n.startsWith(p.Position.Payload)?n.slice(p.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function wt(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]=wt(r[e],t[e]):r[e]=t[e]}),r}function Lt(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 H(n){return n.map(t=>t.value).filter(t=>t!=null&&t!=="")}function G(n,t){let r={};return n.forEach(e=>{let i=e.input.as||e.input.name,s=Lt(e,t);if(e.input.position&&typeof e.input.position=="string"&&e.input.position.startsWith(p.Position.Payload)){let a=Ht(e.input.position,i,s);r=wt(r,a)}else r[i]=s}),r}var Er=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};var L=class L{static debug(...t){L.isTestEnv||console.debug(...t)}static info(...t){L.isTestEnv||console.info(...t)}static warn(...t){L.isTestEnv||console.warn(...t)}static error(...t){L.isTestEnv||console.error(...t)}};L.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=L;var ot=async(n,t,r,e,i,s)=>{let a=[],o=[],c={};for(let[u,d]of Object.entries(n.output||{})){if(d.startsWith(p.Transform.Prefix))continue;let h=Dt(d);if(h!==null&&h!==r){c[u]=null;continue}let[A,...W]=d.split("."),g=(y,v)=>v.reduce((R,O)=>R&&R[O]!==void 0?R[O]:null,y);if(A==="out"||A.startsWith("out[")){let y=W.length===0?t?.data||t:g(t,W);a.push(String(y)),o.push(y),c[u]=y}else c[u]=d}let l=G(e,i);return{values:{string:a,native:o,mapped:l},output:await jt(n,c,r,e,i,s)}},jt=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=Rr(a,n,r,e,i),a=await Br(n,a,s.transform?.runner||null),a},Rr=(n,t,r,e,i)=>{let s={...n},a=S(t,r)?.inputs||[];for(let[o,c]of Object.entries(s))if(typeof c=="string"&&c.startsWith("in.")){let l=c.split(".")[1],u=a.findIndex(h=>h.as===l||h.name===l),d=u!==-1?e[u]?.value:null;s[o]=d?i.stringToNative(d)[1]:null}return s},Br=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(p.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(p.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},Dt=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)};async function kt(n,t,r,e=5){let i=await ht(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 pt(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return kt(n,i,r,5)}function ct(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function $r(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await pt(n,r,e),o=await t(i);return ct(n,o,s,a)}function Vr(n){let t=new Date(n).getTime();return Date.now()<t}function Or(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 qt=n=>n?typeof n=="string"?n:n.address:null,w=(n,t)=>qt(n.user?.wallets?.[t]||null),zt=n=>n?typeof n=="string"?n:n.privateKey:null,Mt=n=>n?typeof n=="string"?n:n.mnemonic:null,Nr=(n,t)=>zt(n.user?.wallets?.[t]||null)?.trim()||null,Fr=(n,t)=>Mt(n.user?.wallets?.[t]||null)?.trim()||null;var x=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===f.Tuple&&Array.isArray(r)){if(r.length===0)return t+p.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(p.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(p.ArgCompositeSeparator)})${p.ArgParamsSeparator}${s.join(p.ArgListSeparator)}`}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===f.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})${p.ArgParamsSeparator}`;let a=s.map(o=>{let[c,l]=this.getTypeAndValue(e[o]);return`(${o}${p.ArgParamsSeparator}${c})${l}`});return`${t}(${i})${p.ArgParamsSeparator}${a.join(p.ArgListSeparator)}`}if(t===f.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${p.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(p.ArgParamsSeparator))){let e=r[0],i=e.indexOf(p.ArgParamsSeparator),s=e.substring(0,i),a=r.map(c=>{let l=c.indexOf(p.ArgParamsSeparator),u=c.substring(l+1);return s.startsWith(f.Tuple)?u.replace(p.ArgListSeparator,p.ArgCompositeSeparator):u}),o=s.startsWith(f.Struct)?p.ArgStructSeparator:p.ArgListSeparator;return t+p.ArgParamsSeparator+s+p.ArgParamsSeparator+a.join(o)}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===f.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?f.Asset+p.ArgParamsSeparator+r.identifier+p.ArgCompositeSeparator+String(r.amount)+p.ArgCompositeSeparator+String(r.decimals):f.Asset+p.ArgParamsSeparator+r.identifier+p.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+p.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(p.ArgParamsSeparator),e=r[0],i=r.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e===f.Option){let[s,a]=i.split(p.ArgParamsSeparator);return[f.Option+p.ArgParamsSeparator+s,a||null]}if(e===f.Vector){let s=i.indexOf(p.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),c=a.startsWith(f.Struct)?p.ArgStructSeparator:p.ArgListSeparator,u=(o?o.split(c):[]).map(d=>this.stringToNative(a+p.ArgParamsSeparator+d)[1]);return[f.Vector+p.ArgParamsSeparator+a,u]}else if(e.startsWith(f.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=i.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}${p.IdentifierParamSeparator}${c}`)[1]);return[e,o]}else if(e.startsWith(f.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(p.ArgListSeparator).forEach(c=>{let l=c.match(new RegExp(`^\\(([^${p.ArgParamsSeparator}]+)${p.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(l){let[,u,d,h]=l;o[u]=this.stringToNative(`${d}${p.IdentifierParamSeparator}${h}`)[1]}}),[e,o]}else{if(e===f.String)return[e,i];if(e===f.Uint8||e===f.Uint16||e===f.Uint32)return[e,Number(i)];if(e===f.Uint64||e===f.Uint128||e===f.Uint256||e===f.Biguint)return[e,BigInt(i||0)];if(e===f.Bool)return[e,i==="true"];if(e===f.Address)return[e,i];if(e===f.Hex)return[e,i];if(e===f.Asset){let[s,a]=i.split(p.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,c]=this.stringToNative(`${a}:${i}`);return[e,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(p.ArgParamsSeparator)){let[r,e]=t.split(p.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[f.Uint32,t]:typeof t=="bigint"?[f.Uint64,t]:typeof t=="boolean"?[f.Bool,t]:[typeof t,t]}};var Ur=n=>new x().nativeToString(f.String,n),Hr=n=>new x().nativeToString(f.Uint8,n),Lr=n=>new x().nativeToString(f.Uint16,n),jr=n=>new x().nativeToString(f.Uint32,n),Dr=n=>new x().nativeToString(f.Uint64,n),kr=n=>new x().nativeToString(f.Biguint,n),qr=n=>new x().nativeToString(f.Bool,n),zr=n=>new x().nativeToString(f.Address,n),St=n=>new x().nativeToString(f.Asset,n),Mr=n=>new x().nativeToString(f.Hex,n),Gr=(n,t)=>{if(t===null)return f.Option+p.ArgParamsSeparator;let r=n(t),e=r.indexOf(p.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return f.Option+p.ArgParamsSeparator+i+p.ArgParamsSeparator+s},Jr=(...n)=>new x().nativeToString(f.Tuple,n),Qr=n=>new x().nativeToString(f.Struct,n),Kr=n=>new x().nativeToString(f.Vector,n);var Gt=rt(require("ajv"),1);var bt=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||B.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new Gt.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var Jt=rt(require("ajv"),1);var J=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}=E(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||B.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new Jt.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 Tt=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}async build(){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"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return mt(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 J(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
- `))}};var Q=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,Xr);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,_r))}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)}}},Qt=new x,_r=(n,t)=>typeof t=="bigint"?Qt.nativeToString("biguint",t):t,Xr=(n,t)=>typeof t=="string"&&t.startsWith(f.Biguint+":")?Qt.stringToNative(t)[1]:t;var V=class V{get(t){let r=V.cache.get(t);return r?Date.now()>r.expiresAt?(V.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;V.cache.set(t,{value:r,expiresAt:i})}forget(t){V.cache.delete(t)}clear(){V.cache.clear()}};V.cache=new Map;var K=V;var Pt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},lt={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}`},_=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new Q:t==="memory"?new K:typeof window<"u"&&window.localStorage?new Q:new K}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 T=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=w(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(p.Vars.Query+p.ArgParamsSeparator)){let c=o.slice(p.Vars.Query.length+1),[l,u]=c.split(p.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(l):null,A=r.queries?.[l]||null||d;A&&s(a,A)}else if(o.startsWith(p.Vars.Env+p.ArgParamsSeparator)){let c=o.slice(p.Vars.Env.length+1),[l,u]=c.split(p.ArgCompositeSeparator),h={...this.config.vars,...r.envs}?.[l];h&&s(a,h)}else o===p.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(p.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(p.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 $(s,a)}applyGlobalsToText(t){if(!Object.values(p.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(p.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 c=o.trim().toLowerCase();if(!this.adapters)return a;try{let l=m(c,this.adapters),u={config:this.config,adapter:l},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 c=o;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${a}.token`]=String(c.identifier),i[`primary.${a}.amount`]=String(c.amount))}}),i}};var j=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 x,this.cache=new _(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,r,e){let i=this.cache.get(lt.WarpExecutable(t,r||"",e))||[];return H(i)}async createExecutable(t,r,e,i={}){let s=S(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=m(a.name,this.adapters),c=new T(this.config,o,this.adapters),l=await c.apply(t,i),u=S(l,r),{action:d,index:h}=E(l),A=this.getStringTypedInputs(d,e),W=await this.getResolvedInputs(a.name,d,A,c),g=await this.getModifiedInputs(W),y=[],v=[];h===r-1&&(y=W,v=g);let R=v.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,O=this.getDestinationFromAction(u),P=R?this.serializer.stringToNative(R)[1]:O;if(P&&(P=c.applyInputs(P,v,this.serializer,g)),!P&&s.type!=="collect")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let ut=this.getPreparedArgs(u,v);ut=ut.map(I=>c.applyInputs(I,v,this.serializer,g));let Kt=v.find(I=>I.input.position==="value")?.value||null,_t="value"in u?u.value:null,Xt=Kt?.split(p.ArgParamsSeparator)[1]||_t||"0",Zt=c.applyInputs(Xt,v,this.serializer,g),Yt=BigInt(Zt),tr=v.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),rr=[...("transfers"in u?u.transfers:[])||[],...tr||[]].map(I=>{let ar=c.applyInputs(I,v,this.serializer,g);return this.serializer.stringToNative(ar)[1]}),er=v.find(I=>I.input.position==="data")?.value,nr="data"in u?u.data||"":null,Bt=er||nr||null,ir=Bt?c.applyInputs(Bt,v,this.serializer,g):null,$t={warp:l,chain:a,action:r,destination:P,args:ut,value:Yt,transfers:rr,data:ir,resolvedInputs:v};return this.cache.set(lt.WarpExecutable(this.config.env,l.meta?.hash||"",r),$t.resolvedInputs,Pt.OneWeek),$t}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(p.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(c=>this.preprocessInput(t,c))),o=(c,l)=>{if(c.source==="query"){let u=this.url.searchParams.get(c.name);return u?this.serializer.nativeToString(c.type,u):null}else if(c.source===p.Source.UserWallet){let u=w(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(c.source==="hidden"){if(c.default===void 0)return null;let u=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,u)}else return a[l]||null};return s.map((c,l)=>{let u=o(c,l),d=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:u||(d!==void 0?this.serializer.nativeToString(c.type,d):null)}})}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(l=>l.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let c=q(o,+a);r.push({...i,value:`${i.input.type}:${c}`})}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(p.Transform.Prefix)){let s=i.input.modifier.substring(p.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),c=await a.run(s,o);if(c==null)r.push(i);else{let l=this.serializer.nativeToString(i.input.type,c);r.push({...i,value:l})}}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,[,c]=this.serializer.stringToNative(a.value);if(i[o]=c,a.input.type==="asset"&&typeof c=="object"&&c!==null){let l=c;"identifier"in l&&"amount"in l&&(i[`${o}.token`]=String(l.identifier),i[`${o}.amount`]=String(l.amount),i[`${o}.identifier`]=String(l.identifier))}}if(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]=st(r),s=m(t,this.adapters);if(e==="asset"){let[a,o,c]=i.split(p.ArgCompositeSeparator);if(c)return r;let l=await s.dataLoader.getAsset(a);if(!l)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof l.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=q(o,l.decimals);return St({...l,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,c]=this.serializer.stringToNative(a),l=c;if(!l||typeof l!="object"||!("identifier"in l)||!("amount"in l))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,d=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",l.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",l.amount)})}else if(s.position.startsWith("arg:")){let o=Number(s.position.split(":")[1])-1;i.push({index:o,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;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(c=>c.inputs?.some(l=>l.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(c=>c.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 X=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new j(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],o=[],{action:c,index:l}=E(t);for(let u=1;u<=t.actions.length;u++){let d=S(t,u);if(!it(d,t))continue;let{tx:h,chain:A,immediateExecution:W,executable:g}=await this.executeAction(t,u,r,e);h&&i.push(h),A&&(s=A),W&&a.push(W),g&&u===l+1&&g.resolvedInputs&&(o=H(g.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=S(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 l=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(l):dt.open(l,"_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 l=await this.executeCollect(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:null,immediateExecution:null,executable:a})}let o=m(a.chain.name,this.adapters);if(s.type==="query"){let l=await o.executor.executeQuery(a);return l.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:l,tx:null})):this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:a.chain,immediateExecution:l,executable:a}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,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(!it(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let c=r[o],l=o+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,l),h={status:"error",warp:t,action:l,user:w(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 ${l} failed: Transaction not found`})),h}let u=await i.output.getActionExecution(t,l,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:l,chain:e,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),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 await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s.map(a=>a.values))}`}))}async executeCollect(t,r){let e=w(this.config,t.chain.name),i=S(t.warp,t.action),s=this.factory.getSerializer(),a=G(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:c}=await ot(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",o,c)}async doHttpRequest(t,r,e,i,s){let a=new T(this.config,m(t.chain.name,this.adapters),this.adapters),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:d,nonce:h,expiresAt:A}=await pt(e,`${t.chain.name}-adapter`),W=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:d,chain:t.chain}));if(W){let g=ct(e,W,h,A);Object.entries(g).forEach(([y,v])=>o.set(y,v))}}r.headers&&Object.entries(r.headers).forEach(([d,h])=>{let A=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(d,A)});let c=r.method||"GET",l=c==="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:c,headers:o,body:l});try{let d=await fetch(u,{method:c,headers:o,body:l});C.debug("Collect response status",{status:d.status});let h=await d.json();C.debug("Collect response content",{content:h});let{values:A,output:W}=await ot(t.warp,h,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,w(this.config,t.chain.name),d.ok?"success":"error",A,W,h)}catch(d){C.error("WarpActionExecutor: Error executing collect",d);let h=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}buildCollectResult(t,r,e,i,s,a){let o=It(this.config,this.adapters,t.warp,t.action,s),c=H(t.resolvedInputs);return{status:e,warp:t.warp,action:t.action,user:r||w(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:xt(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}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),c=m(o.name,this.adapters),l=new T(this.config,c,this.adapters),{action:u}=E(t),d=this.factory.getStringTypedInputs(u,e),h=await this.factory.getResolvedInputs(o.name,u,d,l),A=await this.factory.getModifiedInputs(h),W;if(s)W=s;else{let v=await this.factory.getResolvedInputs(o.name,r,this.factory.getStringTypedInputs(r,e),l);W=await this.factory.getModifiedInputs(v)}let g=l.buildInputBag(W,this.factory.getSerializer(),A),y=Wt(r.when,g);return yt(y)}};var Z=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 Y=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!D(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),o=a.length>0,c=a.map(l=>({url:l.url,warp:l.warp}));return{match:o,output:c}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(p.HttpProtocolPrefix)?D(t):b(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,c=null,l=null,u=m(i.chain,this.adapters),d=t.startsWith(p.HttpProtocolPrefix)?vt(t):At(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let g=await u.registry.getInfoByHash(a,r);c=g.registryInfo,l=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,r);c=g.registryInfo,l=g.brand,g.registryInfo&&(o=await u.builder().createFromTransactionHash(g.registryInfo.hash,r))}if(o&&o.meta&&(Zr(o,u.chainInfo.name,c,i.identifier),o.meta.query=d),!o)return e;let h=o.chain||u.chainInfo.name,A=m(h,this.adapters),W=await new T(this.config,A,this.adapters).apply(o);return{match:!0,url:t,warp:W,chain:h,registryInfo:c,brand:l}}catch(s){return C.error("Error detecting warp link",s),e}}},Zr=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?at(t,"alias",r.alias):at(t,"hash",r?.hash??e))};var Et=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new X(this.config,this.adapters,t)}async detectWarp(t,r){return new Y(this.config,this.adapters).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 c=this.createExecutor(e),{txs:l,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(o,r,{queries:i.queries});return{txs:l,chain:u,immediateExecutions:d,evaluateOutput:async W=>{await c.evaluateOutput(o,W)},resolvedInputs:h}}async createInscriptionTransaction(t,r){return await m(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return m(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=b(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return m(e.chain,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!w(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return m(t,this.adapters).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.adapters).explorer}getOutput(t){return m(t,this.adapters).output}async getRegistry(t){let r=m(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return m(t,this.adapters).dataLoader}getWallet(t){return m(t,this.adapters).wallet}get factory(){return new j(this.config,this.adapters)}get index(){return new Z(this.config)}get linkBuilder(){return new U(this.config,this.adapters)}createBuilder(t){return m(t,this.adapters).builder()}createAbiBuilder(t){return m(t,this.adapters).abiBuilder()}createBrandBuilder(t){return m(t,this.adapters).brandBuilder()}createSerializer(t){return m(t,this.adapters).serializer}resolveText(t){return z(t,this.config)}};var Rt=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,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,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});
1
+ "use strict";var sr=Object.create;var ot=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var pr=Object.getOwnPropertyNames;var cr=Object.getPrototypeOf,lr=Object.prototype.hasOwnProperty;var ur=(n,t)=>{for(var r in t)ot(n,r,{get:t[r],enumerable:!0})},Ft=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of pr(t))!lr.call(n,i)&&i!==r&&ot(n,i,{get:()=>t[i],enumerable:!(e=or(t,i))||e.enumerable});return n};var k=(n,t,r)=>(r=n!=null?sr(cr(n)):{},Ft(t||!n||!n.__esModule?ot(r,"default",{value:n,enumerable:!0}):r,n)),dr=n=>Ft(ot({},"__esModule",{value:!0}),n);var Yr={};ur(Yr,{BrowserCryptoProvider:()=>pt,CacheTtl:()=>$t,NodeCryptoProvider:()=>ct,WARP_LANGUAGES:()=>Ar,WarpBrandBuilder:()=>Rt,WarpBuilder:()=>Bt,WarpCache:()=>nt,WarpCacheKey:()=>ht,WarpChainName:()=>Ut,WarpClient:()=>Vt,WarpConfig:()=>O,WarpConstants:()=>c,WarpExecutor:()=>it,WarpFactory:()=>M,WarpIndex:()=>at,WarpInputTypes:()=>f,WarpInterpolator:()=>P,WarpLinkBuilder:()=>j,WarpLinkDetecter:()=>st,WarpLogger:()=>I,WarpProtocolVersions:()=>U,WarpSerializer:()=>C,WarpTypeRegistry:()=>Nt,WarpValidator:()=>tt,address:()=>zr,applyOutputToMessages:()=>St,asset:()=>Et,biguint:()=>Mr,bool:()=>qr,buildMappedOutput:()=>Z,buildNestedPayload:()=>Mt,bytesToBase64:()=>mr,bytesToHex:()=>Lt,cleanWarpIdentifier:()=>X,createAuthHeaders:()=>gt,createAuthMessage:()=>ft,createCryptoProvider:()=>Wr,createHttpAuthHeaders:()=>$r,createSignableMessage:()=>Gt,createWarpI18nText:()=>Cr,createWarpIdentifier:()=>ut,evaluateOutputCommon:()=>zt,evaluateWhenCondition:()=>Ct,extractCollectOutput:()=>Y,extractIdentifierInfoFromUrl:()=>G,extractQueryStringFromIdentifier:()=>wt,extractQueryStringFromUrl:()=>It,extractResolvedInputValues:()=>B,extractWarpSecrets:()=>vr,findWarpAdapterForChain:()=>m,getCryptoProvider:()=>yt,getEventNameFromWarp:()=>fr,getLatestProtocolIdentifier:()=>_,getNextInfo:()=>bt,getProviderConfig:()=>Er,getRandomBytes:()=>Wt,getRandomHex:()=>vt,getWarpActionByIndex:()=>b,getWarpBrandLogoUrl:()=>gr,getWarpInfoFromIdentifier:()=>R,getWarpPrimaryAction:()=>V,getWarpWalletAddress:()=>Jt,getWarpWalletAddressFromConfig:()=>S,getWarpWalletMnemonic:()=>Qt,getWarpWalletMnemonicFromConfig:()=>Hr,getWarpWalletPrivateKey:()=>_t,getWarpWalletPrivateKeyFromConfig:()=>Or,hasInputPrefix:()=>Tr,hex:()=>kr,isEqualWarpIdentifier:()=>Ir,isWarpActionAutoExecute:()=>lt,isWarpI18nText:()=>xr,mergeNestedPayload:()=>Pt,option:()=>Gr,parseOutputOutIndex:()=>kt,parseSignedMessage:()=>Nr,replacePlaceholders:()=>H,replacePlaceholdersInWhenExpression:()=>xt,resolveWarpText:()=>K,safeWindow:()=>mt,setCryptoProvider:()=>hr,shiftBigintBy:()=>Q,splitInput:()=>dt,string:()=>Fr,struct:()=>_r,testCryptoAvailability:()=>yr,toInputPayloadValue:()=>qt,toPreviewText:()=>At,tuple:()=>Jr,uint16:()=>Lr,uint32:()=>jr,uint64:()=>Dr,uint8:()=>Ur,validateSignedMessage:()=>Vr,vector:()=>Qr});module.exports=dr(Yr);var Ut=(p=>(p.Multiversx="multiversx",p.Vibechain="vibechain",p.Sui="sui",p.Ethereum="ethereum",p.Base="base",p.Arbitrum="arbitrum",p.Somnia="somnia",p.Fastset="fastset",p.Solana="solana",p))(Ut||{}),c={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"}},f={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},mt=typeof window<"u"?window:{open:()=>{}};var U={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},O={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${U.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${U.Brand}.schema.json`,DefaultClientUrl: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",c.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var fr=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=c.Alerts.TriggerEventPrefix+c.ArgParamsSeparator;if(!r.trigger.startsWith(e))return null;let i=r.trigger.replace(e,"");return i||null};var gr=(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"}`)}}},L=null;function yt(){if(L)return L;if(typeof window<"u"&&window.crypto)return L=new pt,L;if(typeof process<"u"&&process.versions?.node)return L=new ct,L;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function hr(n){L=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 Lt(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 mr(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 Lt(r)}async function yr(){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 Wr(){return yt()}var vr=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${c.Vars.Env}:`)).map(t=>{let r=t.replace(`${c.Vars.Env}:`,"").trim(),[e,i]=r.split(c.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}`)},b=(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},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)},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 Ar={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},K=(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""},xr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,Cr=n=>n;var X=n=>n.startsWith(c.IdentifierAliasMarker)?n.replace(c.IdentifierAliasMarker,""):n,Ir=(n,t)=>!n||!t?!1:X(n)===X(t),ut=(n,t,r)=>{let e=X(r);return t===c.IdentifierType.Alias?c.IdentifierAliasMarker+n+c.IdentifierParamSeparator+e:n+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+e},R=n=>{let t=decodeURIComponent(n).trim(),r=X(t),e=r.split("?")[0],i=jt(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:c.IdentifierChainDefault,type:c.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===c.IdentifierType.Alias||a===c.IdentifierType.Hash){let l=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:l,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===c.IdentifierType.Alias||s===c.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:c.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==c.IdentifierType.Alias&&s!==c.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,l=wr(a,s)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:s,type:l,identifier:o,identifierBase:a}}}return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Alias,identifier:r,identifierBase:e}},G=n=>{let t=new URL(n),e=t.searchParams.get(c.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return R(i)},wr=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Sr=n=>{let t=c.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},jt=n=>{let t=Sr(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=jt(s);return[i,...a]},It=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(c.IdentifierParamName),r.toString()||null}catch{return null}},wt=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]||""]},Tr=n=>{let t=new Set(Object.values(f));if(!n.includes(c.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=K(s,r);return[i,H(a,t)]});return Object.fromEntries(e)};var Dt=k(require("qr-code-styling"),1);var j=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!G(t):!1}build(t,r,e){let i=this.config.clientUrl||O.DefaultClientUrl(this.config.env),s=m(t,this.adapters),a=r===c.IdentifierType.Alias?e:r+c.IdentifierParamSeparator+e,o=s.chainInfo.name+c.IdentifierParamSeparator+a,l=encodeURIComponent(o);return O.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${c.IdentifierParamName}=${l}`}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 l=m(t,this.adapters),p=this.build(l.chainInfo.name,r,e);return new Dt.default({type:"svg",width:i,height:i,data:String(p),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 br="https://",bt=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(br))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let g=H(a,{...r.vars,...i});return[{identifier:g,url:Tt(t,g,n)}]}let l=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let g=H(o,{...r.vars,...i}),v=g?`${a}?${g}`:a;return[{identifier:v,url:Tt(t,v,n)}]}let p=l[0];if(!p)return[];let u=p.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let W=l.filter(g=>g.includes(`{{${d}[]`)).map(g=>{let v=g.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:g,field:A?A.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(g=>{let v=o;for(let{regex:E,field:$}of W){let x=$?Pr(g,$):g;if(x==null)return null;v=v.replace(E,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${a}?${v}`:a;return{identifier:A,url:Tt(t,A,n)}}).filter(g=>g!==null)},Tt=(n,t,r)=>{let[e,i]=t.split("?"),s=R(e)||{chain:c.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 j(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let l=new URL(o);return new URLSearchParams(i).forEach((p,u)=>l.searchParams.set(u,p)),l.toString().replace(/\/\?/,"?")},Pr=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function Mt(n,t,r){return n.startsWith(c.Position.Payload)?n.slice(c.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function Pt(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]=Pt(r[e],t[e]):r[e]=t[e]}),r}function qt(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=qt(e,t);if(e.input.position&&typeof e.input.position=="string"&&e.input.position.startsWith(c.Position.Payload)){let a=Mt(e.input.position,i,s);r=Pt(r,a)}else r[i]=s}),r}var Er=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};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 I=D;var Y=async(n,t,r,e,i,s)=>{let a=[],o=[],l={};for(let[u,d]of Object.entries(n.output||{})){if(d.startsWith(c.Transform.Prefix))continue;let h=kt(d);if(h!==null&&h!==r){l[u]=null;continue}let[W,...y]=d.split("."),g=(v,A)=>A.reduce((E,$)=>E&&E[$]!==void 0?E[$]:null,v);if(W==="out"||W.startsWith("out[")){let v=y.length===0?t?.data||t:g(t,y);a.push(String(v)),o.push(v),l[u]=v}else l[u]=d}let p=Z(e,i);return{values:{string:a,native:o,mapped:p},output:await zt(n,l,r,e,i,s)}},zt=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=Rr(a,n,r,e,i),a=await Br(n,a,s.transform?.runner||null),a},Rr=(n,t,r,e,i)=>{let s={...n},a=b(t,r)?.inputs||[];for(let[o,l]of Object.entries(s))if(typeof l=="string"&&l.startsWith("in.")){let p=l.split(".")[1],u=a.findIndex(h=>h.as===p||h.name===p),d=u!==-1?e[u]?.value:null;s[o]=d?i.stringToNative(d)[1]:null}return s},Br=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(c.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(c.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){I.error(`Transform error for output '${s}':`,o),e[s]=null}return e},kt=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)};async function Gt(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 Gt(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 $r(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 Vr(n){let t=new Date(n).getTime();return Date.now()<t}function Nr(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 Jt=n=>n?typeof n=="string"?n:n.address:null,S=(n,t)=>Jt(n.user?.wallets?.[t]||null),_t=n=>n?typeof n=="string"?n:n.privateKey:null,Qt=n=>n?typeof n=="string"?n:n.mnemonic:null,Or=(n,t)=>_t(n.user?.wallets?.[t]||null)?.trim()||null,Hr=(n,t)=>Qt(n.user?.wallets?.[t]||null)?.trim()||null;var C=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===f.Tuple&&Array.isArray(r)){if(r.length===0)return t+c.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(c.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+r.join(c.ArgListSeparator)}if(t===f.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})${c.ArgParamsSeparator}`;let a=s.map(o=>{let[l,p]=this.getTypeAndValue(e[o]);return`(${o}${c.ArgParamsSeparator}${l})${p}`});return`${t}(${i})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}if(t===f.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${c.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(c.ArgParamsSeparator))){let e=r[0],i=e.indexOf(c.ArgParamsSeparator),s=e.substring(0,i),a=r.map(l=>{let p=l.indexOf(c.ArgParamsSeparator),u=l.substring(p+1);return s.startsWith(f.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),o=s.startsWith(f.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+s+c.ArgParamsSeparator+a.join(o)}return t+c.ArgParamsSeparator+r.join(c.ArgListSeparator)}if(t===f.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?f.Asset+c.ArgParamsSeparator+r.identifier+c.ArgCompositeSeparator+String(r.amount)+c.ArgCompositeSeparator+String(r.decimals):f.Asset+c.ArgParamsSeparator+r.identifier+c.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+c.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(c.ArgParamsSeparator),e=r[0],i=r.slice(1).join(c.ArgParamsSeparator);if(e==="null")return[e,null];if(e===f.Option){let[s,a]=i.split(c.ArgParamsSeparator);return[f.Option+c.ArgParamsSeparator+s,a||null]}if(e===f.Vector){let s=i.indexOf(c.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),l=a.startsWith(f.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(o?o.split(l):[]).map(d=>this.stringToNative(a+c.ArgParamsSeparator+d)[1]);return[f.Vector+c.ArgParamsSeparator+a,u]}else if(e.startsWith(f.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),o=i.split(c.ArgCompositeSeparator).map((l,p)=>this.stringToNative(`${s[p]}${c.IdentifierParamSeparator}${l}`)[1]);return[e,o]}else if(e.startsWith(f.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(c.ArgListSeparator).forEach(l=>{let p=l.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(p){let[,u,d,h]=p;o[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${h}`)[1]}}),[e,o]}else{if(e===f.String)return[e,i];if(e===f.Uint8||e===f.Uint16||e===f.Uint32)return[e,Number(i)];if(e===f.Uint64||e===f.Uint128||e===f.Uint256||e===f.Biguint)return[e,BigInt(i||0)];if(e===f.Bool)return[e,i==="true"];if(e===f.Address)return[e,i];if(e===f.Hex)return[e,i];if(e===f.Asset){let[s,a]=i.split(c.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,l]=this.stringToNative(`${a}:${i}`);return[e,l]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(c.ArgParamsSeparator)){let[r,e]=t.split(c.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[f.Uint32,t]:typeof t=="bigint"?[f.Uint64,t]:typeof t=="boolean"?[f.Bool,t]:[typeof t,t]}};var Fr=n=>new C().nativeToString(f.String,n),Ur=n=>new C().nativeToString(f.Uint8,n),Lr=n=>new C().nativeToString(f.Uint16,n),jr=n=>new C().nativeToString(f.Uint32,n),Dr=n=>new C().nativeToString(f.Uint64,n),Mr=n=>new C().nativeToString(f.Biguint,n),qr=n=>new C().nativeToString(f.Bool,n),zr=n=>new C().nativeToString(f.Address,n),Et=n=>new C().nativeToString(f.Asset,n),kr=n=>new C().nativeToString(f.Hex,n),Gr=(n,t)=>{if(t===null)return f.Option+c.ArgParamsSeparator;let r=n(t),e=r.indexOf(c.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return f.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+s},Jr=(...n)=>new C().nativeToString(f.Tuple,n),_r=n=>new C().nativeToString(f.Struct,n),Qr=n=>new C().nativeToString(f.Vector,n);var Kt=k(require("ajv"),1);var Rt=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||O.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new Kt.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var Xt=k(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||O.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new Xt.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 Bt=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}async build(){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"),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,Xr);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,Kr))}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)}}},Zt=new C,Kr=(n,t)=>typeof t=="bigint"?Zt.nativeToString("biguint",t):t,Xr=(n,t)=>typeof t=="string"&&t.startsWith(f.Biguint+":")?Zt.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 et=F;var $t={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 P=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(c.Vars.Query+c.ArgParamsSeparator)){let l=o.slice(c.Vars.Query.length+1),[p,u]=l.split(c.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(p):null,W=r.queries?.[p]||null||d;W&&s(a,W)}else if(o.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=o.slice(c.Vars.Env.length+1),[p,u]=l.split(c.ArgCompositeSeparator),h={...this.config.vars,...r.envs}?.[p];h&&s(a,h)}else o===c.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(c.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(c.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(c.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)||t.includes(`{{${a}:`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(c.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString())),s=this.replacePlaceholdersWithChain(s,a.Placeholder,i,a.Accessor)}),s}replacePlaceholdersWithChain(t,r,e,i){let s=new RegExp(`\\{\\{${r}:([^}]+)\\}\\}`,"g");return t.replace(s,(a,o)=>{let l=o.trim().toLowerCase();if(!this.adapters)return a;try{let p=m(l,this.adapters),u={config:this.config,adapter:p},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 l=o;l&&typeof l=="object"&&"identifier"in l&&"amount"in l&&(i[`primary.${a}.token`]=String(l.identifier),i[`primary.${a}.amount`]=String(l.amount))}}),i}};var M=class{constructor(t,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 C,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=b(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=m(a.name,this.adapters),l=new P(this.config,o,this.adapters),p=await l.apply(t,i),u=b(p,r),{action:d,index:h}=V(p),W=this.getStringTypedInputs(d,e),y=await this.getResolvedInputs(a.name,d,W,l),g=await this.getModifiedInputs(y),v=[],A=[];h===r-1?(v=y,A=g):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(a.name,u,e,l),A=await this.getModifiedInputs(v));let E=A.find(w=>w.input.position==="receiver"||w.input.position==="destination")?.value,$=this.getDestinationFromAction(u),x=E?this.serializer.stringToNative(E)[1]:$;if(x&&(x=l.applyInputs(x,A,this.serializer,g)),!x&&s.type!=="collect"&&s.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let q=this.getPreparedArgs(u,A);q=q.map(w=>l.applyInputs(w,A,this.serializer,g));let z=A.find(w=>w.input.position==="value")?.value||null,T="value"in u?u.value:null,N=z?.split(c.ArgParamsSeparator)[1]||T||"0",J=l.applyInputs(N,A,this.serializer,g),Yt=BigInt(J),tr=A.filter(w=>w.input.position==="transfer"&&w.value).map(w=>w.value),rr=[...("transfers"in u?u.transfers:[])||[],...tr||[]].map(w=>{let ar=l.applyInputs(w,A,this.serializer,g);return this.serializer.stringToNative(ar)[1]}),er=A.find(w=>w.input.position==="data")?.value,nr="data"in u?u.data||"":null,Ot=er||nr||null,ir=Ot?l.applyInputs(Ot,A,this.serializer,g):null,Ht={warp:p,chain:a,action:r,destination:x,args:q,value:Yt,transfers:rr,data:ir,resolvedInputs:A};return this.cache.set(ht.WarpExecutable(this.config.env,p.meta?.hash||"",r),Ht.resolvedInputs,$t.OneWeek),Ht}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(c.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(l=>this.preprocessInput(t,l))),o=(l,p)=>{if(l.source==="query"){let u=this.url.searchParams.get(l.name);return u?this.serializer.nativeToString(l.type,u):null}else if(l.source===c.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(l.source==="hidden"){if(l.default===void 0)return null;let u=i?i.applyInputs(String(l.default),[],this.serializer):String(l.default);return this.serializer.nativeToString(l.type,u)}else return a[p]||null};return s.map((l,p)=>{let u=o(l,p),d=l.default!==void 0?i?i.applyInputs(String(l.default),[],this.serializer):String(l.default):void 0;return{input:l,value:u||(d!==void 0?this.serializer.nativeToString(l.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(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(p=>p.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 l=Q(o,+a);r.push({...i,value:`${i.input.type}:${l}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=Q(a,+s);r.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let s=i.input.modifier.substring(c.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let o=this.buildInputContext(t,e,i),l=await a.run(s,o);if(l==null)r.push(i);else{let p=this.serializer.nativeToString(i.input.type,l);r.push({...i,value:p})}}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,[,l]=this.serializer.stringToNative(a.value);if(i[o]=l,a.input.type==="asset"&&typeof l=="object"&&l!==null){let p=l;"identifier"in p&&"amount"in p&&(i[`${o}.token`]=String(p.identifier),i[`${o}.amount`]=String(p.amount),i[`${o}.identifier`]=String(p.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,l]=i.split(c.ArgCompositeSeparator);if(l)return r;let p=await s.dataLoader.getAsset(a);if(!p)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof p.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=Q(o,p.decimals);return Et({...p,amount:u})}else return r}catch(e){throw I.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,l]=this.serializer.stringToNative(a),p=l;if(!p||typeof p!="object"||!("identifier"in p)||!("amount"in p))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",p.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",p.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(l=>l.inputs?.some(p=>p.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(l=>l.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 M(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],o=[],{action:l,index:p}=V(t);for(let u=1;u<=t.actions.length;u++){let d=b(t,u);if(!lt(d,t))continue;let{tx:h,chain:W,immediateExecution:y,executable:g}=await this.executeAction(t,u,r,e);h&&i.push(h),W&&(s=W),y&&a.push(y),g&&u===p+1&&g.resolvedInputs&&(o=B(g.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 p=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(p):mt.open(p,"_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 p=await this.executeCollect(a);return p.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:a}):p.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(p.output._DATA),result:p}),{tx:null,chain:null,immediateExecution:null,executable:a})}if(s.type==="mcp"){let p=await this.executeMcp(a);return p.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:a}):p.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(p.output._DATA),result:p}),{tx:null,chain:null,immediateExecution:p,executable:a})}let o=m(a.chain.name,this.adapters);if(s.type==="query"){let p=await o.executor.executeQuery(a);return p.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:p,tx:null})):this.handlers?.onError?.({message:JSON.stringify(p.output._DATA),result:p}),{tx:null,chain:a.chain,immediateExecution:p,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 l=r[o],p=o+1;if(!l){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,p),h={status:"error",warp:t,action:p,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 ${p} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,p,l);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:p,chain:e,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else{let a=s.find(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=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:l}=await Y(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",o,l)}async doHttpRequest(t,r,e,i,s){let a=new P(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:W}=await ft(e,`${t.chain.name}-adapter`),y=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:d,chain:t.chain}));if(y){let g=gt(e,y,h,W);Object.entries(g).forEach(([v,A])=>o.set(v,A))}}r.headers&&Object.entries(r.headers).forEach(([d,h])=>{let W=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(d,W)});let l=r.method||"GET",p=l==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());I.debug("WarpExecutor: Executing HTTP collect",{url:u,method:l,headers:o,body:p});try{let d=await fetch(u,{method:l,headers:o,body:p});I.debug("Collect response status",{status:d.status});let h=await d.json();I.debug("Collect response content",{content:h});let{values:W,output:y}=await Y(t.warp,h,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),d.ok?"success":"error",W,y,h)}catch(d){I.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=b(t.warp,t.action);if(!i.destination){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("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}let s,a;try{s=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,a=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let y=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user: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(),l=new P(this.config,m(t.chain.name,this.adapters),this.adapters),p=i.destination,u=l.applyInputs(p.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(p.tool,t.resolvedInputs,this.factory.getSerializer()),h={};p.headers&&Object.entries(p.headers).forEach(([W,y])=>{let g=l.applyInputs(y,t.resolvedInputs,this.factory.getSerializer());h[W]=g}),I.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let W=new a(new URL(u),{requestInit:{headers:h}}),y=new s({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(W);let g={};t.resolvedInputs.forEach(({input:x,value:q})=>{if(q&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let z=x.position.replace("payload:",""),[T,N]=o.stringToNative(q);if(T==="string")g[z]=String(N);else if(T==="bool")g[z]=!!N;else if(T==="uint8"||T==="uint16"||T==="uint32"||T==="uint64"||T==="uint128"||T==="uint256"||T==="biguint"){let J=Number(N);g[z]=(Number.isInteger(J),J)}else g[z]=N}}),r&&Object.assign(g,r);let v=await y.callTool({name:d,arguments:g});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:E,output:$}=await Y(t.warp,A,t.action,t.resolvedInputs,o,this.config);return this.buildCollectResult(t,e,"success",E,$,v)}catch(W){I.error("WarpExecutor: Error executing MCP",W);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:W},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),l=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:l}}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),l=m(o.name,this.adapters),p=new P(this.config,l,this.adapters),{action:u}=V(t),d=this.factory.getStringTypedInputs(u,e),h=await this.factory.getResolvedInputs(o.name,u,d,p),W=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),p);y=await this.factory.getModifiedInputs(A)}let g=p.buildInputBag(y,this.factory.getSerializer(),W),v=xt(r.when,g);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 I.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(c.HttpProtocolPrefix)?!!G(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),a=(await Promise.all(i)).filter(p=>p.match),o=a.length>0,l=a.map(p=>({url:p.url,warp:p.warp}));return{match:o,output:l}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(c.HttpProtocolPrefix)?G(t):R(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,l=null,p=null,u=m(i.chain,this.adapters),d=t.startsWith(c.HttpProtocolPrefix)?It(t):wt(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let g=await u.registry.getInfoByHash(a,r);l=g.registryInfo,p=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,r);l=g.registryInfo,p=g.brand,g.registryInfo&&(o=await u.builder().createFromTransactionHash(g.registryInfo.hash,r))}if(o&&o.meta&&(Zr(o,u.chainInfo.name,l,i.identifier),o.meta.query=d),!o)return e;let h=o.chain||u.chainInfo.name,W=m(h,this.adapters),y=await new P(this.config,W,this.adapters).apply(o);return{match:!0,url:t,warp:y,chain:h,registryInfo:l,brand:p}}catch(s){return I.error("Error detecting warp link",s),e}}},Zr=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?ut(t,"alias",r.alias):ut(t,"hash",r?.hash??e))};var Vt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new it(this.config,this.adapters,t)}async detectWarp(t,r){return new st(this.config,this.adapters).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 l=this.createExecutor(e),{txs:p,chain:u,immediateExecutions:d,resolvedInputs:h}=await l.execute(o,r,{queries:i.queries});return{txs:p,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await l.evaluateOutput(o,y)},resolvedInputs:h}}async createInscriptionTransaction(t,r){return await m(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return m(t,this.adapters).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.adapters).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.adapters).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.adapters).explorer}getOutput(t){return m(t,this.adapters).output}async getRegistry(t){let r=m(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return m(t,this.adapters).dataLoader}getWallet(t){return m(t,this.adapters).wallet}get factory(){return new M(this.config,this.adapters)}get index(){return new at(this.config)}get linkBuilder(){return new j(this.config,this.adapters)}createBuilder(t){return m(t,this.adapters).builder()}createAbiBuilder(t){return m(t,this.adapters).abiBuilder()}createBrandBuilder(t){return m(t,this.adapters).brandBuilder()}createSerializer(t){return m(t,this.adapters).serializer}resolveText(t){return K(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,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,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});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var zt=(l=>(l.Multiversx="multiversx",l.Vibechain="vibechain",l.Sui="sui",l.Ethereum="ethereum",l.Base="base",l.Arbitrum="arbitrum",l.Somnia="somnia",l.Fastset="fastset",l.Solana="solana",l))(zt||{}),p={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"}},f={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"},ft=typeof window<"u"?window:{open:()=>{}};var U={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},V={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${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",p.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 yr=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=p.Alerts.TriggerEventPrefix+p.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 rt=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}},et=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"}`)}}},O=null;function gt(){if(O)return O;if(typeof window<"u"&&window.crypto)return O=new rt,O;if(typeof process<"u"&&process.versions?.node)return O=new et,O;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Cr(n){O=n}async function ht(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||gt()).getRandomBytes(n)}function Mt(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 Ir(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 mt(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await ht(n/2,t);return Mt(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 ht(16),n.randomBytes=!0}catch{}return n}function Sr(){return gt()}var Pr=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${p.Vars.Env}:`)).map(t=>{let r=t.replace(`${p.Vars.Env}:`,"").trim(),[e,i]=r.split(p.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},z=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}`)},b=(n,t)=>n?.actions[t-1],R=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"],e=n.actions.find(s=>r.includes(s.type));return e?{action:e,index:n.actions.indexOf(e)}:{action:n.actions[0],index:0}},nt=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=R(t);return n===r}return!0},M=(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)},Wt=(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},N=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),yt=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>{let i=t[e];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),vt=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 $r={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"},G=(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""},Vr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,Or=n=>n;var J=n=>n.startsWith(p.IdentifierAliasMarker)?n.replace(p.IdentifierAliasMarker,""):n,Ur=(n,t)=>!n||!t?!1:J(n)===J(t),it=(n,t,r)=>{let e=J(r);return t===p.IdentifierType.Alias?p.IdentifierAliasMarker+n+p.IdentifierParamSeparator+e:n+p.IdentifierParamSeparator+t+p.IdentifierParamSeparator+e},T=n=>{let t=decodeURIComponent(n).trim(),r=J(t),e=r.split("?")[0],i=At(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:p.IdentifierChainDefault,type:p.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===p.IdentifierType.Alias||a===p.IdentifierType.Hash){let c=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:c,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===p.IdentifierType.Alias||s===p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:p.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==p.IdentifierType.Alias&&s!==p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,c=Gt(a,s)?p.IdentifierType.Hash:p.IdentifierType.Alias;return{chain:s,type:c,identifier:o,identifierBase:a}}}return{chain:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:e}},D=n=>{let t=new URL(n),e=t.searchParams.get(p.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return T(i)},Gt=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Jt=n=>{let t=p.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},At=n=>{let t=Jt(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=At(s);return[i,...a]},xt=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(p.IdentifierParamName),r.toString()||null}catch{return null}},Ct=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 at=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},jr=n=>{let t=new Set(Object.values(f));if(!n.includes(p.ArgParamsSeparator))return!1;let r=at(n)[0];return t.has(r)};var It=(n,t,r)=>{let e=Object.entries(n.messages||{}).map(([i,s])=>{let a=G(s,r);return[i,N(a,t)]});return Object.fromEntries(e)};import Qt from"qr-code-styling";var H=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!D(t):!1}build(t,r,e){let i=this.config.clientUrl||V.DefaultClientUrl(this.config.env),s=m(t,this.adapters),a=r===p.IdentifierType.Alias?e:r+p.IdentifierParamSeparator+e,o=s.chainInfo.name+p.IdentifierParamSeparator+a,c=encodeURIComponent(o);return V.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${p.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let r=T(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 c=m(t,this.adapters),l=this.build(c.chainInfo.name,r,e);return new Qt({type:"svg",width:i,height:i,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Kt="https://",wt=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Kt))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let g=N(a,{...r.vars,...i});return[{identifier:g,url:st(t,g,n)}]}let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let g=N(o,{...r.vars,...i}),y=g?`${a}?${g}`:a;return[{identifier:y,url:st(t,y,n)}]}let l=c[0];if(!l)return[];let u=l.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let A=c.filter(g=>g.includes(`{{${d}[]`)).map(g=>{let y=g.match(/\[\](\.[^}]+)?}}/),v=y&&y[1]||"";return{placeholder:g,field:v?v.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(g=>{let y=o;for(let{regex:E,field:$}of A){let S=$?_t(g,$):g;if(S==null)return null;y=y.replace(E,S)}if(y.includes("{{")||y.includes("}}"))return null;let v=y?`${a}?${y}`:a;return{identifier:v,url:st(t,v,n)}}).filter(g=>g!==null)},st=(n,t,r)=>{let[e,i]=t.split("?"),s=T(e)||{chain:p.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 H(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let c=new URL(o);return new URLSearchParams(i).forEach((l,u)=>c.searchParams.set(u,l)),c.toString().replace(/\/\?/,"?")},_t=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function Xt(n,t,r){return n.startsWith(p.Position.Payload)?n.slice(p.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function St(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]=St(r[e],t[e]):r[e]=t[e]}),r}function Zt(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 L(n){return n.map(t=>t.value).filter(t=>t!=null&&t!=="")}function Q(n,t){let r={};return n.forEach(e=>{let i=e.input.as||e.input.name,s=Zt(e,t);if(e.input.position&&typeof e.input.position=="string"&&e.input.position.startsWith(p.Position.Payload)){let a=Xt(e.input.position,i,s);r=St(r,a)}else r[i]=s}),r}var ie=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};var F=class F{static debug(...t){F.isTestEnv||console.debug(...t)}static info(...t){F.isTestEnv||console.info(...t)}static warn(...t){F.isTestEnv||console.warn(...t)}static error(...t){F.isTestEnv||console.error(...t)}};F.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var I=F;var ot=async(n,t,r,e,i,s)=>{let a=[],o=[],c={};for(let[u,d]of Object.entries(n.output||{})){if(d.startsWith(p.Transform.Prefix))continue;let h=er(d);if(h!==null&&h!==r){c[u]=null;continue}let[A,...W]=d.split("."),g=(y,v)=>v.reduce((E,$)=>E&&E[$]!==void 0?E[$]:null,y);if(A==="out"||A.startsWith("out[")){let y=W.length===0?t?.data||t:g(t,W);a.push(String(y)),o.push(y),c[u]=y}else c[u]=d}let l=Q(e,i);return{values:{string:a,native:o,mapped:l},output:await Yt(n,c,r,e,i,s)}},Yt=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=tr(a,n,r,e,i),a=await rr(n,a,s.transform?.runner||null),a},tr=(n,t,r,e,i)=>{let s={...n},a=b(t,r)?.inputs||[];for(let[o,c]of Object.entries(s))if(typeof c=="string"&&c.startsWith("in.")){let l=c.split(".")[1],u=a.findIndex(h=>h.as===l||h.name===l),d=u!==-1?e[u]?.value:null;s[o]=d?i.stringToNative(d)[1]:null}return s},rr=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(p.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(p.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){I.error(`Transform error for output '${s}':`,o),e[s]=null}return e},er=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)};async function nr(n,t,r,e=5){let i=await mt(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 pt(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return nr(n,i,r,5)}function ct(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function ge(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await pt(n,r,e),o=await t(i);return ct(n,o,s,a)}function he(n){let t=new Date(n).getTime();return Date.now()<t}function me(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 ir=n=>n?typeof n=="string"?n:n.address:null,w=(n,t)=>ir(n.user?.wallets?.[t]||null),ar=n=>n?typeof n=="string"?n:n.privateKey:null,sr=n=>n?typeof n=="string"?n:n.mnemonic:null,ye=(n,t)=>ar(n.user?.wallets?.[t]||null)?.trim()||null,ve=(n,t)=>sr(n.user?.wallets?.[t]||null)?.trim()||null;var x=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===f.Tuple&&Array.isArray(r)){if(r.length===0)return t+p.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(p.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(p.ArgCompositeSeparator)})${p.ArgParamsSeparator}${s.join(p.ArgListSeparator)}`}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===f.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})${p.ArgParamsSeparator}`;let a=s.map(o=>{let[c,l]=this.getTypeAndValue(e[o]);return`(${o}${p.ArgParamsSeparator}${c})${l}`});return`${t}(${i})${p.ArgParamsSeparator}${a.join(p.ArgListSeparator)}`}if(t===f.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${p.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(p.ArgParamsSeparator))){let e=r[0],i=e.indexOf(p.ArgParamsSeparator),s=e.substring(0,i),a=r.map(c=>{let l=c.indexOf(p.ArgParamsSeparator),u=c.substring(l+1);return s.startsWith(f.Tuple)?u.replace(p.ArgListSeparator,p.ArgCompositeSeparator):u}),o=s.startsWith(f.Struct)?p.ArgStructSeparator:p.ArgListSeparator;return t+p.ArgParamsSeparator+s+p.ArgParamsSeparator+a.join(o)}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===f.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?f.Asset+p.ArgParamsSeparator+r.identifier+p.ArgCompositeSeparator+String(r.amount)+p.ArgCompositeSeparator+String(r.decimals):f.Asset+p.ArgParamsSeparator+r.identifier+p.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+p.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(p.ArgParamsSeparator),e=r[0],i=r.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e===f.Option){let[s,a]=i.split(p.ArgParamsSeparator);return[f.Option+p.ArgParamsSeparator+s,a||null]}if(e===f.Vector){let s=i.indexOf(p.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),c=a.startsWith(f.Struct)?p.ArgStructSeparator:p.ArgListSeparator,u=(o?o.split(c):[]).map(d=>this.stringToNative(a+p.ArgParamsSeparator+d)[1]);return[f.Vector+p.ArgParamsSeparator+a,u]}else if(e.startsWith(f.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=i.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}${p.IdentifierParamSeparator}${c}`)[1]);return[e,o]}else if(e.startsWith(f.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(p.ArgListSeparator).forEach(c=>{let l=c.match(new RegExp(`^\\(([^${p.ArgParamsSeparator}]+)${p.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(l){let[,u,d,h]=l;o[u]=this.stringToNative(`${d}${p.IdentifierParamSeparator}${h}`)[1]}}),[e,o]}else{if(e===f.String)return[e,i];if(e===f.Uint8||e===f.Uint16||e===f.Uint32)return[e,Number(i)];if(e===f.Uint64||e===f.Uint128||e===f.Uint256||e===f.Biguint)return[e,BigInt(i||0)];if(e===f.Bool)return[e,i==="true"];if(e===f.Address)return[e,i];if(e===f.Hex)return[e,i];if(e===f.Asset){let[s,a]=i.split(p.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,c]=this.stringToNative(`${a}:${i}`);return[e,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(p.ArgParamsSeparator)){let[r,e]=t.split(p.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[f.Uint32,t]:typeof t=="bigint"?[f.Uint64,t]:typeof t=="boolean"?[f.Bool,t]:[typeof t,t]}};var Se=n=>new x().nativeToString(f.String,n),be=n=>new x().nativeToString(f.Uint8,n),Te=n=>new x().nativeToString(f.Uint16,n),Pe=n=>new x().nativeToString(f.Uint32,n),Ee=n=>new x().nativeToString(f.Uint64,n),Re=n=>new x().nativeToString(f.Biguint,n),Be=n=>new x().nativeToString(f.Bool,n),$e=n=>new x().nativeToString(f.Address,n),bt=n=>new x().nativeToString(f.Asset,n),Ve=n=>new x().nativeToString(f.Hex,n),Oe=(n,t)=>{if(t===null)return f.Option+p.ArgParamsSeparator;let r=n(t),e=r.indexOf(p.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return f.Option+p.ArgParamsSeparator+i+p.ArgParamsSeparator+s},Ne=(...n)=>new x().nativeToString(f.Tuple,n),Fe=n=>new x().nativeToString(f.Struct,n),Ue=n=>new x().nativeToString(f.Vector,n);import or from"ajv";var Tt=class{constructor(t){this.pendingBrand={protocol:z("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||V.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new or,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import pr from"ajv";var K=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}=R(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||V.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new pr({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 Pt=class{constructor(t){this.config=t;this.pendingWarp={protocol:z("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}async build(){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"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return Wt(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 K(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
- `))}};var k=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,lr);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,cr))}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)}}},Et=new x,cr=(n,t)=>typeof t=="bigint"?Et.nativeToString("biguint",t):t,lr=(n,t)=>typeof t=="string"&&t.startsWith(f.Biguint+":")?Et.stringToNative(t)[1]:t;var B=class B{get(t){let r=B.cache.get(t);return r?Date.now()>r.expiresAt?(B.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;B.cache.set(t,{value:r,expiresAt:i})}forget(t){B.cache.delete(t)}clear(){B.cache.clear()}};B.cache=new Map;var q=B;var Rt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},lt={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}`},_=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new k:t==="memory"?new q:typeof window<"u"&&window.localStorage?new k:new q}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 P=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=w(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(p.Vars.Query+p.ArgParamsSeparator)){let c=o.slice(p.Vars.Query.length+1),[l,u]=c.split(p.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(l):null,A=r.queries?.[l]||null||d;A&&s(a,A)}else if(o.startsWith(p.Vars.Env+p.ArgParamsSeparator)){let c=o.slice(p.Vars.Env.length+1),[l,u]=c.split(p.ArgCompositeSeparator),h={...this.config.vars,...r.envs}?.[l];h&&s(a,h)}else o===p.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(p.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(p.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 N(s,a)}applyGlobalsToText(t){if(!Object.values(p.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(p.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 c=o.trim().toLowerCase();if(!this.adapters)return a;try{let l=m(c,this.adapters),u={config:this.config,adapter:l},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 c=o;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${a}.token`]=String(c.identifier),i[`primary.${a}.amount`]=String(c.amount))}}),i}};var j=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 x,this.cache=new _(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,r,e){let i=this.cache.get(lt.WarpExecutable(t,r||"",e))||[];return L(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=m(a.name,this.adapters),c=new P(this.config,o,this.adapters),l=await c.apply(t,i),u=b(l,r),{action:d,index:h}=R(l),A=this.getStringTypedInputs(d,e),W=await this.getResolvedInputs(a.name,d,A,c),g=await this.getModifiedInputs(W),y=[],v=[];h===r-1&&(y=W,v=g);let E=v.find(C=>C.input.position==="receiver"||C.input.position==="destination")?.value,$=this.getDestinationFromAction(u),S=E?this.serializer.stringToNative(E)[1]:$;if(S&&(S=c.applyInputs(S,v,this.serializer,g)),!S&&s.type!=="collect")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let tt=this.getPreparedArgs(u,v);tt=tt.map(C=>c.applyInputs(C,v,this.serializer,g));let Vt=v.find(C=>C.input.position==="value")?.value||null,Ot="value"in u?u.value:null,Nt=Vt?.split(p.ArgParamsSeparator)[1]||Ot||"0",Ft=c.applyInputs(Nt,v,this.serializer,g),Ut=BigInt(Ft),Ht=v.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),Lt=[...("transfers"in u?u.transfers:[])||[],...Ht||[]].map(C=>{let qt=c.applyInputs(C,v,this.serializer,g);return this.serializer.stringToNative(qt)[1]}),jt=v.find(C=>C.input.position==="data")?.value,Dt="data"in u?u.data||"":null,ut=jt||Dt||null,kt=ut?c.applyInputs(ut,v,this.serializer,g):null,dt={warp:l,chain:a,action:r,destination:S,args:tt,value:Ut,transfers:Lt,data:kt,resolvedInputs:v};return this.cache.set(lt.WarpExecutable(this.config.env,l.meta?.hash||"",r),dt.resolvedInputs,Rt.OneWeek),dt}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(p.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(c=>this.preprocessInput(t,c))),o=(c,l)=>{if(c.source==="query"){let u=this.url.searchParams.get(c.name);return u?this.serializer.nativeToString(c.type,u):null}else if(c.source===p.Source.UserWallet){let u=w(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(c.source==="hidden"){if(c.default===void 0)return null;let u=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,u)}else return a[l]||null};return s.map((c,l)=>{let u=o(c,l),d=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:u||(d!==void 0?this.serializer.nativeToString(c.type,d):null)}})}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(l=>l.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let c=M(o,+a);r.push({...i,value:`${i.input.type}:${c}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=M(a,+s);r.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(p.Transform.Prefix)){let s=i.input.modifier.substring(p.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),c=await a.run(s,o);if(c==null)r.push(i);else{let l=this.serializer.nativeToString(i.input.type,c);r.push({...i,value:l})}}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,[,c]=this.serializer.stringToNative(a.value);if(i[o]=c,a.input.type==="asset"&&typeof c=="object"&&c!==null){let l=c;"identifier"in l&&"amount"in l&&(i[`${o}.token`]=String(l.identifier),i[`${o}.amount`]=String(l.amount),i[`${o}.identifier`]=String(l.identifier))}}if(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]=at(r),s=m(t,this.adapters);if(e==="asset"){let[a,o,c]=i.split(p.ArgCompositeSeparator);if(c)return r;let l=await s.dataLoader.getAsset(a);if(!l)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof l.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=M(o,l.decimals);return bt({...l,amount:u})}else return r}catch(e){throw I.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,c]=this.serializer.stringToNative(a),l=c;if(!l||typeof l!="object"||!("identifier"in l)||!("amount"in l))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,d=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",l.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",l.amount)})}else if(s.position.startsWith("arg:")){let o=Number(s.position.split(":")[1])-1;i.push({index:o,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;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(c=>c.inputs?.some(l=>l.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(c=>c.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 X=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new j(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],o=[],{action:c,index:l}=R(t);for(let u=1;u<=t.actions.length;u++){let d=b(t,u);if(!nt(d,t))continue;let{tx:h,chain:A,immediateExecution:W,executable:g}=await this.executeAction(t,u,r,e);h&&i.push(h),A&&(s=A),W&&a.push(W),g&&u===l+1&&g.resolvedInputs&&(o=L(g.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 l=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(l):ft.open(l,"_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 l=await this.executeCollect(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:null,immediateExecution:null,executable:a})}let o=m(a.chain.name,this.adapters);if(s.type==="query"){let l=await o.executor.executeQuery(a);return l.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:l,tx:null})):this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:a.chain,immediateExecution:l,executable:a}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,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(!nt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let c=r[o],l=o+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,l),h={status:"error",warp:t,action:l,user:w(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 ${l} failed: Transaction not found`})),h}let u=await i.output.getActionExecution(t,l,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:l,chain:e,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),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 await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s.map(a=>a.values))}`}))}async executeCollect(t,r){let e=w(this.config,t.chain.name),i=b(t.warp,t.action),s=this.factory.getSerializer(),a=Q(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:c}=await ot(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",o,c)}async doHttpRequest(t,r,e,i,s){let a=new P(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:A}=await pt(e,`${t.chain.name}-adapter`),W=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:d,chain:t.chain}));if(W){let g=ct(e,W,h,A);Object.entries(g).forEach(([y,v])=>o.set(y,v))}}r.headers&&Object.entries(r.headers).forEach(([d,h])=>{let A=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(d,A)});let c=r.method||"GET",l=c==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());I.debug("WarpExecutor: Executing HTTP collect",{url:u,method:c,headers:o,body:l});try{let d=await fetch(u,{method:c,headers:o,body:l});I.debug("Collect response status",{status:d.status});let h=await d.json();I.debug("Collect response content",{content:h});let{values:A,output:W}=await ot(t.warp,h,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,w(this.config,t.chain.name),d.ok?"success":"error",A,W,h)}catch(d){I.error("WarpActionExecutor: Error executing collect",d);let h=L(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}buildCollectResult(t,r,e,i,s,a){let o=wt(this.config,this.adapters,t.warp,t.action,s),c=L(t.resolvedInputs);return{status:e,warp:t.warp,action:t.action,user:r||w(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:It(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}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),c=m(o.name,this.adapters),l=new P(this.config,c,this.adapters),{action:u}=R(t),d=this.factory.getStringTypedInputs(u,e),h=await this.factory.getResolvedInputs(o.name,u,d,l),A=await this.factory.getModifiedInputs(h),W;if(s)W=s;else{let v=await this.factory.getResolvedInputs(o.name,r,this.factory.getStringTypedInputs(r,e),l);W=await this.factory.getModifiedInputs(v)}let g=l.buildInputBag(W,this.factory.getSerializer(),A),y=yt(r.when,g);return vt(y)}};var Z=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 I.error("WarpIndex: Error searching for warps: ",i),i}}};var Y=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!D(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),o=a.length>0,c=a.map(l=>({url:l.url,warp:l.warp}));return{match:o,output:c}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(p.HttpProtocolPrefix)?D(t):T(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,c=null,l=null,u=m(i.chain,this.adapters),d=t.startsWith(p.HttpProtocolPrefix)?xt(t):Ct(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let g=await u.registry.getInfoByHash(a,r);c=g.registryInfo,l=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,r);c=g.registryInfo,l=g.brand,g.registryInfo&&(o=await u.builder().createFromTransactionHash(g.registryInfo.hash,r))}if(o&&o.meta&&(ur(o,u.chainInfo.name,c,i.identifier),o.meta.query=d),!o)return e;let h=o.chain||u.chainInfo.name,A=m(h,this.adapters),W=await new P(this.config,A,this.adapters).apply(o);return{match:!0,url:t,warp:W,chain:h,registryInfo:c,brand:l}}catch(s){return I.error("Error detecting warp link",s),e}}},ur=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?it(t,"alias",r.alias):it(t,"hash",r?.hash??e))};var Bt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new X(this.config,this.adapters,t)}async detectWarp(t,r){return new Y(this.config,this.adapters).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 c=this.createExecutor(e),{txs:l,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(o,r,{queries:i.queries});return{txs:l,chain:u,immediateExecutions:d,evaluateOutput:async W=>{await c.evaluateOutput(o,W)},resolvedInputs:h}}async createInscriptionTransaction(t,r){return await m(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return m(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=T(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return m(e.chain,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!w(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return m(t,this.adapters).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.adapters).explorer}getOutput(t){return m(t,this.adapters).output}async getRegistry(t){let r=m(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return m(t,this.adapters).dataLoader}getWallet(t){return m(t,this.adapters).wallet}get factory(){return new j(this.config,this.adapters)}get index(){return new Z(this.config)}get linkBuilder(){return new H(this.config,this.adapters)}createBuilder(t){return m(t,this.adapters).builder()}createAbiBuilder(t){return m(t,this.adapters).abiBuilder()}createBrandBuilder(t){return m(t,this.adapters).brandBuilder()}createSerializer(t){return m(t,this.adapters).serializer}resolveText(t){return G(t,this.config)}};var $t=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{rt as BrowserCryptoProvider,Rt as CacheTtl,et as NodeCryptoProvider,$r as WARP_LANGUAGES,Tt as WarpBrandBuilder,Pt as WarpBuilder,_ as WarpCache,lt as WarpCacheKey,zt as WarpChainName,Bt as WarpClient,V as WarpConfig,p as WarpConstants,X as WarpExecutor,j as WarpFactory,Z as WarpIndex,f as WarpInputTypes,P as WarpInterpolator,H as WarpLinkBuilder,Y as WarpLinkDetecter,I as WarpLogger,U as WarpProtocolVersions,x as WarpSerializer,$t as WarpTypeRegistry,K as WarpValidator,$e as address,It as applyOutputToMessages,bt as asset,Re as biguint,Be as bool,Q as buildMappedOutput,Xt as buildNestedPayload,Ir as bytesToBase64,Mt as bytesToHex,J as cleanWarpIdentifier,ct as createAuthHeaders,pt as createAuthMessage,Sr as createCryptoProvider,ge as createHttpAuthHeaders,nr as createSignableMessage,Or as createWarpI18nText,it as createWarpIdentifier,Yt as evaluateOutputCommon,vt as evaluateWhenCondition,ot as extractCollectOutput,D as extractIdentifierInfoFromUrl,Ct as extractQueryStringFromIdentifier,xt as extractQueryStringFromUrl,L as extractResolvedInputValues,Pr as extractWarpSecrets,m as findWarpAdapterForChain,gt as getCryptoProvider,yr as getEventNameFromWarp,z as getLatestProtocolIdentifier,wt as getNextInfo,ie as getProviderConfig,ht as getRandomBytes,mt as getRandomHex,b as getWarpActionByIndex,Ar as getWarpBrandLogoUrl,T as getWarpInfoFromIdentifier,R as getWarpPrimaryAction,ir as getWarpWalletAddress,w as getWarpWalletAddressFromConfig,sr as getWarpWalletMnemonic,ve as getWarpWalletMnemonicFromConfig,ar as getWarpWalletPrivateKey,ye as getWarpWalletPrivateKeyFromConfig,jr as hasInputPrefix,Ve as hex,Ur as isEqualWarpIdentifier,nt as isWarpActionAutoExecute,Vr as isWarpI18nText,St as mergeNestedPayload,Oe as option,er as parseOutputOutIndex,me as parseSignedMessage,N as replacePlaceholders,yt as replacePlaceholdersInWhenExpression,G as resolveWarpText,ft as safeWindow,Cr as setCryptoProvider,M as shiftBigintBy,at as splitInput,Se as string,Fe as struct,wr as testCryptoAvailability,Zt as toInputPayloadValue,Wt as toPreviewText,Ne as tuple,Te as uint16,Pe as uint32,Ee as uint64,be as uint8,he as validateSignedMessage,Ue as vector};
1
+ var zt=(p=>(p.Multiversx="multiversx",p.Vibechain="vibechain",p.Sui="sui",p.Ethereum="ethereum",p.Base="base",p.Arbitrum="arbitrum",p.Somnia="somnia",p.Fastset="fastset",p.Solana="solana",p))(zt||{}),c={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"}},f={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 M={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${M.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${M.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",c.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var Wr=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=c.Alerts.TriggerEventPrefix+c.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 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"}`)}}},F=null;function Wt(){if(F)return F;if(typeof window<"u"&&window.crypto)return F=new st,F;if(typeof process<"u"&&process.versions?.node)return F=new ot,F;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Cr(n){F=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 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 Ir(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 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 vt(16),n.randomBytes=!0}catch{}return n}function Sr(){return Wt()}var Pr=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${c.Vars.Env}:`)).map(t=>{let r=t.replace(`${c.Vars.Env}:`,"").trim(),[e,i]=r.split(c.ArgCompositeSeparator);return{key:e,description:i||null}});var y=(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},Q=n=>{if(n==="warp")return`warp:${M.Warp}`;if(n==="brand")return`brand:${M.Brand}`;if(n==="abi")return`abi:${M.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},P=(n,t)=>n?.actions[t-1],N=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}=N(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)},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)}),It=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 $r={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""},Vr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,Nr=n=>n;var Z=n=>n.startsWith(c.IdentifierAliasMarker)?n.replace(c.IdentifierAliasMarker,""):n,Fr=(n,t)=>!n||!t?!1:Z(n)===Z(t),ct=(n,t,r)=>{let e=Z(r);return t===c.IdentifierType.Alias?c.IdentifierAliasMarker+n+c.IdentifierParamSeparator+e:n+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+e},B=n=>{let t=decodeURIComponent(n).trim(),r=Z(t),e=r.split("?")[0],i=wt(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:c.IdentifierChainDefault,type:c.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===c.IdentifierType.Alias||a===c.IdentifierType.Hash){let l=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:l,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===c.IdentifierType.Alias||s===c.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:c.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==c.IdentifierType.Alias&&s!==c.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,l=Gt(a,s)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:s,type:l,identifier:o,identifierBase:a}}}return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Alias,identifier:r,identifierBase:e}},G=n=>{let t=new URL(n),e=t.searchParams.get(c.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return B(i)},Gt=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Jt=n=>{let t=c.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},wt=n=>{let t=Jt(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=wt(s);return[i,...a]},St=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(c.IdentifierParamName),r.toString()||null}catch{return null}},Tt=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]||""]},jr=n=>{let t=new Set(Object.values(f));if(!n.includes(c.ArgParamsSeparator))return!1;let r=lt(n)[0];return t.has(r)};var bt=(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 _t from"qr-code-styling";var q=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!G(t):!1}build(t,r,e){let i=this.config.clientUrl||H.DefaultClientUrl(this.config.env),s=y(t,this.adapters),a=r===c.IdentifierType.Alias?e:r+c.IdentifierParamSeparator+e,o=s.chainInfo.name+c.IdentifierParamSeparator+a,l=encodeURIComponent(o);return H.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${c.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let r=B(t);if(!r)return null;let e=y(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 l=y(t,this.adapters),p=this.build(l.chainInfo.name,r,e);return new _t({type:"svg",width:i,height:i,data:String(p),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 Qt="https://",Pt=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Qt))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let g=U(a,{...r.vars,...i});return[{identifier:g,url:ut(t,g,n)}]}let l=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let g=U(o,{...r.vars,...i}),v=g?`${a}?${g}`:a;return[{identifier:v,url:ut(t,v,n)}]}let p=l[0];if(!p)return[];let u=p.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let W=l.filter(g=>g.includes(`{{${d}[]`)).map(g=>{let v=g.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:g,field:A?A.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(g=>{let v=o;for(let{regex:b,field:R}of W){let x=R?Kt(g,R):g;if(x==null)return null;v=v.replace(b,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${a}?${v}`:a;return{identifier:A,url:ut(t,A,n)}}).filter(g=>g!==null)},ut=(n,t,r)=>{let[e,i]=t.split("?"),s=B(e)||{chain:c.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=y(s.chain,n);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let o=new q(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let l=new URL(o);return new URLSearchParams(i).forEach((p,u)=>l.searchParams.set(u,p)),l.toString().replace(/\/\?/,"?")},Kt=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function Xt(n,t,r){return n.startsWith(c.Position.Payload)?n.slice(c.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 Zt(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=Zt(e,t);if(e.input.position&&typeof e.input.position=="string"&&e.input.position.startsWith(c.Position.Payload)){let a=Xt(e.input.position,i,s);r=Et(r,a)}else r[i]=s}),r}var ie=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};var L=class L{static debug(...t){L.isTestEnv||console.debug(...t)}static info(...t){L.isTestEnv||console.info(...t)}static warn(...t){L.isTestEnv||console.warn(...t)}static error(...t){L.isTestEnv||console.error(...t)}};L.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var I=L;var tt=async(n,t,r,e,i,s)=>{let a=[],o=[],l={};for(let[u,d]of Object.entries(n.output||{})){if(d.startsWith(c.Transform.Prefix))continue;let h=er(d);if(h!==null&&h!==r){l[u]=null;continue}let[W,...m]=d.split("."),g=(v,A)=>A.reduce((b,R)=>b&&b[R]!==void 0?b[R]:null,v);if(W==="out"||W.startsWith("out[")){let v=m.length===0?t?.data||t:g(t,m);a.push(String(v)),o.push(v),l[u]=v}else l[u]=d}let p=Y(e,i);return{values:{string:a,native:o,mapped:p},output:await Yt(n,l,r,e,i,s)}},Yt=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=tr(a,n,r,e,i),a=await rr(n,a,s.transform?.runner||null),a},tr=(n,t,r,e,i)=>{let s={...n},a=P(t,r)?.inputs||[];for(let[o,l]of Object.entries(s))if(typeof l=="string"&&l.startsWith("in.")){let p=l.split(".")[1],u=a.findIndex(h=>h.as===p||h.name===p),d=u!==-1?e[u]?.value:null;s[o]=d?i.stringToNative(d)[1]:null}return s},rr=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(c.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(c.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){I.error(`Transform error for output '${s}':`,o),e[s]=null}return e},er=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)};async function nr(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 nr(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 ge(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 he(n){let t=new Date(n).getTime();return Date.now()<t}function me(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 ir=n=>n?typeof n=="string"?n:n.address:null,S=(n,t)=>ir(n.user?.wallets?.[t]||null),ar=n=>n?typeof n=="string"?n:n.privateKey:null,sr=n=>n?typeof n=="string"?n:n.mnemonic:null,We=(n,t)=>ar(n.user?.wallets?.[t]||null)?.trim()||null,ve=(n,t)=>sr(n.user?.wallets?.[t]||null)?.trim()||null;var C=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===f.Tuple&&Array.isArray(r)){if(r.length===0)return t+c.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(c.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+r.join(c.ArgListSeparator)}if(t===f.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})${c.ArgParamsSeparator}`;let a=s.map(o=>{let[l,p]=this.getTypeAndValue(e[o]);return`(${o}${c.ArgParamsSeparator}${l})${p}`});return`${t}(${i})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}if(t===f.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${c.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(c.ArgParamsSeparator))){let e=r[0],i=e.indexOf(c.ArgParamsSeparator),s=e.substring(0,i),a=r.map(l=>{let p=l.indexOf(c.ArgParamsSeparator),u=l.substring(p+1);return s.startsWith(f.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),o=s.startsWith(f.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+s+c.ArgParamsSeparator+a.join(o)}return t+c.ArgParamsSeparator+r.join(c.ArgListSeparator)}if(t===f.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?f.Asset+c.ArgParamsSeparator+r.identifier+c.ArgCompositeSeparator+String(r.amount)+c.ArgCompositeSeparator+String(r.decimals):f.Asset+c.ArgParamsSeparator+r.identifier+c.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+c.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(c.ArgParamsSeparator),e=r[0],i=r.slice(1).join(c.ArgParamsSeparator);if(e==="null")return[e,null];if(e===f.Option){let[s,a]=i.split(c.ArgParamsSeparator);return[f.Option+c.ArgParamsSeparator+s,a||null]}if(e===f.Vector){let s=i.indexOf(c.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),l=a.startsWith(f.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(o?o.split(l):[]).map(d=>this.stringToNative(a+c.ArgParamsSeparator+d)[1]);return[f.Vector+c.ArgParamsSeparator+a,u]}else if(e.startsWith(f.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),o=i.split(c.ArgCompositeSeparator).map((l,p)=>this.stringToNative(`${s[p]}${c.IdentifierParamSeparator}${l}`)[1]);return[e,o]}else if(e.startsWith(f.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(c.ArgListSeparator).forEach(l=>{let p=l.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(p){let[,u,d,h]=p;o[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${h}`)[1]}}),[e,o]}else{if(e===f.String)return[e,i];if(e===f.Uint8||e===f.Uint16||e===f.Uint32)return[e,Number(i)];if(e===f.Uint64||e===f.Uint128||e===f.Uint256||e===f.Biguint)return[e,BigInt(i||0)];if(e===f.Bool)return[e,i==="true"];if(e===f.Address)return[e,i];if(e===f.Hex)return[e,i];if(e===f.Asset){let[s,a]=i.split(c.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,l]=this.stringToNative(`${a}:${i}`);return[e,l]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(c.ArgParamsSeparator)){let[r,e]=t.split(c.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[f.Uint32,t]:typeof t=="bigint"?[f.Uint64,t]:typeof t=="boolean"?[f.Bool,t]:[typeof t,t]}};var Se=n=>new C().nativeToString(f.String,n),Te=n=>new C().nativeToString(f.Uint8,n),be=n=>new C().nativeToString(f.Uint16,n),Pe=n=>new C().nativeToString(f.Uint32,n),Ee=n=>new C().nativeToString(f.Uint64,n),Re=n=>new C().nativeToString(f.Biguint,n),Be=n=>new C().nativeToString(f.Bool,n),$e=n=>new C().nativeToString(f.Address,n),Rt=n=>new C().nativeToString(f.Asset,n),Ve=n=>new C().nativeToString(f.Hex,n),Ne=(n,t)=>{if(t===null)return f.Option+c.ArgParamsSeparator;let r=n(t),e=r.indexOf(c.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return f.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+s},Oe=(...n)=>new C().nativeToString(f.Tuple,n),He=n=>new C().nativeToString(f.Struct,n),Fe=n=>new C().nativeToString(f.Vector,n);import or from"ajv";var Bt=class{constructor(t){this.pendingBrand={protocol:Q("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 or,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import pr 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}=N(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 pr({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 $t=class{constructor(t){this.config=t;this.pendingWarp={protocol:Q("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}async build(){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"),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,lr);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,cr))}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)}}},Vt=new C,cr=(n,t)=>typeof t=="bigint"?Vt.nativeToString("biguint",t):t,lr=(n,t)=>typeof t=="string"&&t.startsWith(f.Biguint+":")?Vt.stringToNative(t)[1]:t;var O=class O{get(t){let r=O.cache.get(t);return r?Date.now()>r.expiresAt?(O.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;O.cache.set(t,{value:r,expiresAt:i})}forget(t){O.cache.delete(t)}clear(){O.cache.clear()}};O.cache=new Map;var _=O;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(c.Vars.Query+c.ArgParamsSeparator)){let l=o.slice(c.Vars.Query.length+1),[p,u]=l.split(c.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(p):null,W=r.queries?.[p]||null||d;W&&s(a,W)}else if(o.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=o.slice(c.Vars.Env.length+1),[p,u]=l.split(c.ArgCompositeSeparator),h={...this.config.vars,...r.envs}?.[p];h&&s(a,h)}else o===c.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(c.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(c.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(c.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)||t.includes(`{{${a}:`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(c.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString())),s=this.replacePlaceholdersWithChain(s,a.Placeholder,i,a.Accessor)}),s}replacePlaceholdersWithChain(t,r,e,i){let s=new RegExp(`\\{\\{${r}:([^}]+)\\}\\}`,"g");return t.replace(s,(a,o)=>{let l=o.trim().toLowerCase();if(!this.adapters)return a;try{let p=y(l,this.adapters),u={config:this.config,adapter:p},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 l=o;l&&typeof l=="object"&&"identifier"in l&&"amount"in l&&(i[`primary.${a}.token`]=String(l.identifier),i[`primary.${a}.amount`]=String(l.amount))}}),i}};var z=class{constructor(t,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 C,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=P(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=y(a.name,this.adapters),l=new E(this.config,o,this.adapters),p=await l.apply(t,i),u=P(p,r),{action:d,index:h}=N(p),W=this.getStringTypedInputs(d,e),m=await this.getResolvedInputs(a.name,d,W,l),g=await this.getModifiedInputs(m),v=[],A=[];h===r-1?(v=m,A=g):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(a.name,u,e,l),A=await this.getModifiedInputs(v));let b=A.find(w=>w.input.position==="receiver"||w.input.position==="destination")?.value,R=this.getDestinationFromAction(u),x=b?this.serializer.stringToNative(b)[1]:R;if(x&&(x=l.applyInputs(x,A,this.serializer,g)),!x&&s.type!=="collect"&&s.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let j=this.getPreparedArgs(u,A);j=j.map(w=>l.applyInputs(w,A,this.serializer,g));let D=A.find(w=>w.input.position==="value")?.value||null,T="value"in u?u.value:null,V=D?.split(c.ArgParamsSeparator)[1]||T||"0",k=l.applyInputs(V,A,this.serializer,g),Ft=BigInt(k),Ut=A.filter(w=>w.input.position==="transfer"&&w.value).map(w=>w.value),Lt=[...("transfers"in u?u.transfers:[])||[],...Ut||[]].map(w=>{let qt=l.applyInputs(w,A,this.serializer,g);return this.serializer.stringToNative(qt)[1]}),jt=A.find(w=>w.input.position==="data")?.value,Dt="data"in u?u.data||"":null,ht=jt||Dt||null,Mt=ht?l.applyInputs(ht,A,this.serializer,g):null,mt={warp:p,chain:a,action:r,destination:x,args:j,value:Ft,transfers:Lt,data:Mt,resolvedInputs:A};return this.cache.set(gt.WarpExecutable(this.config.env,p.meta?.hash||"",r),mt.resolvedInputs,Nt.OneWeek),mt}async getChainInfoForWarp(t,r){if(t.chain)return y(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(c.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(l=>this.preprocessInput(t,l))),o=(l,p)=>{if(l.source==="query"){let u=this.url.searchParams.get(l.name);return u?this.serializer.nativeToString(l.type,u):null}else if(l.source===c.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(l.source==="hidden"){if(l.default===void 0)return null;let u=i?i.applyInputs(String(l.default),[],this.serializer):String(l.default);return this.serializer.nativeToString(l.type,u)}else return a[p]||null};return s.map((l,p)=>{let u=o(l,p),d=l.default!==void 0?i?i.applyInputs(String(l.default),[],this.serializer):String(l.default):void 0;return{input:l,value:u||(d!==void 0?this.serializer.nativeToString(l.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(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(p=>p.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 l=K(o,+a);r.push({...i,value:`${i.input.type}:${l}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=K(a,+s);r.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let s=i.input.modifier.substring(c.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let o=this.buildInputContext(t,e,i),l=await a.run(s,o);if(l==null)r.push(i);else{let p=this.serializer.nativeToString(i.input.type,l);r.push({...i,value:p})}}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,[,l]=this.serializer.stringToNative(a.value);if(i[o]=l,a.input.type==="asset"&&typeof l=="object"&&l!==null){let p=l;"identifier"in p&&"amount"in p&&(i[`${o}.token`]=String(p.identifier),i[`${o}.amount`]=String(p.amount),i[`${o}.identifier`]=String(p.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=y(t,this.adapters);if(e==="asset"){let[a,o,l]=i.split(c.ArgCompositeSeparator);if(l)return r;let p=await s.dataLoader.getAsset(a);if(!p)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof p.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=K(o,p.decimals);return Rt({...p,amount:u})}else return r}catch(e){throw I.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,l]=this.serializer.stringToNative(a),p=l;if(!p||typeof p!="object"||!("identifier"in p)||!("amount"in p))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",p.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",p.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(l=>l.inputs?.some(p=>p.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(l=>l.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 y(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 z(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],o=[],{action:l,index:p}=N(t);for(let u=1;u<=t.actions.length;u++){let d=P(t,u);if(!pt(d,t))continue;let{tx:h,chain:W,immediateExecution:m,executable:g}=await this.executeAction(t,u,r,e);h&&i.push(h),W&&(s=W),m&&a.push(m),g&&u===p+1&&g.resolvedInputs&&(o=$(g.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=P(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 p=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(p):yt.open(p,"_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 p=await this.executeCollect(a);return p.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:a}):p.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(p.output._DATA),result:p}),{tx:null,chain:null,immediateExecution:null,executable:a})}if(s.type==="mcp"){let p=await this.executeMcp(a);return p.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:a}):p.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(p.output._DATA),result:p}),{tx:null,chain:null,immediateExecution:p,executable:a})}let o=y(a.chain.name,this.adapters);if(s.type==="query"){let p=await o.executor.executeQuery(a);return p.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:p,tx:null})):this.handlers?.onError?.({message:JSON.stringify(p.output._DATA),result:p}),{tx:null,chain:a.chain,immediateExecution:p,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=y(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 l=r[o],p=o+1;if(!l){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,p),h={status:"error",warp:t,action:p,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 ${p} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,p,l);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:p,chain:e,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else{let a=s.find(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=P(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:l}=await tt(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",o,l)}async doHttpRequest(t,r,e,i,s){let a=new E(this.config,y(t.chain.name,this.adapters),this.adapters),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:d,nonce:h,expiresAt:W}=await dt(e,`${t.chain.name}-adapter`),m=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:d,chain:t.chain}));if(m){let g=ft(e,m,h,W);Object.entries(g).forEach(([v,A])=>o.set(v,A))}}r.headers&&Object.entries(r.headers).forEach(([d,h])=>{let W=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(d,W)});let l=r.method||"GET",p=l==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());I.debug("WarpExecutor: Executing HTTP collect",{url:u,method:l,headers:o,body:p});try{let d=await fetch(u,{method:l,headers:o,body:p});I.debug("Collect response status",{status:d.status});let h=await d.json();I.debug("Collect response content",{content:h});let{values:W,output:m}=await tt(t.warp,h,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),d.ok?"success":"error",W,m,h)}catch(d){I.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=P(t.warp,t.action);if(!i.destination){let W=$(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:W}}let s,a;try{s=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,a=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let 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("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let o=this.factory.getSerializer(),l=new E(this.config,y(t.chain.name,this.adapters),this.adapters),p=i.destination,u=l.applyInputs(p.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(p.tool,t.resolvedInputs,this.factory.getSerializer()),h={};p.headers&&Object.entries(p.headers).forEach(([W,m])=>{let g=l.applyInputs(m,t.resolvedInputs,this.factory.getSerializer());h[W]=g}),I.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let W=new a(new URL(u),{requestInit:{headers:h}}),m=new s({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await m.connect(W);let g={};t.resolvedInputs.forEach(({input:x,value:j})=>{if(j&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let D=x.position.replace("payload:",""),[T,V]=o.stringToNative(j);if(T==="string")g[D]=String(V);else if(T==="bool")g[D]=!!V;else if(T==="uint8"||T==="uint16"||T==="uint32"||T==="uint64"||T==="uint128"||T==="uint256"||T==="biguint"){let k=Number(V);g[D]=(Number.isInteger(k),k)}else g[D]=V}}),r&&Object.assign(g,r);let v=await m.callTool({name:d,arguments:g});await m.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:b,output:R}=await tt(t.warp,A,t.action,t.resolvedInputs,o,this.config);return this.buildCollectResult(t,e,"success",b,R,v)}catch(W){I.error("WarpExecutor: Error executing MCP",W);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:W},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}buildCollectResult(t,r,e,i,s,a){let o=Pt(this.config,this.adapters,t.warp,t.action,s),l=$(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:bt(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}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),l=y(o.name,this.adapters),p=new E(this.config,l,this.adapters),{action:u}=N(t),d=this.factory.getStringTypedInputs(u,e),h=await this.factory.getResolvedInputs(o.name,u,d,p),W=await this.factory.getModifiedInputs(h),m;if(s)m=s;else{let A=await this.factory.getResolvedInputs(o.name,r,this.factory.getStringTypedInputs(r,e),p);m=await this.factory.getModifiedInputs(A)}let g=p.buildInputBag(m,this.factory.getSerializer(),W),v=Ct(r.when,g);return It(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 I.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(c.HttpProtocolPrefix)?!!G(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),a=(await Promise.all(i)).filter(p=>p.match),o=a.length>0,l=a.map(p=>({url:p.url,warp:p.warp}));return{match:o,output:l}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(c.HttpProtocolPrefix)?G(t):B(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,l=null,p=null,u=y(i.chain,this.adapters),d=t.startsWith(c.HttpProtocolPrefix)?St(t):Tt(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let g=await u.registry.getInfoByHash(a,r);l=g.registryInfo,p=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,r);l=g.registryInfo,p=g.brand,g.registryInfo&&(o=await u.builder().createFromTransactionHash(g.registryInfo.hash,r))}if(o&&o.meta&&(ur(o,u.chainInfo.name,l,i.identifier),o.meta.query=d),!o)return e;let h=o.chain||u.chainInfo.name,W=y(h,this.adapters),m=await new E(this.config,W,this.adapters).apply(o);return{match:!0,url:t,warp:m,chain:h,registryInfo:l,brand:p}}catch(s){return I.error("Error detecting warp link",s),e}}},ur=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?ct(t,"alias",r.alias):ct(t,"hash",r?.hash??e))};var Ot=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new nt(this.config,this.adapters,t)}async detectWarp(t,r){return new at(this.config,this.adapters).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 m=await fetch(t);if(!m.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await m.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let l=this.createExecutor(e),{txs:p,chain:u,immediateExecutions:d,resolvedInputs:h}=await l.execute(o,r,{queries:i.queries});return{txs:p,chain:u,immediateExecutions:d,evaluateOutput:async m=>{await l.evaluateOutput(o,m)},resolvedInputs:h}}async createInscriptionTransaction(t,r){return await y(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return y(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=B(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return y(e.chain,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return y(t,this.adapters).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 y(t,this.adapters).explorer}getOutput(t){return y(t,this.adapters).output}async getRegistry(t){let r=y(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return y(t,this.adapters).dataLoader}getWallet(t){return y(t,this.adapters).wallet}get factory(){return new z(this.config,this.adapters)}get index(){return new it(this.config)}get linkBuilder(){return new q(this.config,this.adapters)}createBuilder(t){return y(t,this.adapters).builder()}createAbiBuilder(t){return y(t,this.adapters).abiBuilder()}createBrandBuilder(t){return y(t,this.adapters).brandBuilder()}createSerializer(t){return y(t,this.adapters).serializer}resolveText(t){return X(t,this.config)}};var Ht=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,$r as WARP_LANGUAGES,Bt as WarpBrandBuilder,$t as WarpBuilder,et as WarpCache,gt as WarpCacheKey,zt as WarpChainName,Ot as WarpClient,H as WarpConfig,c as WarpConstants,nt as WarpExecutor,z as WarpFactory,it as WarpIndex,f as WarpInputTypes,E as WarpInterpolator,q as WarpLinkBuilder,at as WarpLinkDetecter,I as WarpLogger,M as WarpProtocolVersions,C as WarpSerializer,Ht as WarpTypeRegistry,rt as WarpValidator,$e as address,bt as applyOutputToMessages,Rt as asset,Re as biguint,Be as bool,Y as buildMappedOutput,Xt as buildNestedPayload,Ir as bytesToBase64,kt as bytesToHex,Z as cleanWarpIdentifier,ft as createAuthHeaders,dt as createAuthMessage,Sr as createCryptoProvider,ge as createHttpAuthHeaders,nr as createSignableMessage,Nr as createWarpI18nText,ct as createWarpIdentifier,Yt as evaluateOutputCommon,It as evaluateWhenCondition,tt as extractCollectOutput,G as extractIdentifierInfoFromUrl,Tt as extractQueryStringFromIdentifier,St as extractQueryStringFromUrl,$ as extractResolvedInputValues,Pr as extractWarpSecrets,y as findWarpAdapterForChain,Wt as getCryptoProvider,Wr as getEventNameFromWarp,Q as getLatestProtocolIdentifier,Pt as getNextInfo,ie as getProviderConfig,vt as getRandomBytes,At as getRandomHex,P as getWarpActionByIndex,Ar as getWarpBrandLogoUrl,B as getWarpInfoFromIdentifier,N as getWarpPrimaryAction,ir as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,sr as getWarpWalletMnemonic,ve as getWarpWalletMnemonicFromConfig,ar as getWarpWalletPrivateKey,We as getWarpWalletPrivateKeyFromConfig,jr as hasInputPrefix,Ve as hex,Fr as isEqualWarpIdentifier,pt as isWarpActionAutoExecute,Vr as isWarpI18nText,Et as mergeNestedPayload,Ne as option,er as parseOutputOutIndex,me as parseSignedMessage,U as replacePlaceholders,Ct as replacePlaceholdersInWhenExpression,X as resolveWarpText,yt as safeWindow,Cr as setCryptoProvider,K as shiftBigintBy,lt as splitInput,Se as string,He as struct,wr as testCryptoAvailability,Zt as toInputPayloadValue,xt as toPreviewText,Oe as tuple,be as uint16,Pe as uint32,Ee as uint64,Te as uint8,he as validateSignedMessage,Fe as vector};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "3.0.0-beta.167",
3
+ "version": "3.0.0-beta.169",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",
@@ -30,8 +30,8 @@
30
30
  "jest": "^30.2.0",
31
31
  "jest-environment-jsdom": "^30.2.0",
32
32
  "jest-fetch-mock": "^3.0.3",
33
- "ts-jest": "^29.4.5",
34
- "tsup": "^8.5.0",
33
+ "ts-jest": "^29.4.6",
34
+ "tsup": "^8.5.1",
35
35
  "typescript": "^5.9.3"
36
36
  },
37
37
  "publishConfig": {