@vleap/warps 3.0.0-alpha.122 → 3.0.0-alpha.123

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
@@ -33,6 +33,12 @@ type WarpCacheType = 'memory' | 'localStorage';
33
33
  type WarpChainEnv = 'mainnet' | 'testnet' | 'devnet';
34
34
  type ProtocolName = 'warp' | 'brand' | 'abi';
35
35
 
36
+ type WarpLanguage = 'en' | 'es' | 'fr' | 'de' | 'it' | 'pt' | 'ru' | 'zh' | 'ja' | 'ko' | 'ar' | 'hi' | 'nl' | 'sv' | 'da' | 'no' | 'fi' | 'pl' | 'tr' | 'el' | 'he' | 'th' | 'vi' | 'id' | 'ms' | 'tl' | string;
37
+ type WarpText = string | WarpI18nText;
38
+ type WarpI18nText = {
39
+ [language: string]: string;
40
+ };
41
+
36
42
  type WarpTrustStatus = 'unverified' | 'verified' | 'blacklisted';
37
43
  type WarpRegistryInfo = {
38
44
  hash: string;
@@ -114,6 +120,7 @@ type WarpClientConfig = {
114
120
  wallets?: WarpUserWallets;
115
121
  };
116
122
  preferences?: {
123
+ language?: WarpLanguage;
117
124
  explorers?: Record<WarpChain, WarpExplorerName>;
118
125
  };
119
126
  providers?: Record<WarpChain, WarpProviderConfig>;
@@ -311,8 +318,8 @@ type Warp = {
311
318
  protocol: string;
312
319
  chain?: WarpChain;
313
320
  name: string;
314
- title: string;
315
- description: string | null;
321
+ title: WarpText;
322
+ description: WarpText | null;
316
323
  bot?: string;
317
324
  preview?: string;
318
325
  vars?: Record<WarpVarPlaceholder, string>;
@@ -333,8 +340,8 @@ type WarpActionIndex = number;
333
340
  type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link';
334
341
  type WarpTransferAction = {
335
342
  type: WarpActionType;
336
- label: string;
337
- description?: string | null;
343
+ label: WarpText;
344
+ description?: WarpText | null;
338
345
  address?: string;
339
346
  data?: string;
340
347
  value?: string;
@@ -346,8 +353,8 @@ type WarpTransferAction = {
346
353
  };
347
354
  type WarpContractAction = {
348
355
  type: WarpActionType;
349
- label: string;
350
- description?: string | null;
356
+ label: WarpText;
357
+ description?: WarpText | null;
351
358
  address?: string;
352
359
  func?: string | null;
353
360
  args?: string[];
@@ -362,8 +369,8 @@ type WarpContractAction = {
362
369
  };
363
370
  type WarpQueryAction = {
364
371
  type: WarpActionType;
365
- label: string;
366
- description?: string | null;
372
+ label: WarpText;
373
+ description?: WarpText | null;
367
374
  address?: string;
368
375
  func?: string;
369
376
  args?: string[];
@@ -375,8 +382,8 @@ type WarpQueryAction = {
375
382
  };
376
383
  type WarpCollectAction = {
377
384
  type: WarpActionType;
378
- label: string;
379
- description?: string | null;
385
+ label: WarpText;
386
+ description?: WarpText | null;
380
387
  destination: {
381
388
  url: string;
382
389
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
@@ -389,8 +396,8 @@ type WarpCollectAction = {
389
396
  };
390
397
  type WarpLinkAction = {
391
398
  type: WarpActionType;
392
- label: string;
393
- description?: string | null;
399
+ label: WarpText;
400
+ description?: WarpText | null;
394
401
  url: string;
395
402
  inputs?: WarpActionInput[];
396
403
  primary?: boolean;
@@ -408,7 +415,8 @@ type WarpActionInputModifier = 'scale';
408
415
  type WarpActionInput = {
409
416
  name: string;
410
417
  as?: string;
411
- description?: string | null;
418
+ label?: WarpText;
419
+ description?: WarpText | null;
412
420
  bot?: string;
413
421
  type: WarpActionInputType;
414
422
  position?: WarpActionInputPosition;
@@ -417,7 +425,7 @@ type WarpActionInput = {
417
425
  min?: number | WarpVarPlaceholder;
418
426
  max?: number | WarpVarPlaceholder;
419
427
  pattern?: string;
420
- patternDescription?: string;
428
+ patternDescription?: WarpText;
421
429
  options?: string[] | {
422
430
  [key: string]: string;
423
431
  };
@@ -596,6 +604,10 @@ declare const toPreviewText: (text: string, maxChars?: number) => string;
596
604
  declare const replacePlaceholders: (message: string, bag: Record<string, any>) => string;
597
605
  declare const applyResultsToMessages: (warp: Warp, results: Record<string, any>) => Record<string, string>;
598
606
 
607
+ declare const resolveWarpText: (text: WarpText, language?: WarpLanguage, config?: WarpClientConfig) => string;
608
+ declare const isWarpI18nText: (text: WarpText) => text is WarpI18nText;
609
+ declare const createWarpI18nText: (translations: Record<string, string>) => WarpI18nText;
610
+
599
611
  declare const getWarpInfoFromIdentifier: (prefixedIdentifier: string) => {
600
612
  chainPrefix: string;
601
613
  type: WarpIdType;
@@ -775,6 +787,7 @@ declare class WarpBuilder implements BaseWarpBuilder {
775
787
  build(): Promise<Warp>;
776
788
  getDescriptionPreview(description: string, maxChars?: number): string;
777
789
  private ensure;
790
+ private ensureWarpText;
778
791
  private validate;
779
792
  }
780
793
 
@@ -999,4 +1012,4 @@ declare class WarpValidator {
999
1012
  private validateSchema;
1000
1013
  }
1001
1014
 
1002
- export { type Adapter, type AdapterFactory, type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, 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, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecution, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, 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, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpProviderConfig, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, address, applyResultsToMessages, asset, biguint, bool, buildNestedPayload, bytesToBase64, bytesToHex, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, extractWarpSecrets, findWarpAdapterByPrefix, findWarpAdapterForChain, getCryptoProvider, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getProviderUrl, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, isWarpActionAutoExecute, mergeNestedPayload, option, parseResultsOutIndex, parseSignedMessage, replacePlaceholders, safeWindow, setCryptoProvider, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateSignedMessage, vector };
1015
+ export { type Adapter, type AdapterFactory, type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, 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, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecution, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, 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, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLanguage, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpProviderConfig, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, 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, applyResultsToMessages, asset, biguint, bool, buildNestedPayload, bytesToBase64, bytesToHex, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, extractWarpSecrets, findWarpAdapterByPrefix, findWarpAdapterForChain, getCryptoProvider, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getProviderUrl, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, isWarpActionAutoExecute, isWarpI18nText, mergeNestedPayload, option, parseResultsOutIndex, parseSignedMessage, replacePlaceholders, resolveWarpText, safeWindow, setCryptoProvider, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateSignedMessage, vector };
package/dist/index.d.ts CHANGED
@@ -33,6 +33,12 @@ type WarpCacheType = 'memory' | 'localStorage';
33
33
  type WarpChainEnv = 'mainnet' | 'testnet' | 'devnet';
34
34
  type ProtocolName = 'warp' | 'brand' | 'abi';
35
35
 
36
+ type WarpLanguage = 'en' | 'es' | 'fr' | 'de' | 'it' | 'pt' | 'ru' | 'zh' | 'ja' | 'ko' | 'ar' | 'hi' | 'nl' | 'sv' | 'da' | 'no' | 'fi' | 'pl' | 'tr' | 'el' | 'he' | 'th' | 'vi' | 'id' | 'ms' | 'tl' | string;
37
+ type WarpText = string | WarpI18nText;
38
+ type WarpI18nText = {
39
+ [language: string]: string;
40
+ };
41
+
36
42
  type WarpTrustStatus = 'unverified' | 'verified' | 'blacklisted';
37
43
  type WarpRegistryInfo = {
38
44
  hash: string;
@@ -114,6 +120,7 @@ type WarpClientConfig = {
114
120
  wallets?: WarpUserWallets;
115
121
  };
116
122
  preferences?: {
123
+ language?: WarpLanguage;
117
124
  explorers?: Record<WarpChain, WarpExplorerName>;
118
125
  };
119
126
  providers?: Record<WarpChain, WarpProviderConfig>;
@@ -311,8 +318,8 @@ type Warp = {
311
318
  protocol: string;
312
319
  chain?: WarpChain;
313
320
  name: string;
314
- title: string;
315
- description: string | null;
321
+ title: WarpText;
322
+ description: WarpText | null;
316
323
  bot?: string;
317
324
  preview?: string;
318
325
  vars?: Record<WarpVarPlaceholder, string>;
@@ -333,8 +340,8 @@ type WarpActionIndex = number;
333
340
  type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link';
334
341
  type WarpTransferAction = {
335
342
  type: WarpActionType;
336
- label: string;
337
- description?: string | null;
343
+ label: WarpText;
344
+ description?: WarpText | null;
338
345
  address?: string;
339
346
  data?: string;
340
347
  value?: string;
@@ -346,8 +353,8 @@ type WarpTransferAction = {
346
353
  };
347
354
  type WarpContractAction = {
348
355
  type: WarpActionType;
349
- label: string;
350
- description?: string | null;
356
+ label: WarpText;
357
+ description?: WarpText | null;
351
358
  address?: string;
352
359
  func?: string | null;
353
360
  args?: string[];
@@ -362,8 +369,8 @@ type WarpContractAction = {
362
369
  };
363
370
  type WarpQueryAction = {
364
371
  type: WarpActionType;
365
- label: string;
366
- description?: string | null;
372
+ label: WarpText;
373
+ description?: WarpText | null;
367
374
  address?: string;
368
375
  func?: string;
369
376
  args?: string[];
@@ -375,8 +382,8 @@ type WarpQueryAction = {
375
382
  };
376
383
  type WarpCollectAction = {
377
384
  type: WarpActionType;
378
- label: string;
379
- description?: string | null;
385
+ label: WarpText;
386
+ description?: WarpText | null;
380
387
  destination: {
381
388
  url: string;
382
389
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
@@ -389,8 +396,8 @@ type WarpCollectAction = {
389
396
  };
390
397
  type WarpLinkAction = {
391
398
  type: WarpActionType;
392
- label: string;
393
- description?: string | null;
399
+ label: WarpText;
400
+ description?: WarpText | null;
394
401
  url: string;
395
402
  inputs?: WarpActionInput[];
396
403
  primary?: boolean;
@@ -408,7 +415,8 @@ type WarpActionInputModifier = 'scale';
408
415
  type WarpActionInput = {
409
416
  name: string;
410
417
  as?: string;
411
- description?: string | null;
418
+ label?: WarpText;
419
+ description?: WarpText | null;
412
420
  bot?: string;
413
421
  type: WarpActionInputType;
414
422
  position?: WarpActionInputPosition;
@@ -417,7 +425,7 @@ type WarpActionInput = {
417
425
  min?: number | WarpVarPlaceholder;
418
426
  max?: number | WarpVarPlaceholder;
419
427
  pattern?: string;
420
- patternDescription?: string;
428
+ patternDescription?: WarpText;
421
429
  options?: string[] | {
422
430
  [key: string]: string;
423
431
  };
@@ -596,6 +604,10 @@ declare const toPreviewText: (text: string, maxChars?: number) => string;
596
604
  declare const replacePlaceholders: (message: string, bag: Record<string, any>) => string;
597
605
  declare const applyResultsToMessages: (warp: Warp, results: Record<string, any>) => Record<string, string>;
598
606
 
607
+ declare const resolveWarpText: (text: WarpText, language?: WarpLanguage, config?: WarpClientConfig) => string;
608
+ declare const isWarpI18nText: (text: WarpText) => text is WarpI18nText;
609
+ declare const createWarpI18nText: (translations: Record<string, string>) => WarpI18nText;
610
+
599
611
  declare const getWarpInfoFromIdentifier: (prefixedIdentifier: string) => {
600
612
  chainPrefix: string;
601
613
  type: WarpIdType;
@@ -775,6 +787,7 @@ declare class WarpBuilder implements BaseWarpBuilder {
775
787
  build(): Promise<Warp>;
776
788
  getDescriptionPreview(description: string, maxChars?: number): string;
777
789
  private ensure;
790
+ private ensureWarpText;
778
791
  private validate;
779
792
  }
780
793
 
@@ -999,4 +1012,4 @@ declare class WarpValidator {
999
1012
  private validateSchema;
1000
1013
  }
1001
1014
 
1002
- export { type Adapter, type AdapterFactory, type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, 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, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecution, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, 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, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpProviderConfig, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, address, applyResultsToMessages, asset, biguint, bool, buildNestedPayload, bytesToBase64, bytesToHex, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, extractWarpSecrets, findWarpAdapterByPrefix, findWarpAdapterForChain, getCryptoProvider, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getProviderUrl, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, isWarpActionAutoExecute, mergeNestedPayload, option, parseResultsOutIndex, parseSignedMessage, replacePlaceholders, safeWindow, setCryptoProvider, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateSignedMessage, vector };
1015
+ export { type Adapter, type AdapterFactory, type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, 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, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecution, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, 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, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLanguage, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpProviderConfig, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, 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, applyResultsToMessages, asset, biguint, bool, buildNestedPayload, bytesToBase64, bytesToHex, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, extractWarpSecrets, findWarpAdapterByPrefix, findWarpAdapterForChain, getCryptoProvider, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getProviderUrl, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, isWarpActionAutoExecute, isWarpI18nText, mergeNestedPayload, option, parseResultsOutIndex, parseSignedMessage, replacePlaceholders, resolveWarpText, safeWindow, setCryptoProvider, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateSignedMessage, vector };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Dt=Object.create;var K=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var Mt=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,kt=Object.prototype.hasOwnProperty;var Gt=(n,t)=>{for(var r in t)K(n,r,{get:t[r],enumerable:!0})},St=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Mt(t))!kt.call(n,i)&&i!==r&&K(n,i,{get:()=>t[i],enumerable:!(e=qt(t,i))||e.enumerable});return n};var X=(n,t,r)=>(r=n!=null?Dt(zt(n)):{},St(t||!n||!n.__esModule?K(r,"default",{value:n,enumerable:!0}):r,n)),Jt=n=>St(K({},"__esModule",{value:!0}),n);var Tr={};Gt(Tr,{BrowserCryptoProvider:()=>_,CacheTtl:()=>At,NodeCryptoProvider:()=>Z,WarpBrandBuilder:()=>Wt,WarpBuilder:()=>yt,WarpCache:()=>z,WarpCacheKey:()=>xt,WarpChainName:()=>It,WarpClient:()=>vt,WarpConfig:()=>T,WarpConstants:()=>o,WarpExecutor:()=>k,WarpFactory:()=>U,WarpIndex:()=>G,WarpInputTypes:()=>d,WarpInterpolator:()=>N,WarpLinkBuilder:()=>$,WarpLinkDetecter:()=>J,WarpLogger:()=>x,WarpProtocolVersions:()=>R,WarpSerializer:()=>y,WarpTypeRegistry:()=>Ct,WarpValidator:()=>D,address:()=>xr,applyResultsToMessages:()=>ut,asset:()=>mt,biguint:()=>yr,bool:()=>Ar,buildNestedPayload:()=>gt,bytesToBase64:()=>Kt,bytesToHex:()=>bt,createAuthHeaders:()=>at,createAuthMessage:()=>it,createCryptoProvider:()=>_t,createHttpAuthHeaders:()=>pr,createSignableMessage:()=>Bt,evaluateResultsCommon:()=>Et,extractCollectResults:()=>ht,extractIdentifierInfoFromUrl:()=>F,extractWarpSecrets:()=>Zt,findWarpAdapterByPrefix:()=>P,findWarpAdapterForChain:()=>h,getCryptoProvider:()=>ot,getLatestProtocolIdentifier:()=>O,getNextInfo:()=>ft,getProviderConfig:()=>ar,getProviderUrl:()=>ir,getRandomBytes:()=>pt,getRandomHex:()=>ct,getWarpActionByIndex:()=>S,getWarpInfoFromIdentifier:()=>I,getWarpPrimaryAction:()=>Y,getWarpWalletAddress:()=>$t,getWarpWalletAddressFromConfig:()=>b,getWarpWalletMnemonic:()=>Nt,getWarpWalletMnemonicFromConfig:()=>dr,getWarpWalletPrivateKey:()=>Vt,getWarpWalletPrivateKeyFromConfig:()=>ur,hasInputPrefix:()=>rr,hex:()=>vr,isWarpActionAutoExecute:()=>tt,mergeNestedPayload:()=>nt,option:()=>Cr,parseResultsOutIndex:()=>Rt,parseSignedMessage:()=>lr,replacePlaceholders:()=>rt,safeWindow:()=>st,setCryptoProvider:()=>Qt,shiftBigintBy:()=>j,splitInput:()=>et,string:()=>fr,struct:()=>Sr,testCryptoAvailability:()=>Xt,toPreviewText:()=>lt,tuple:()=>wr,uint16:()=>hr,uint32:()=>mr,uint64:()=>Wr,uint8:()=>gr,validateSignedMessage:()=>cr,vector:()=>Ir});module.exports=Jt(Tr);var It=(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))(It||{}),o={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},d={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},st=typeof window<"u"?window:{open:()=>{}};var R={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},T={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${R.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${R.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",o.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 _=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}},Z=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"}`)}}},B=null;function ot(){if(B)return B;if(typeof window<"u"&&window.crypto)return B=new _,B;if(typeof process<"u"&&process.versions?.node)return B=new Z,B;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Qt(n){B=n}async function pt(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||ot()).getRandomBytes(n)}function bt(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 Kt(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 ct(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await pt(n/2,t);return bt(r)}async function Xt(){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 pt(16),n.randomBytes=!0}catch{}return n}function _t(){return ot()}var Zt=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${o.Vars.Env}:`)).map(t=>{let r=t.replace(`${o.Vars.Env}:`,"").trim(),[e,i]=r.split(o.ArgCompositeSeparator);return{key:e,description:i||null}});var h=(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},P=(n,t)=>{let r=t.find(e=>e.prefix.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for prefix: ${n}`);return r},O=n=>{if(n==="warp")return`warp:${R.Warp}`;if(n==="brand")return`brand:${R.Brand}`;if(n==="abi")return`abi:${R.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},S=(n,t)=>n?.actions[t-1],Y=n=>{let t=n.actions.find(a=>a.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let r=["transfer","contract","query","collect"],e=n.actions.filter(a=>!r.includes(a.type));if(e.length>0){let a=e[e.length-1];return{action:a,index:n.actions.indexOf(a)}}let s=[...n.actions].reverse().find(a=>r.includes(a.type));if(!s)throw new Error(`Warp has no primary action: ${n.meta?.hash}`);return{action:s,index:n.actions.indexOf(s)}},tt=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){let{action:r}=Y(t);return n===r||n.auto===!0}return!0},j=(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 p=a.slice(0,-s)||"0";return BigInt(p)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},lt=(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},rt=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),ut=(n,t)=>{let r=Object.entries(n.messages||{}).map(([e,i])=>[e,rt(i,t)]);return Object.fromEntries(r)};var Yt=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,tr=n=>{let t=o.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},Pt=n=>{let t=tr(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=Pt(s);return[i,...a]},I=n=>{let t=decodeURIComponent(n).trim(),r=t.split("?")[0],e=Pt(r);if(r.length===64&&/^[a-fA-F0-9]+$/.test(r))return{chainPrefix:o.IdentifierChainDefault,type:o.IdentifierType.Hash,identifier:t,identifierBase:r};if(e.length===2&&/^[a-zA-Z0-9]{62}$/.test(e[0])&&/^[a-zA-Z0-9]{2}$/.test(e[1]))return null;if(e.length===3){let[i,s,a]=e;if(s===o.IdentifierType.Alias||s===o.IdentifierType.Hash){let p=t.includes("?")?a+t.substring(t.indexOf("?")):a;return{chainPrefix:i,type:s,identifier:p,identifierBase:a}}}if(e.length===2){let[i,s]=e;if(i===o.IdentifierType.Alias||i===o.IdentifierType.Hash){let a=t.includes("?")?s+t.substring(t.indexOf("?")):s;return{chainPrefix:o.IdentifierChainDefault,type:i,identifier:a,identifierBase:s}}}if(e.length===2){let[i,s]=e;if(i!==o.IdentifierType.Alias&&i!==o.IdentifierType.Hash){let a=t.includes("?")?s+t.substring(t.indexOf("?")):s,p=Yt(s,i)?o.IdentifierType.Hash:o.IdentifierType.Alias;return{chainPrefix:i,type:p,identifier:a,identifierBase:s}}}return{chainPrefix:o.IdentifierChainDefault,type:o.IdentifierType.Alias,identifier:t,identifierBase:r}},F=n=>{let t=new URL(n),e=t.searchParams.get(o.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return I(i)};var et=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},rr=n=>{let t=new Set(Object.values(d));if(!n.includes(o.ArgParamsSeparator))return!1;let r=et(n)[0];return t.has(r)};var Tt=X(require("qr-code-styling"),1);var $=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(o.HttpProtocolPrefix)?!!F(t):!1}build(t,r,e){let i=this.config.clientUrl||T.DefaultClientUrl(this.config.env),s=h(t,this.adapters),a=r===o.IdentifierType.Alias?e:r+o.IdentifierParamSeparator+e,p=s.prefix+o.IdentifierParamSeparator+a,l=encodeURIComponent(p);return T.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${o.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let r=I(t);if(!r)return null;let e=P(r.chainPrefix,this.adapters);return e?this.build(e.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,e,i=512,s="white",a="black",p="#23F7DD"){let l=h(t,this.adapters),c=this.build(l.chainInfo.name,r,e);return new Tt.default({type:"svg",width:i,height:i,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var er="https://",ft=(n,t,r,e,i)=>{let s=r.actions?.[e]?.next||r.next||null;if(!s)return null;if(s.startsWith(er))return[{identifier:null,url:s}];let[a,p]=s.split("?");if(!p)return[{identifier:a,url:dt(t,a,n)}];let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let W=rt(p,{...r.vars,...i}),A=W?`${a}?${W}`:a;return[{identifier:A,url:dt(t,A,n)}]}let c=l[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let g=Array.isArray(i[f])?i[f]:[i[f]];if(g.length===0)return[];let m=l.filter(W=>W.includes(`{{${f}[]`)).map(W=>{let A=W.match(/\[\](\.[^}]+)?}}/),w=A&&A[1]||"";return{placeholder:W,field:w?w.slice(1):"",regex:new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return g.map(W=>{let A=p;for(let{regex:H,field:Q}of m){let L=Q?nr(W,Q):W;if(L==null)return null;A=A.replace(H,L)}if(A.includes("{{")||A.includes("}}"))return null;let w=A?`${a}?${A}`:a;return{identifier:w,url:dt(t,w,n)}}).filter(W=>W!==null)},dt=(n,t,r)=>{let[e,i]=t.split("?"),s=I(e)||{chainPrefix:o.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=P(s.chainPrefix,n);if(!a)throw new Error(`Adapter not found for chain ${s.chainPrefix}`);let p=new $(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((c,u)=>l.searchParams.set(u,c)),l.toString().replace(/\/\?/,"?")},nr=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function gt(n,t,r){return n.startsWith(o.Position.Payload)?n.slice(o.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function nt(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]=nt(r[e],t[e]):r[e]=t[e]}),r}var ir=(n,t,r,e)=>{let i=n.providers?.[t];return i?.[r]?i[r]:e},ar=(n,t)=>n.providers?.[t];var V=class V{static debug(...t){V.isTestEnv||console.debug(...t)}static info(...t){V.isTestEnv||console.info(...t)}static warn(...t){V.isTestEnv||console.warn(...t)}static error(...t){V.isTestEnv||console.error(...t)}};V.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=V;var ht=async(n,t,r,e,i,s)=>{let a=[],p=[],l={};for(let[c,u]of Object.entries(n.results||{})){if(u.startsWith(o.Transform.Prefix))continue;let f=Rt(u);if(f!==null&&f!==r){l[c]=null;continue}let[g,...m]=u.split("."),C=(W,A)=>A.reduce((w,H)=>w&&w[H]!==void 0?w[H]:null,W);if(g==="out"||g.startsWith("out[")){let W=m.length===0?t?.data||t:C(t,m);a.push(String(W)),p.push(W),l[c]=W}else l[c]=u}return{values:{string:a,native:p},results:await Et(n,l,r,e,i,s)}},Et=async(n,t,r,e,i,s)=>{if(!n.results)return t;let a={...t};return a=sr(a,n,r,e,i),a=await or(n,a,s),a},sr=(n,t,r,e,i)=>{let s={...n},a=S(t,r)?.inputs||[];for(let[p,l]of Object.entries(s))if(typeof l=="string"&&l.startsWith("input.")){let c=l.split(".")[1],u=a.findIndex(g=>g.as===c||g.name===c),f=u!==-1?e[u]?.value:null;s[p]=f?i.stringToNative(f)[1]:null}return s},or=async(n,t,r)=>{if(!n.results)return t;let e={...t},i=Object.entries(n.results).filter(([,s])=>s.startsWith(o.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(o.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.run!="function"))throw new Error("Transform results are 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(p){x.error(`Transform error for result '${s}':`,p),e[s]=null}return e},Rt=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 Bt(n,t,r,e=5){let i=await ct(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 it(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return Bt(n,i,r,5)}function at(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function pr(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await it(n,r,e),p=await t(i);return at(n,p,s,a)}function cr(n){let t=new Date(n).getTime();return Date.now()<t}function lr(n){try{let t=JSON.parse(n);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var $t=n=>n?typeof n=="string"?n:n.address:null,b=(n,t)=>$t(n.user?.wallets?.[t]||null),Vt=n=>n?typeof n=="string"?n:n.privateKey:null,Nt=n=>n?typeof n=="string"?n:n.mnemonic:null,ur=(n,t)=>Vt(n.user?.wallets?.[t]||null)?.trim()||null,dr=(n,t)=>Nt(n.user?.wallets?.[t]||null)?.trim()||null;var y=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===d.Tuple&&Array.isArray(r)){if(r.length===0)return t+o.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(o.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(o.ArgCompositeSeparator)})${o.ArgParamsSeparator}${s.join(o.ArgListSeparator)}`}return t+o.ArgParamsSeparator+r.join(o.ArgListSeparator)}if(t===d.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(p=>p!=="_name");if(s.length===0)return`${t}(${i})${o.ArgParamsSeparator}`;let a=s.map(p=>{let[l,c]=this.getTypeAndValue(e[p]);return`(${p}${o.ArgParamsSeparator}${l})${c}`});return`${t}(${i})${o.ArgParamsSeparator}${a.join(o.ArgListSeparator)}`}if(t===d.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${o.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(o.ArgParamsSeparator))){let e=r[0],i=e.indexOf(o.ArgParamsSeparator),s=e.substring(0,i),a=r.map(l=>{let c=l.indexOf(o.ArgParamsSeparator),u=l.substring(c+1);return s.startsWith(d.Tuple)?u.replace(o.ArgListSeparator,o.ArgCompositeSeparator):u}),p=s.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator;return t+o.ArgParamsSeparator+s+o.ArgParamsSeparator+a.join(p)}return t+o.ArgParamsSeparator+r.join(o.ArgListSeparator)}if(t===d.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?d.Asset+o.ArgParamsSeparator+r.identifier+o.ArgCompositeSeparator+String(r.amount)+o.ArgCompositeSeparator+String(r.decimals):d.Asset+o.ArgParamsSeparator+r.identifier+o.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+o.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(o.ArgParamsSeparator),e=r[0],i=r.slice(1).join(o.ArgParamsSeparator);if(e==="null")return[e,null];if(e===d.Option){let[s,a]=i.split(o.ArgParamsSeparator);return[d.Option+o.ArgParamsSeparator+s,a||null]}if(e===d.Vector){let s=i.indexOf(o.ArgParamsSeparator),a=i.substring(0,s),p=i.substring(s+1),l=a.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator,u=(p?p.split(l):[]).map(f=>this.stringToNative(a+o.ArgParamsSeparator+f)[1]);return[d.Vector+o.ArgParamsSeparator+a,u]}else if(e.startsWith(d.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(o.ArgCompositeSeparator),p=i.split(o.ArgCompositeSeparator).map((l,c)=>this.stringToNative(`${s[c]}${o.IdentifierParamSeparator}${l}`)[1]);return[e,p]}else if(e.startsWith(d.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:s[1]};return i&&i.split(o.ArgListSeparator).forEach(l=>{let c=l.match(new RegExp(`^\\(([^${o.ArgParamsSeparator}]+)${o.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(c){let[,u,f,g]=c;p[u]=this.stringToNative(`${f}${o.IdentifierParamSeparator}${g}`)[1]}}),[e,p]}else{if(e===d.String)return[e,i];if(e===d.Uint8||e===d.Uint16||e===d.Uint32)return[e,Number(i)];if(e===d.Uint64||e===d.Uint128||e===d.Uint256||e===d.Biguint)return[e,BigInt(i||0)];if(e===d.Bool)return[e,i==="true"];if(e===d.Address)return[e,i];if(e===d.Hex)return[e,i];if(e===d.Asset){let[s,a]=i.split(o.ArgCompositeSeparator),p={identifier:s,amount:BigInt(a)};return[e,p]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let p=s.stringToNative(i);return[e,p]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[p,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(o.ArgParamsSeparator)){let[r,e]=t.split(o.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[d.Uint32,t]:typeof t=="bigint"?[d.Uint64,t]:typeof t=="boolean"?[d.Bool,t]:[typeof t,t]}};var fr=n=>new y().nativeToString(d.String,n),gr=n=>new y().nativeToString(d.Uint8,n),hr=n=>new y().nativeToString(d.Uint16,n),mr=n=>new y().nativeToString(d.Uint32,n),Wr=n=>new y().nativeToString(d.Uint64,n),yr=n=>new y().nativeToString(d.Biguint,n),Ar=n=>new y().nativeToString(d.Bool,n),xr=n=>new y().nativeToString(d.Address,n),mt=n=>new y().nativeToString(d.Asset,n),vr=n=>new y().nativeToString(d.Hex,n),Cr=(n,t)=>{if(t===null)return d.Option+o.ArgParamsSeparator;let r=n(t),e=r.indexOf(o.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return d.Option+o.ArgParamsSeparator+i+o.ArgParamsSeparator+s},wr=(...n)=>new y().nativeToString(d.Tuple,n),Sr=n=>new y().nativeToString(d.Struct,n),Ir=n=>new y().nativeToString(d.Vector,n);var Ut=X(require("ajv"),1);var Wt=class{constructor(t){this.pendingBrand={protocol:O("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.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),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}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||T.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new Ut.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var Ht=X(require("ajv"),1);var D=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}=Y(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.results,"Result"),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.results||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.results&&!i&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||T.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new Ht.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 yt=class{constructor(t){this.config=t;this.pendingWarp={protocol:O("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.ensure(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 lt(t,r)}ensure(t,r){if(!t)throw new Error(r)}async validate(t){let e=await new D(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,Pr);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,br))}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)}}},Ft=new y,br=(n,t)=>typeof t=="bigint"?Ft.nativeToString("biguint",t):t,Pr=(n,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?Ft.stringToNative(t)[1]:t;var E=class E{get(t){let r=E.cache.get(t);return r?Date.now()>r.expiresAt?(E.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;E.cache.set(t,{value:r,expiresAt:i})}forget(t){E.cache.delete(t)}clear(){E.cache.clear()}};E.cache=new Map;var M=E;var At={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},xt={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}`},z=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new q:t==="memory"?new M:typeof window<"u"&&window.localStorage?new q:new M}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 N=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r,e={}){let i=this.applyVars(t,r,e);return await this.applyGlobals(t,i)}async applyGlobals(t,r){let e={...r};return e.actions=await Promise.all(e.actions.map(async i=>await this.applyActionGlobals(i))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r,e={}){if(!r?.vars)return r;let i=b(t,this.adapter.chainInfo.name),s=JSON.stringify(r),a=(p,l)=>{s=s.replace(new RegExp(`{{${p.toUpperCase()}}}`,"g"),l.toString())};return Object.entries(r.vars).forEach(([p,l])=>{if(typeof l!="string")a(p,l);else if(l.startsWith(o.Vars.Query+o.ArgParamsSeparator)){let c=l.slice(o.Vars.Query.length+1),[u,f]=c.split(o.ArgCompositeSeparator),g=t.currentUrl?new URLSearchParams(t.currentUrl.split("?")[1]).get(u):null,C=e.queries?.[u]||null||g;C&&a(p,C)}else if(l.startsWith(o.Vars.Env+o.ArgParamsSeparator)){let c=l.slice(o.Vars.Env.length+1),[u,f]=c.split(o.ArgCompositeSeparator),m={...t.vars,...e.envs}?.[u];m&&a(p,m)}else l===o.Source.UserWallet&&i?a(p,i):a(p,l)}),JSON.parse(s)}async applyRootGlobals(t,r){let e=JSON.stringify(t),i={config:r,chain:this.adapter.chainInfo};return Object.values(o.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,chain:this.adapter.chainInfo};return Object.values(o.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}};var U=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 y,this.cache=new z(t.cache?.type)}getSerializer(){return this.serializer}async createExecutable(t,r,e,i={}){if(!S(t,r))throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),p=h(a.name,this.adapters),l=await new N(this.config,p).apply(this.config,t,i),c=S(l,r),u=this.getStringTypedInputs(c,e),f=await this.getResolvedInputs(a.name,c,u),g=this.getModifiedInputs(f),m=g.find(v=>v.input.position==="receiver")?.value,C=this.getDestinationFromAction(c),W=m?this.serializer.stringToNative(m)[1]:C;if(!W)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let A=this.getPreparedArgs(c,g),w=g.find(v=>v.input.position==="value")?.value||null,H="value"in c?c.value:null,Q=BigInt(w?.split(o.ArgParamsSeparator)[1]||H||0),L=g.filter(v=>v.input.position==="transfer"&&v.value).map(v=>v.value),Lt=[...("transfers"in c?c.transfers:[])||[],...L||[]].map(v=>this.serializer.stringToNative(v)[1]),Ot=g.find(v=>v.input.position==="data")?.value,jt="data"in c?c.data||"":null,wt={warp:l,chain:a,action:r,destination:W,args:A,value:Q,transfers:Lt,data:Ot||jt||null,resolvedInputs:g};return this.cache.set(xt.WarpExecutable(this.config.env,l.meta?.hash||"",r),wt.resolvedInputs,At.OneWeek),wt}async getChainInfoForWarp(t,r){if(t.chain)return h(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(o.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e){let i=r.inputs||[],s=await Promise.all(e.map(p=>this.preprocessInput(t,p))),a=(p,l)=>{if(p.source==="query"){let c=this.url.searchParams.get(p.name);return c?this.serializer.nativeToString(p.type,c):null}else if(p.source===o.Source.UserWallet){let c=b(this.config,t);return c?this.serializer.nativeToString("address",c):null}else return p.source==="hidden"?p.default!==void 0?this.serializer.nativeToString(p.type,p.default):null:s[l]||null};return i.map((p,l)=>{let c=a(p,l);return{input:p,value:c||(p.default!==void 0?this.serializer.nativeToString(p.type,p.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,i]=r.input.modifier.split(":");if(isNaN(Number(i))){let s=Number(t.find(l=>l.input.name===i)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let p=j(a,+s);return{...r,value:`${r.input.type}:${p}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=j(s,+i);return{...r,value:`${r.input.type}:${a}`}}}else return r})}async preprocessInput(t,r){try{let[e,i]=et(r),s=h(t,this.adapters);if(e==="asset"){let[a,p,l]=i.split(o.ArgCompositeSeparator);if(l)return r;let c=await s.dataLoader.getAsset(a);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=j(p,c.decimals);return mt({...c,amount:u})}else return r}catch(e){throw x.warn("WarpFactory: Preprocess input failed",e),e}}getDestinationFromAction(t){return"address"in t&&t.address?t.address:"destination"in t&&t.destination?.url?t.destination.url:null}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:i,value:s})=>{if(!s||!i.position?.startsWith("arg:"))return;let a=Number(i.position.split(":")[1])-1;e.splice(a,0,s)}),e}async tryGetChainFromInputs(t,r){let e=t.actions.find(l=>l.inputs?.some(c=>c.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 h(a,this.adapters).chainInfo}};var k=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new U(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[];for(let p=1;p<=t.actions.length;p++){let l=S(t,p);if(!tt(l,t))continue;let{tx:c,chain:u,immediateExecution:f}=await this.executeAction(t,p,r,e);c&&i.push(c),u&&(s=u),f&&a.push(f)}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let p=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(p))}return{txs:i,chain:s,immediateExecutions:a}}async executeAction(t,r,e,i={}){let s=S(t,r);if(s.type==="link")return await this.callHandler(async()=>{let c=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(c):st.open(c,"_blank")}),{tx:null,chain:null,immediateExecution:null};let a=await this.factory.createExecutable(t,r,e,i);if(s.type==="collect"){let c=await this.executeCollect(a);return c.success?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c}):(this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null,immediateExecution:null})}let p=h(a.chain.name,this.adapters);if(s.type==="query"){let c=await p.executor.executeQuery(a);return c.success?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:c,tx:null})):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:a.chain,immediateExecution:c}}return{tx:await p.executor.createTransaction(a),chain:a.chain,immediateExecution:null}}async evaluateResults(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=h(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,p)=>{if(!tt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let l=r[p],c=p+1,u=await i.results.getActionExecution(t,c,l);return u.success?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:c,chain:e,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.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=b(this.config,t.chain.name),i=S(t.warp,t.action),s=u=>{if(!u.value)return null;let f=this.factory.getSerializer().stringToNative(u.value)[1];if(u.input.type==="biguint")return f.toString();if(u.input.type==="asset"){let{identifier:g,amount:m}=f;return{identifier:g,amount:m.toString()}}else return f},a=new Headers;if(a.set("Content-Type","application/json"),a.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:u,nonce:f,expiresAt:g}=await it(e,`${t.chain.name}-adapter`),m=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:u,chain:t.chain}));if(m){let C=at(e,m,f,g);Object.entries(C).forEach(([W,A])=>a.set(W,A))}}Object.entries(i.destination.headers||{}).forEach(([u,f])=>{a.set(u,f)});let p={};t.resolvedInputs.forEach(u=>{let f=u.input.as||u.input.name,g=s(u);if(u.input.position&&u.input.position.startsWith(o.Position.Payload)){let m=gt(u.input.position,f,g);p=nt(p,m)}else p[f]=g});let l=i.destination.method||"GET",c=l==="GET"?void 0:JSON.stringify({...p,...r});x.debug("Executing collect",{url:i.destination.url,method:l,headers:a,body:c});try{let u=await fetch(i.destination.url,{method:l,headers:a,body:c});x.debug("Collect response status",{status:u.status});let f=await u.json();x.debug("Collect response content",{content:f});let{values:g,results:m}=await ht(t.warp,f,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config.transform?.runner),C=ft(this.config,this.adapters,t.warp,t.action,m);return{success:u.ok,warp:t.warp,action:t.action,user:b(this.config,t.chain.name),txHash:null,tx:null,next:C,values:g,results:{...m,_DATA:f},messages:ut(t.warp,m)}}catch(u){return x.error("WarpActionExecutor: Error executing collect",u),{success:!1,warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[]},results:{_DATA:u},messages:{}}}}async callHandler(t){if(t)return await t()}};var G=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}`);return(await i.json()).hits}catch(i){throw x.error("WarpIndex: Error searching for warps: ",i),i}}};var J=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(o.HttpProtocolPrefix)?!!F(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),p=a.length>0,l=a.map(c=>({url:c.url,warp:c.warp}));return{match:p,results:l}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(o.HttpProtocolPrefix)?F(t):I(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,p=null,l=null,c=null,u=P(i.chainPrefix,this.adapters);if(s==="hash"){p=await u.builder().createFromTransactionHash(a,r);let g=await u.registry.getInfoByHash(a,r);l=g.registryInfo,c=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,r);l=g.registryInfo,c=g.brand,g.registryInfo&&(p=await u.builder().createFromTransactionHash(g.registryInfo.hash,r))}let f=p?await new N(this.config,u).apply(this.config,p):null;return f?{match:!0,url:t,warp:f,chain:u.chainInfo.name,registryInfo:l,brand:c}:e}catch(s){return x.error("Error detecting warp link",s),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 k(this.config,this.adapters,t)}async detectWarp(t,r){return new J(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"),p=s?t:null;if(!p&&a&&(p=await(await fetch(t)).json()),p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(e),{txs:c,chain:u,immediateExecutions:f}=await l.execute(p,r,{queries:i.queries});return{txs:c,chain:u,immediateExecutions:f,evaluateResults:async m=>{await l.evaluateResults(p,m)}}}createInscriptionTransaction(t,r){return h(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return h(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=I(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return P(e.chainPrefix,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!b(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return h(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 h(t,this.adapters).explorer}getResults(t){return h(t,this.adapters).results}async getRegistry(t){let r=h(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return h(t,this.adapters).dataLoader}getWallet(t){return h(t,this.adapters).wallet}get factory(){return new U(this.config,this.adapters)}get index(){return new G(this.config)}get linkBuilder(){return new $(this.config,this.adapters)}createBuilder(t){return h(t,this.adapters).builder()}createAbiBuilder(t){return h(t,this.adapters).abiBuilder()}createBrandBuilder(t){return h(t,this.adapters).brandBuilder()}createSerializer(t){return h(t,this.adapters).serializer}};var Ct=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,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyResultsToMessages,asset,biguint,bool,buildNestedPayload,bytesToBase64,bytesToHex,createAuthHeaders,createAuthMessage,createCryptoProvider,createHttpAuthHeaders,createSignableMessage,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,extractWarpSecrets,findWarpAdapterByPrefix,findWarpAdapterForChain,getCryptoProvider,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getProviderUrl,getRandomBytes,getRandomHex,getWarpActionByIndex,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,isWarpActionAutoExecute,mergeNestedPayload,option,parseResultsOutIndex,parseSignedMessage,replacePlaceholders,safeWindow,setCryptoProvider,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateSignedMessage,vector});
1
+ "use strict";var Dr=Object.create;var K=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var Mr=Object.getOwnPropertyNames;var kr=Object.getPrototypeOf,zr=Object.prototype.hasOwnProperty;var Gr=(n,r)=>{for(var t in r)K(n,t,{get:r[t],enumerable:!0})},Sr=(n,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Mr(r))!zr.call(n,i)&&i!==t&&K(n,i,{get:()=>r[i],enumerable:!(e=qr(r,i))||e.enumerable});return n};var X=(n,r,t)=>(t=n!=null?Dr(kr(n)):{},Sr(r||!n||!n.__esModule?K(t,"default",{value:n,enumerable:!0}):t,n)),Jr=n=>Sr(K({},"__esModule",{value:!0}),n);var Bt={};Gr(Bt,{BrowserCryptoProvider:()=>_,CacheTtl:()=>Ar,NodeCryptoProvider:()=>Z,WarpBrandBuilder:()=>Wr,WarpBuilder:()=>yr,WarpCache:()=>k,WarpCacheKey:()=>xr,WarpChainName:()=>Ir,WarpClient:()=>vr,WarpConfig:()=>T,WarpConstants:()=>o,WarpExecutor:()=>z,WarpFactory:()=>U,WarpIndex:()=>G,WarpInputTypes:()=>d,WarpInterpolator:()=>N,WarpLinkBuilder:()=>$,WarpLinkDetecter:()=>J,WarpLogger:()=>x,WarpProtocolVersions:()=>R,WarpSerializer:()=>y,WarpTypeRegistry:()=>Cr,WarpValidator:()=>D,address:()=>wt,applyResultsToMessages:()=>ur,asset:()=>mr,biguint:()=>vt,bool:()=>Ct,buildNestedPayload:()=>gr,bytesToBase64:()=>Kr,bytesToHex:()=>br,createAuthHeaders:()=>ar,createAuthMessage:()=>ir,createCryptoProvider:()=>_r,createHttpAuthHeaders:()=>ut,createSignableMessage:()=>Br,createWarpI18nText:()=>tt,evaluateResultsCommon:()=>Er,extractCollectResults:()=>hr,extractIdentifierInfoFromUrl:()=>L,extractWarpSecrets:()=>Zr,findWarpAdapterByPrefix:()=>P,findWarpAdapterForChain:()=>h,getCryptoProvider:()=>or,getLatestProtocolIdentifier:()=>O,getNextInfo:()=>fr,getProviderConfig:()=>pt,getProviderUrl:()=>ot,getRandomBytes:()=>pr,getRandomHex:()=>cr,getWarpActionByIndex:()=>S,getWarpInfoFromIdentifier:()=>I,getWarpPrimaryAction:()=>Y,getWarpWalletAddress:()=>$r,getWarpWalletAddressFromConfig:()=>b,getWarpWalletMnemonic:()=>Nr,getWarpWalletMnemonicFromConfig:()=>ht,getWarpWalletPrivateKey:()=>Vr,getWarpWalletPrivateKeyFromConfig:()=>gt,hasInputPrefix:()=>it,hex:()=>St,isWarpActionAutoExecute:()=>rr,isWarpI18nText:()=>rt,mergeNestedPayload:()=>nr,option:()=>It,parseResultsOutIndex:()=>Rr,parseSignedMessage:()=>ft,replacePlaceholders:()=>tr,resolveWarpText:()=>Yr,safeWindow:()=>sr,setCryptoProvider:()=>Qr,shiftBigintBy:()=>j,splitInput:()=>er,string:()=>mt,struct:()=>Pt,testCryptoAvailability:()=>Xr,toPreviewText:()=>lr,tuple:()=>bt,uint16:()=>yt,uint32:()=>At,uint64:()=>xt,uint8:()=>Wt,validateSignedMessage:()=>dt,vector:()=>Tt});module.exports=Jr(Bt);var Ir=(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))(Ir||{}),o={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},d={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"},sr=typeof window<"u"?window:{open:()=>{}};var R={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},T={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${R.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${R.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",o.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 _=class{async getRandomBytes(r){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let t=new Uint8Array(r);return window.crypto.getRandomValues(t),t}},Z=class{async getRandomBytes(r){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let t=await import("crypto");return new Uint8Array(t.randomBytes(r))}catch(t){throw new Error(`Node.js crypto not available: ${t instanceof Error?t.message:"Unknown error"}`)}}},B=null;function or(){if(B)return B;if(typeof window<"u"&&window.crypto)return B=new _,B;if(typeof process<"u"&&process.versions?.node)return B=new Z,B;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Qr(n){B=n}async function pr(n,r){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(r||or()).getRandomBytes(n)}function br(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let r=new Array(n.length*2);for(let t=0;t<n.length;t++){let e=n[t];r[t*2]=(e>>>4).toString(16),r[t*2+1]=(e&15).toString(16)}return r.join("")}function Kr(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 r=String.fromCharCode.apply(null,Array.from(n));return btoa(r)}else throw new Error("Base64 encoding not available in this environment")}async function cr(n,r){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let t=await pr(n/2,r);return br(t)}async function Xr(){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 pr(16),n.randomBytes=!0}catch{}return n}function _r(){return or()}var Zr=n=>Object.values(n.vars||{}).filter(r=>r.startsWith(`${o.Vars.Env}:`)).map(r=>{let t=r.replace(`${o.Vars.Env}:`,"").trim(),[e,i]=t.split(o.ArgCompositeSeparator);return{key:e,description:i||null}});var h=(n,r)=>{let t=r.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${n}`);return t},P=(n,r)=>{let t=r.find(e=>e.prefix.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for prefix: ${n}`);return t},O=n=>{if(n==="warp")return`warp:${R.Warp}`;if(n==="brand")return`brand:${R.Brand}`;if(n==="abi")return`abi:${R.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},S=(n,r)=>n?.actions[r-1],Y=n=>{let r=n.actions.find(a=>a.primary===!0);if(r)return{action:r,index:n.actions.indexOf(r)};let t=["transfer","contract","query","collect"],e=n.actions.filter(a=>!t.includes(a.type));if(e.length>0){let a=e[e.length-1];return{action:a,index:n.actions.indexOf(a)}}let s=[...n.actions].reverse().find(a=>t.includes(a.type));if(!s)throw new Error(`Warp has no primary action: ${n.meta?.hash}`);return{action:s,index:n.actions.indexOf(s)}},rr=(n,r)=>{if(n.auto===!1)return!1;if(n.type==="link"){let{action:t}=Y(r);return n===t||n.auto===!0}return!0},j=(n,r)=>{let t=n.toString(),[e,i=""]=t.split("."),s=Math.abs(r);if(r>0)return BigInt(e+i.padEnd(s,"0"));if(r<0){let a=e+i;if(s>=a.length)return 0n;let p=a.slice(0,-s)||"0";return BigInt(p)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},lr=(n,r=100)=>{if(!n)return"";let t=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return t=t.startsWith("- ")?t.slice(2):t,t=t.length>r?t.substring(0,t.lastIndexOf(" ",r))+"...":t,t},tr=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(t,e)=>r[e]||""),ur=(n,r)=>{let t=Object.entries(n.messages||{}).map(([e,i])=>[e,tr(i,r)]);return Object.fromEntries(t)};var Yr=(n,r,t)=>{let e=r||t?.preferences?.language||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(e in n)return n[e];if("en"in n)return n.en;let i=Object.keys(n);if(i.length>0)return n[i[0]]}return""},rt=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,tt=n=>n;var et=(n,r)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,nt=n=>{let r=o.IdentifierParamSeparator,t=n.indexOf(r);return t!==-1?{separator:r,index:t}:null},Pr=n=>{let r=nt(n);if(!r)return[n];let{separator:t,index:e}=r,i=n.substring(0,e),s=n.substring(e+t.length),a=Pr(s);return[i,...a]},I=n=>{let r=decodeURIComponent(n).trim(),t=r.split("?")[0],e=Pr(t);if(t.length===64&&/^[a-fA-F0-9]+$/.test(t))return{chainPrefix:o.IdentifierChainDefault,type:o.IdentifierType.Hash,identifier:r,identifierBase:t};if(e.length===2&&/^[a-zA-Z0-9]{62}$/.test(e[0])&&/^[a-zA-Z0-9]{2}$/.test(e[1]))return null;if(e.length===3){let[i,s,a]=e;if(s===o.IdentifierType.Alias||s===o.IdentifierType.Hash){let p=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chainPrefix:i,type:s,identifier:p,identifierBase:a}}}if(e.length===2){let[i,s]=e;if(i===o.IdentifierType.Alias||i===o.IdentifierType.Hash){let a=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:o.IdentifierChainDefault,type:i,identifier:a,identifierBase:s}}}if(e.length===2){let[i,s]=e;if(i!==o.IdentifierType.Alias&&i!==o.IdentifierType.Hash){let a=r.includes("?")?s+r.substring(r.indexOf("?")):s,p=et(s,i)?o.IdentifierType.Hash:o.IdentifierType.Alias;return{chainPrefix:i,type:p,identifier:a,identifierBase:s}}}return{chainPrefix:o.IdentifierChainDefault,type:o.IdentifierType.Alias,identifier:r,identifierBase:t}},L=n=>{let r=new URL(n),e=r.searchParams.get(o.IdentifierParamName);if(e||(e=r.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return I(i)};var er=n=>{let[r,...t]=n.split(/:(.*)/,2);return[r,t[0]||""]},it=n=>{let r=new Set(Object.values(d));if(!n.includes(o.ArgParamsSeparator))return!1;let t=er(n)[0];return r.has(t)};var Tr=X(require("qr-code-styling"),1);var $=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(o.HttpProtocolPrefix)?!!L(r):!1}build(r,t,e){let i=this.config.clientUrl||T.DefaultClientUrl(this.config.env),s=h(r,this.adapters),a=t===o.IdentifierType.Alias?e:t+o.IdentifierParamSeparator+e,p=s.prefix+o.IdentifierParamSeparator+a,l=encodeURIComponent(p);return T.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${o.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(r){let t=I(r);if(!t)return null;let e=P(t.chainPrefix,this.adapters);return e?this.build(e.chainInfo.name,t.type,t.identifierBase):null}generateQrCode(r,t,e,i=512,s="white",a="black",p="#23F7DD"){let l=h(r,this.adapters),c=this.build(l.chainInfo.name,t,e);return new Tr.default({type:"svg",width:i,height:i,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var at="https://",fr=(n,r,t,e,i)=>{let s=t.actions?.[e]?.next||t.next||null;if(!s)return null;if(s.startsWith(at))return[{identifier:null,url:s}];let[a,p]=s.split("?");if(!p)return[{identifier:a,url:dr(r,a,n)}];let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let W=tr(p,{...t.vars,...i}),A=W?`${a}?${W}`:a;return[{identifier:A,url:dr(r,A,n)}]}let c=l[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let g=Array.isArray(i[f])?i[f]:[i[f]];if(g.length===0)return[];let m=l.filter(W=>W.includes(`{{${f}[]`)).map(W=>{let A=W.match(/\[\](\.[^}]+)?}}/),w=A&&A[1]||"";return{placeholder:W,field:w?w.slice(1):"",regex:new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return g.map(W=>{let A=p;for(let{regex:H,field:Q}of m){let F=Q?st(W,Q):W;if(F==null)return null;A=A.replace(H,F)}if(A.includes("{{")||A.includes("}}"))return null;let w=A?`${a}?${A}`:a;return{identifier:w,url:dr(r,w,n)}}).filter(W=>W!==null)},dr=(n,r,t)=>{let[e,i]=r.split("?"),s=I(e)||{chainPrefix:o.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=P(s.chainPrefix,n);if(!a)throw new Error(`Adapter not found for chain ${s.chainPrefix}`);let p=new $(t,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((c,u)=>l.searchParams.set(u,c)),l.toString().replace(/\/\?/,"?")},st=(n,r)=>r.split(".").reduce((t,e)=>t?.[e],n);function gr(n,r,t){return n.startsWith(o.Position.Payload)?n.slice(o.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[r]:t}:e}),{}):{[r]:t}}function nr(n,r){if(!n)return{...r};if(!r)return{...n};let t={...n};return Object.keys(r).forEach(e=>{t[e]&&typeof t[e]=="object"&&typeof r[e]=="object"?t[e]=nr(t[e],r[e]):t[e]=r[e]}),t}var ot=(n,r,t,e)=>{let i=n.providers?.[r];return i?.[t]?i[t]:e},pt=(n,r)=>n.providers?.[r];var V=class V{static debug(...r){V.isTestEnv||console.debug(...r)}static info(...r){V.isTestEnv||console.info(...r)}static warn(...r){V.isTestEnv||console.warn(...r)}static error(...r){V.isTestEnv||console.error(...r)}};V.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=V;var hr=async(n,r,t,e,i,s)=>{let a=[],p=[],l={};for(let[c,u]of Object.entries(n.results||{})){if(u.startsWith(o.Transform.Prefix))continue;let f=Rr(u);if(f!==null&&f!==t){l[c]=null;continue}let[g,...m]=u.split("."),C=(W,A)=>A.reduce((w,H)=>w&&w[H]!==void 0?w[H]:null,W);if(g==="out"||g.startsWith("out[")){let W=m.length===0?r?.data||r:C(r,m);a.push(String(W)),p.push(W),l[c]=W}else l[c]=u}return{values:{string:a,native:p},results:await Er(n,l,t,e,i,s)}},Er=async(n,r,t,e,i,s)=>{if(!n.results)return r;let a={...r};return a=ct(a,n,t,e,i),a=await lt(n,a,s),a},ct=(n,r,t,e,i)=>{let s={...n},a=S(r,t)?.inputs||[];for(let[p,l]of Object.entries(s))if(typeof l=="string"&&l.startsWith("input.")){let c=l.split(".")[1],u=a.findIndex(g=>g.as===c||g.name===c),f=u!==-1?e[u]?.value:null;s[p]=f?i.stringToNative(f)[1]:null}return s},lt=async(n,r,t)=>{if(!n.results)return r;let e={...r},i=Object.entries(n.results).filter(([,s])=>s.startsWith(o.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(o.Transform.Prefix.length)}));if(i.length>0&&(!t||typeof t.run!="function"))throw new Error("Transform results are 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 t.run(a,e)}catch(p){x.error(`Transform error for result '${s}':`,p),e[s]=null}return e},Rr=n=>{if(n==="out")return 1;let r=n.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};async function Br(n,r,t,e=5){let i=await cr(64,t),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:s,purpose:r}),nonce:i,expiresAt:s}}async function ir(n,r,t,e){let i=e||`prove-wallet-ownership for app "${r}"`;return Br(n,i,t,5)}function ar(n,r,t,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":r,"X-Signer-Nonce":t,"X-Signer-ExpiresAt":e}}async function ut(n,r,t,e){let{message:i,nonce:s,expiresAt:a}=await ir(n,t,e),p=await r(i);return ar(n,p,s,a)}function dt(n){let r=new Date(n).getTime();return Date.now()<r}function ft(n){try{let r=JSON.parse(n);if(!r.wallet||!r.nonce||!r.expiresAt||!r.purpose)throw new Error("Invalid signed message: missing required fields");return r}catch(r){throw new Error(`Failed to parse signed message: ${r instanceof Error?r.message:"Unknown error"}`)}}var $r=n=>n?typeof n=="string"?n:n.address:null,b=(n,r)=>$r(n.user?.wallets?.[r]||null),Vr=n=>n?typeof n=="string"?n:n.privateKey:null,Nr=n=>n?typeof n=="string"?n:n.mnemonic:null,gt=(n,r)=>Vr(n.user?.wallets?.[r]||null)?.trim()||null,ht=(n,r)=>Nr(n.user?.wallets?.[r]||null)?.trim()||null;var y=class{constructor(r){this.typeRegistry=r?.typeRegistry}nativeToString(r,t){if(r===d.Tuple&&Array.isArray(t)){if(t.length===0)return r+o.ArgParamsSeparator;if(t.every(e=>typeof e=="string"&&e.includes(o.ArgParamsSeparator))){let e=t.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${r}(${i.join(o.ArgCompositeSeparator)})${o.ArgParamsSeparator}${s.join(o.ArgListSeparator)}`}return r+o.ArgParamsSeparator+t.join(o.ArgListSeparator)}if(r===d.Struct&&typeof t=="object"&&t!==null&&!Array.isArray(t)){let e=t;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(p=>p!=="_name");if(s.length===0)return`${r}(${i})${o.ArgParamsSeparator}`;let a=s.map(p=>{let[l,c]=this.getTypeAndValue(e[p]);return`(${p}${o.ArgParamsSeparator}${l})${c}`});return`${r}(${i})${o.ArgParamsSeparator}${a.join(o.ArgListSeparator)}`}if(r===d.Vector&&Array.isArray(t)){if(t.length===0)return`${r}${o.ArgParamsSeparator}`;if(t.every(e=>typeof e=="string"&&e.includes(o.ArgParamsSeparator))){let e=t[0],i=e.indexOf(o.ArgParamsSeparator),s=e.substring(0,i),a=t.map(l=>{let c=l.indexOf(o.ArgParamsSeparator),u=l.substring(c+1);return s.startsWith(d.Tuple)?u.replace(o.ArgListSeparator,o.ArgCompositeSeparator):u}),p=s.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator;return r+o.ArgParamsSeparator+s+o.ArgParamsSeparator+a.join(p)}return r+o.ArgParamsSeparator+t.join(o.ArgListSeparator)}if(r===d.Asset&&typeof t=="object"&&t&&"identifier"in t&&"amount"in t)return"decimals"in t?d.Asset+o.ArgParamsSeparator+t.identifier+o.ArgCompositeSeparator+String(t.amount)+o.ArgCompositeSeparator+String(t.decimals):d.Asset+o.ArgParamsSeparator+t.identifier+o.ArgCompositeSeparator+String(t.amount);if(this.typeRegistry){let e=this.typeRegistry.getHandler(r);if(e)return e.nativeToString(t);let i=this.typeRegistry.resolveType(r);if(i!==r)return this.nativeToString(i,t)}return r+o.ArgParamsSeparator+(t?.toString()??"")}stringToNative(r){let t=r.split(o.ArgParamsSeparator),e=t[0],i=t.slice(1).join(o.ArgParamsSeparator);if(e==="null")return[e,null];if(e===d.Option){let[s,a]=i.split(o.ArgParamsSeparator);return[d.Option+o.ArgParamsSeparator+s,a||null]}if(e===d.Vector){let s=i.indexOf(o.ArgParamsSeparator),a=i.substring(0,s),p=i.substring(s+1),l=a.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator,u=(p?p.split(l):[]).map(f=>this.stringToNative(a+o.ArgParamsSeparator+f)[1]);return[d.Vector+o.ArgParamsSeparator+a,u]}else if(e.startsWith(d.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(o.ArgCompositeSeparator),p=i.split(o.ArgCompositeSeparator).map((l,c)=>this.stringToNative(`${s[c]}${o.IdentifierParamSeparator}${l}`)[1]);return[e,p]}else if(e.startsWith(d.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:s[1]};return i&&i.split(o.ArgListSeparator).forEach(l=>{let c=l.match(new RegExp(`^\\(([^${o.ArgParamsSeparator}]+)${o.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(c){let[,u,f,g]=c;p[u]=this.stringToNative(`${f}${o.IdentifierParamSeparator}${g}`)[1]}}),[e,p]}else{if(e===d.String)return[e,i];if(e===d.Uint8||e===d.Uint16||e===d.Uint32)return[e,Number(i)];if(e===d.Uint64||e===d.Uint128||e===d.Uint256||e===d.Biguint)return[e,BigInt(i||0)];if(e===d.Bool)return[e,i==="true"];if(e===d.Address)return[e,i];if(e===d.Hex)return[e,i];if(e===d.Asset){let[s,a]=i.split(o.ArgCompositeSeparator),p={identifier:s,amount:BigInt(a)};return[e,p]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let p=s.stringToNative(i);return[e,p]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[p,l]=this.stringToNative(`${a}:${i}`);return[e,l]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(r){if(typeof r=="string"&&r.includes(o.ArgParamsSeparator)){let[t,e]=r.split(o.ArgParamsSeparator);return[t,e]}return typeof r=="number"?[d.Uint32,r]:typeof r=="bigint"?[d.Uint64,r]:typeof r=="boolean"?[d.Bool,r]:[typeof r,r]}};var mt=n=>new y().nativeToString(d.String,n),Wt=n=>new y().nativeToString(d.Uint8,n),yt=n=>new y().nativeToString(d.Uint16,n),At=n=>new y().nativeToString(d.Uint32,n),xt=n=>new y().nativeToString(d.Uint64,n),vt=n=>new y().nativeToString(d.Biguint,n),Ct=n=>new y().nativeToString(d.Bool,n),wt=n=>new y().nativeToString(d.Address,n),mr=n=>new y().nativeToString(d.Asset,n),St=n=>new y().nativeToString(d.Hex,n),It=(n,r)=>{if(r===null)return d.Option+o.ArgParamsSeparator;let t=n(r),e=t.indexOf(o.ArgParamsSeparator),i=t.substring(0,e),s=t.substring(e+1);return d.Option+o.ArgParamsSeparator+i+o.ArgParamsSeparator+s},bt=(...n)=>new y().nativeToString(d.Tuple,n),Pt=n=>new y().nativeToString(d.Struct,n),Tt=n=>new y().nativeToString(d.Vector,n);var Ur=X(require("ajv"),1);var Wr=class{constructor(r){this.pendingBrand={protocol:O("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.schema?.brand||T.LatestBrandSchemaUrl,i=await(await fetch(t)).json(),s=new Ur.default,a=s.compile(i);if(!a(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var Hr=X(require("ajv"),1);var D=class{constructor(r){this.config=r;this.config=r}async validate(r){let t=[];return t.push(...this.validatePrimaryAction(r)),t.push(...this.validateMaxOneValuePosition(r)),t.push(...this.validateVariableNamesAndResultNamesUppercase(r)),t.push(...this.validateAbiIsSetIfApplicable(r)),t.push(...await this.validateSchema(r)),{valid:t.length===0,errors:t}}validatePrimaryAction(r){try{let{action:t}=Y(r);return t?[]:["Primary action is required"]}catch(t){return[t instanceof Error?t.message:"Primary action is required"]}}validateMaxOneValuePosition(r){return r.actions.filter(e=>e.inputs?e.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],e=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&t.push(`${s} name '${a}' must be uppercase`)})};return e(r.vars,"Variable"),e(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(a=>a.type==="contract"),e=r.actions.some(a=>a.type==="query");if(!t&&!e)return[];let i=r.actions.some(a=>a.abi),s=Object.values(r.results||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return r.results&&!i&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||T.LatestWarpSchemaUrl,i=await(await fetch(t)).json(),s=new Hr.default({strict:!1}),a=s.compile(i);return a(r)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var yr=class{constructor(r){this.config=r;this.pendingWarp={protocol:O("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.validate(e),e}async createFromUrl(r){return await(await fetch(r)).json()}setChain(r){return this.pendingWarp.chain=r,this}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),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(r,t=100){return lr(r,t)}ensure(r,t){if(!r)throw new Error(t)}ensureWarpText(r,t){if(!r)throw new Error(t);if(typeof r=="object"&&!r.en)throw new Error(t)}async validate(r){let e=await new D(this.config).validate(r);if(!e.valid)throw new Error(e.errors.join(`
2
+ `))}};var q=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let t=localStorage.getItem(this.getKey(r));if(!t)return null;let e=JSON.parse(t,Rt);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(r)),null):e.value}catch{return null}}set(r,t,e){let i={value:t,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(i,Et))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let t=localStorage.key(r);t?.startsWith(this.prefix)&&localStorage.removeItem(t)}}},Lr=new y,Et=(n,r)=>typeof r=="bigint"?Lr.nativeToString("biguint",r):r,Rt=(n,r)=>typeof r=="string"&&r.startsWith(d.Biguint+":")?Lr.stringToNative(r)[1]:r;var E=class E{get(r){let t=E.cache.get(r);return t?Date.now()>t.expiresAt?(E.cache.delete(r),null):t.value:null}set(r,t,e){let i=Date.now()+e*1e3;E.cache.set(r,{value:t,expiresAt:i})}forget(r){E.cache.delete(r)}clear(){E.cache.clear()}};E.cache=new Map;var M=E;var Ar={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},xr={Warp:(n,r)=>`warp:${n}:${r}`,WarpAbi:(n,r)=>`warp-abi:${n}:${r}`,WarpExecutable:(n,r,t)=>`warp-exec:${n}:${r}:${t}`,RegistryInfo:(n,r)=>`registry-info:${n}:${r}`,Brand:(n,r)=>`brand:${n}:${r}`,Asset:(n,r,t)=>`asset:${n}:${r}:${t}`},k=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new q:r==="memory"?new M:typeof window<"u"&&window.localStorage?new q:new M}set(r,t,e){this.strategy.set(r,t,e)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var N=class{constructor(r,t){this.config=r;this.adapter=t}async apply(r,t,e={}){let i=this.applyVars(r,t,e);return await this.applyGlobals(r,i)}async applyGlobals(r,t){let e={...t};return e.actions=await Promise.all(e.actions.map(async i=>await this.applyActionGlobals(i))),e=await this.applyRootGlobals(e,r),e}applyVars(r,t,e={}){if(!t?.vars)return t;let i=b(r,this.adapter.chainInfo.name),s=JSON.stringify(t),a=(p,l)=>{s=s.replace(new RegExp(`{{${p.toUpperCase()}}}`,"g"),l.toString())};return Object.entries(t.vars).forEach(([p,l])=>{if(typeof l!="string")a(p,l);else if(l.startsWith(o.Vars.Query+o.ArgParamsSeparator)){let c=l.slice(o.Vars.Query.length+1),[u,f]=c.split(o.ArgCompositeSeparator),g=r.currentUrl?new URLSearchParams(r.currentUrl.split("?")[1]).get(u):null,C=e.queries?.[u]||null||g;C&&a(p,C)}else if(l.startsWith(o.Vars.Env+o.ArgParamsSeparator)){let c=l.slice(o.Vars.Env.length+1),[u,f]=c.split(o.ArgCompositeSeparator),m={...r.vars,...e.envs}?.[u];m&&a(p,m)}else l===o.Source.UserWallet&&i?a(p,i):a(p,l)}),JSON.parse(s)}async applyRootGlobals(r,t){let e=JSON.stringify(r),i={config:t,chain:this.adapter.chainInfo};return Object.values(o.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(e)}async applyActionGlobals(r){let t=JSON.stringify(r),e={config:this.config,chain:this.adapter.chainInfo};return Object.values(o.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(t=t.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(t)}};var U=class{constructor(r,t){this.config=r;this.adapters=t;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new y,this.cache=new k(r.cache?.type)}getSerializer(){return this.serializer}async createExecutable(r,t,e,i={}){if(!S(r,t))throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(r,e),p=h(a.name,this.adapters),l=await new N(this.config,p).apply(this.config,r,i),c=S(l,t),u=this.getStringTypedInputs(c,e),f=await this.getResolvedInputs(a.name,c,u),g=this.getModifiedInputs(f),m=g.find(v=>v.input.position==="receiver")?.value,C=this.getDestinationFromAction(c),W=m?this.serializer.stringToNative(m)[1]:C;if(!W)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let A=this.getPreparedArgs(c,g),w=g.find(v=>v.input.position==="value")?.value||null,H="value"in c?c.value:null,Q=BigInt(w?.split(o.ArgParamsSeparator)[1]||H||0),F=g.filter(v=>v.input.position==="transfer"&&v.value).map(v=>v.value),Fr=[...("transfers"in c?c.transfers:[])||[],...F||[]].map(v=>this.serializer.stringToNative(v)[1]),Or=g.find(v=>v.input.position==="data")?.value,jr="data"in c?c.data||"":null,wr={warp:l,chain:a,action:t,destination:W,args:A,value:Q,transfers:Fr,data:Or||jr||null,resolvedInputs:g};return this.cache.set(xr.WarpExecutable(this.config.env,l.meta?.hash||"",t),wr.resolvedInputs,Ar.OneWeek),wr}async getChainInfoForWarp(r,t){if(r.chain)return h(r.chain,this.adapters).chainInfo;if(t){let i=await this.tryGetChainFromInputs(r,t);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(r,t){let e=r.inputs||[];return t.map((i,s)=>{let a=e[s];return!a||i.includes(o.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(r,t,e){let i=t.inputs||[],s=await Promise.all(e.map(p=>this.preprocessInput(r,p))),a=(p,l)=>{if(p.source==="query"){let c=this.url.searchParams.get(p.name);return c?this.serializer.nativeToString(p.type,c):null}else if(p.source===o.Source.UserWallet){let c=b(this.config,r);return c?this.serializer.nativeToString("address",c):null}else return p.source==="hidden"?p.default!==void 0?this.serializer.nativeToString(p.type,p.default):null:s[l]||null};return i.map((p,l)=>{let c=a(p,l);return{input:p,value:c||(p.default!==void 0?this.serializer.nativeToString(p.type,p.default):null)}})}getModifiedInputs(r){return r.map((t,e)=>{if(t.input.modifier?.startsWith("scale:")){let[,i]=t.input.modifier.split(":");if(isNaN(Number(i))){let s=Number(r.find(l=>l.input.name===i)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=t.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let p=j(a,+s);return{...t,value:`${t.input.type}:${p}`}}else{let s=t.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=j(s,+i);return{...t,value:`${t.input.type}:${a}`}}}else return t})}async preprocessInput(r,t){try{let[e,i]=er(t),s=h(r,this.adapters);if(e==="asset"){let[a,p,l]=i.split(o.ArgCompositeSeparator);if(l)return t;let c=await s.dataLoader.getAsset(a);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=j(p,c.decimals);return mr({...c,amount:u})}else return t}catch(e){throw x.warn("WarpFactory: Preprocess input failed",e),e}}getDestinationFromAction(r){return"address"in r&&r.address?r.address:"destination"in r&&r.destination?.url?r.destination.url:null}getPreparedArgs(r,t){let e="args"in r?r.args||[]:[];return t.forEach(({input:i,value:s})=>{if(!s||!i.position?.startsWith("arg:"))return;let a=Number(i.position.split(":")[1])-1;e.splice(a,0,s)}),e}async tryGetChainFromInputs(r,t){let e=r.actions.find(l=>l.inputs?.some(c=>c.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=t[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return h(a,this.adapters).chainInfo}};var z=class{constructor(r,t,e){this.config=r;this.adapters=t;this.handlers=e;this.handlers=e,this.factory=new U(r,t)}async execute(r,t,e={}){let i=[],s=null,a=[];for(let p=1;p<=r.actions.length;p++){let l=S(r,p);if(!rr(l,r))continue;let{tx:c,chain:u,immediateExecution:f}=await this.executeAction(r,p,t,e);c&&i.push(c),u&&(s=u),f&&a.push(f)}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let p=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(p))}return{txs:i,chain:s,immediateExecutions:a}}async executeAction(r,t,e,i={}){let s=S(r,t);if(s.type==="link")return await this.callHandler(async()=>{let c=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(c):sr.open(c,"_blank")}),{tx:null,chain:null,immediateExecution:null};let a=await this.factory.createExecutable(r,t,e,i);if(s.type==="collect"){let c=await this.executeCollect(a);return c.success?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:t,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c}):(this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null,immediateExecution:null})}let p=h(a.chain.name,this.adapters);if(s.type==="query"){let c=await p.executor.executeQuery(a);return c.success?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:t,chain:a.chain,execution:c,tx:null})):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:a.chain,immediateExecution:c}}return{tx:await p.executor.createTransaction(a),chain:a.chain,immediateExecution:null}}async evaluateResults(r,t){if(t.length===0||r.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(r),i=h(e.name,this.adapters),s=(await Promise.all(r.actions.map(async(a,p)=>{if(!rr(a,r)||a.type!=="transfer"&&a.type!=="contract")return null;let l=t[p],c=p+1,u=await i.results.getActionExecution(r,c,l);return u.success?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:c,chain:e,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.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(r,t){let e=b(this.config,r.chain.name),i=S(r.warp,r.action),s=u=>{if(!u.value)return null;let f=this.factory.getSerializer().stringToNative(u.value)[1];if(u.input.type==="biguint")return f.toString();if(u.input.type==="asset"){let{identifier:g,amount:m}=f;return{identifier:g,amount:m.toString()}}else return f},a=new Headers;if(a.set("Content-Type","application/json"),a.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${r.chain.name}`);let{message:u,nonce:f,expiresAt:g}=await ir(e,`${r.chain.name}-adapter`),m=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:u,chain:r.chain}));if(m){let C=ar(e,m,f,g);Object.entries(C).forEach(([W,A])=>a.set(W,A))}}Object.entries(i.destination.headers||{}).forEach(([u,f])=>{a.set(u,f)});let p={};r.resolvedInputs.forEach(u=>{let f=u.input.as||u.input.name,g=s(u);if(u.input.position&&u.input.position.startsWith(o.Position.Payload)){let m=gr(u.input.position,f,g);p=nr(p,m)}else p[f]=g});let l=i.destination.method||"GET",c=l==="GET"?void 0:JSON.stringify({...p,...t});x.debug("Executing collect",{url:i.destination.url,method:l,headers:a,body:c});try{let u=await fetch(i.destination.url,{method:l,headers:a,body:c});x.debug("Collect response status",{status:u.status});let f=await u.json();x.debug("Collect response content",{content:f});let{values:g,results:m}=await hr(r.warp,f,r.action,r.resolvedInputs,this.factory.getSerializer(),this.config.transform?.runner),C=fr(this.config,this.adapters,r.warp,r.action,m);return{success:u.ok,warp:r.warp,action:r.action,user:b(this.config,r.chain.name),txHash:null,tx:null,next:C,values:g,results:{...m,_DATA:f},messages:ur(r.warp,m)}}catch(u){return x.error("WarpActionExecutor: Error executing collect",u),{success:!1,warp:r.warp,action:r.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[]},results:{_DATA:u},messages:{}}}}async callHandler(r){if(r)return await r()}};var G=class{constructor(r){this.config=r}async search(r,t,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"]:r,...t})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}`);return(await i.json()).hits}catch(i){throw x.error("WarpIndex: Error searching for warps: ",i),i}}};var J=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(o.HttpProtocolPrefix)?!!L(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let i=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),p=a.length>0,l=a.map(c=>({url:c.url,warp:c.warp}));return{match:p,results:l}}async detect(r,t){let e={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},i=r.startsWith(o.HttpProtocolPrefix)?L(r):I(r);if(!i)return e;try{let{type:s,identifierBase:a}=i,p=null,l=null,c=null,u=P(i.chainPrefix,this.adapters);if(s==="hash"){p=await u.builder().createFromTransactionHash(a,t);let g=await u.registry.getInfoByHash(a,t);l=g.registryInfo,c=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,t);l=g.registryInfo,c=g.brand,g.registryInfo&&(p=await u.builder().createFromTransactionHash(g.registryInfo.hash,t))}let f=p?await new N(this.config,u).apply(this.config,p):null;return f?{match:!0,url:r,warp:f,chain:u.chainInfo.name,registryInfo:l,brand:c}:e}catch(s){return x.error("Error detecting warp link",s),e}}};var vr=class{constructor(r,t){this.config=r;this.adapters=t}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new z(this.config,this.adapters,r)}async detectWarp(r,t){return new J(this.config,this.adapters).detect(r,t)}async executeWarp(r,t,e,i={}){let s=typeof r=="object",a=!s&&r.startsWith("http")&&r.endsWith(".json"),p=s?r:null;if(!p&&a&&(p=await(await fetch(r)).json()),p||(p=(await this.detectWarp(r,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(e),{txs:c,chain:u,immediateExecutions:f}=await l.execute(p,t,{queries:i.queries});return{txs:c,chain:u,immediateExecutions:f,evaluateResults:async m=>{await l.evaluateResults(p,m)}}}createInscriptionTransaction(r,t){return h(r,this.adapters).builder().createInscriptionTransaction(t)}async createFromTransaction(r,t,e=!1){return h(r,this.adapters).builder().createFromTransaction(t,e)}async createFromTransactionHash(r,t){let e=I(r);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return P(e.chainPrefix,this.adapters).builder().createFromTransactionHash(r,t)}async signMessage(r,t){if(!b(this.config,r))throw new Error(`No wallet configured for chain ${r}`);return h(r,this.adapters).wallet.signMessage(t)}async getActions(r,t,e=!1){let i=this.getDataLoader(r);return(await Promise.all(t.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(r){return h(r,this.adapters).explorer}getResults(r){return h(r,this.adapters).results}async getRegistry(r){let t=h(r,this.adapters).registry;return await t.init(),t}getDataLoader(r){return h(r,this.adapters).dataLoader}getWallet(r){return h(r,this.adapters).wallet}get factory(){return new U(this.config,this.adapters)}get index(){return new G(this.config)}get linkBuilder(){return new $(this.config,this.adapters)}createBuilder(r){return h(r,this.adapters).builder()}createAbiBuilder(r){return h(r,this.adapters).abiBuilder()}createBrandBuilder(r){return h(r,this.adapters).brandBuilder()}createSerializer(r){return h(r,this.adapters).serializer}};var Cr=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(r,t){this.typeHandlers.set(r,t)}registerTypeAlias(r,t){this.typeAliases.set(r,t)}hasType(r){return this.typeHandlers.has(r)||this.typeAliases.has(r)}getHandler(r){let t=this.typeAliases.get(r);return t?this.getHandler(t):this.typeHandlers.get(r)}getAlias(r){return this.typeAliases.get(r)}resolveType(r){let t=this.typeAliases.get(r);return t?this.resolveType(t):r}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,NodeCryptoProvider,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyResultsToMessages,asset,biguint,bool,buildNestedPayload,bytesToBase64,bytesToHex,createAuthHeaders,createAuthMessage,createCryptoProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,extractWarpSecrets,findWarpAdapterByPrefix,findWarpAdapterForChain,getCryptoProvider,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getProviderUrl,getRandomBytes,getRandomHex,getWarpActionByIndex,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,isWarpActionAutoExecute,isWarpI18nText,mergeNestedPayload,option,parseResultsOutIndex,parseSignedMessage,replacePlaceholders,resolveWarpText,safeWindow,setCryptoProvider,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateSignedMessage,vector});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var Pt=(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))(Pt||{}),o={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},d={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},st=typeof window<"u"?window:{open:()=>{}};var V={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},E={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${V.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${V.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",o.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 K=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}},X=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"}`)}}},R=null;function ot(){if(R)return R;if(typeof window<"u"&&window.crypto)return R=new K,R;if(typeof process<"u"&&process.versions?.node)return R=new X,R;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Zt(n){R=n}async function pt(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||ot()).getRandomBytes(n)}function Tt(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 Yt(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 ct(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await pt(n/2,t);return Tt(r)}async function tr(){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 pt(16),n.randomBytes=!0}catch{}return n}function rr(){return ot()}var ir=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${o.Vars.Env}:`)).map(t=>{let r=t.replace(`${o.Vars.Env}:`,"").trim(),[e,i]=r.split(o.ArgCompositeSeparator);return{key:e,description:i||null}});var W=(n,t)=>{let r=t.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},P=(n,t)=>{let r=t.find(e=>e.prefix.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for prefix: ${n}`);return r},q=n=>{if(n==="warp")return`warp:${V.Warp}`;if(n==="brand")return`brand:${V.Brand}`;if(n==="abi")return`abi:${V.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},S=(n,t)=>n?.actions[t-1],_=n=>{let t=n.actions.find(a=>a.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let r=["transfer","contract","query","collect"],e=n.actions.filter(a=>!r.includes(a.type));if(e.length>0){let a=e[e.length-1];return{action:a,index:n.actions.indexOf(a)}}let s=[...n.actions].reverse().find(a=>r.includes(a.type));if(!s)throw new Error(`Warp has no primary action: ${n.meta?.hash}`);return{action:s,index:n.actions.indexOf(s)}},Z=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){let{action:r}=_(t);return n===r||n.auto===!0}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 p=a.slice(0,-s)||"0";return BigInt(p)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},lt=(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},Y=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),ut=(n,t)=>{let r=Object.entries(n.messages||{}).map(([e,i])=>[e,Y(i,t)]);return Object.fromEntries(r)};var Et=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Rt=n=>{let t=o.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},dt=n=>{let t=Rt(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=dt(s);return[i,...a]},I=n=>{let t=decodeURIComponent(n).trim(),r=t.split("?")[0],e=dt(r);if(r.length===64&&/^[a-fA-F0-9]+$/.test(r))return{chainPrefix:o.IdentifierChainDefault,type:o.IdentifierType.Hash,identifier:t,identifierBase:r};if(e.length===2&&/^[a-zA-Z0-9]{62}$/.test(e[0])&&/^[a-zA-Z0-9]{2}$/.test(e[1]))return null;if(e.length===3){let[i,s,a]=e;if(s===o.IdentifierType.Alias||s===o.IdentifierType.Hash){let p=t.includes("?")?a+t.substring(t.indexOf("?")):a;return{chainPrefix:i,type:s,identifier:p,identifierBase:a}}}if(e.length===2){let[i,s]=e;if(i===o.IdentifierType.Alias||i===o.IdentifierType.Hash){let a=t.includes("?")?s+t.substring(t.indexOf("?")):s;return{chainPrefix:o.IdentifierChainDefault,type:i,identifier:a,identifierBase:s}}}if(e.length===2){let[i,s]=e;if(i!==o.IdentifierType.Alias&&i!==o.IdentifierType.Hash){let a=t.includes("?")?s+t.substring(t.indexOf("?")):s,p=Et(s,i)?o.IdentifierType.Hash:o.IdentifierType.Alias;return{chainPrefix:i,type:p,identifier:a,identifierBase:s}}}return{chainPrefix:o.IdentifierChainDefault,type:o.IdentifierType.Alias,identifier:t,identifierBase:r}},L=n=>{let t=new URL(n),e=t.searchParams.get(o.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return I(i)};var tt=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},ur=n=>{let t=new Set(Object.values(d));if(!n.includes(o.ArgParamsSeparator))return!1;let r=tt(n)[0];return t.has(r)};import Bt from"qr-code-styling";var N=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(o.HttpProtocolPrefix)?!!L(t):!1}build(t,r,e){let i=this.config.clientUrl||E.DefaultClientUrl(this.config.env),s=W(t,this.adapters),a=r===o.IdentifierType.Alias?e:r+o.IdentifierParamSeparator+e,p=s.prefix+o.IdentifierParamSeparator+a,l=encodeURIComponent(p);return E.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${o.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let r=I(t);if(!r)return null;let e=P(r.chainPrefix,this.adapters);return e?this.build(e.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,e,i=512,s="white",a="black",p="#23F7DD"){let l=W(t,this.adapters),c=this.build(l.chainInfo.name,r,e);return new Bt({type:"svg",width:i,height:i,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var $t="https://",ft=(n,t,r,e,i)=>{let s=r.actions?.[e]?.next||r.next||null;if(!s)return null;if(s.startsWith($t))return[{identifier:null,url:s}];let[a,p]=s.split("?");if(!p)return[{identifier:a,url:rt(t,a,n)}];let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let m=Y(p,{...r.vars,...i}),A=m?`${a}?${m}`:a;return[{identifier:A,url:rt(t,A,n)}]}let c=l[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let g=Array.isArray(i[f])?i[f]:[i[f]];if(g.length===0)return[];let h=l.filter(m=>m.includes(`{{${f}[]`)).map(m=>{let A=m.match(/\[\](\.[^}]+)?}}/),w=A&&A[1]||"";return{placeholder:m,field:w?w.slice(1):"",regex:new RegExp(m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return g.map(m=>{let A=p;for(let{regex:$,field:D}of h){let F=D?Vt(m,D):m;if(F==null)return null;A=A.replace($,F)}if(A.includes("{{")||A.includes("}}"))return null;let w=A?`${a}?${A}`:a;return{identifier:w,url:rt(t,w,n)}}).filter(m=>m!==null)},rt=(n,t,r)=>{let[e,i]=t.split("?"),s=I(e)||{chainPrefix:o.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=P(s.chainPrefix,n);if(!a)throw new Error(`Adapter not found for chain ${s.chainPrefix}`);let p=new N(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((c,u)=>l.searchParams.set(u,c)),l.toString().replace(/\/\?/,"?")},Vt=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function gt(n,t,r){return n.startsWith(o.Position.Payload)?n.slice(o.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}var br=(n,t,r,e)=>{let i=n.providers?.[t];return i?.[r]?i[r]:e},Pr=(n,t)=>n.providers?.[t];var B=class B{static debug(...t){B.isTestEnv||console.debug(...t)}static info(...t){B.isTestEnv||console.info(...t)}static warn(...t){B.isTestEnv||console.warn(...t)}static error(...t){B.isTestEnv||console.error(...t)}};B.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=B;var ht=async(n,t,r,e,i,s)=>{let a=[],p=[],l={};for(let[c,u]of Object.entries(n.results||{})){if(u.startsWith(o.Transform.Prefix))continue;let f=Ft(u);if(f!==null&&f!==r){l[c]=null;continue}let[g,...h]=u.split("."),C=(m,A)=>A.reduce((w,$)=>w&&w[$]!==void 0?w[$]:null,m);if(g==="out"||g.startsWith("out[")){let m=h.length===0?t?.data||t:C(t,h);a.push(String(m)),p.push(m),l[c]=m}else l[c]=u}return{values:{string:a,native:p},results:await Nt(n,l,r,e,i,s)}},Nt=async(n,t,r,e,i,s)=>{if(!n.results)return t;let a={...t};return a=Ut(a,n,r,e,i),a=await Ht(n,a,s),a},Ut=(n,t,r,e,i)=>{let s={...n},a=S(t,r)?.inputs||[];for(let[p,l]of Object.entries(s))if(typeof l=="string"&&l.startsWith("input.")){let c=l.split(".")[1],u=a.findIndex(g=>g.as===c||g.name===c),f=u!==-1?e[u]?.value:null;s[p]=f?i.stringToNative(f)[1]:null}return s},Ht=async(n,t,r)=>{if(!n.results)return t;let e={...t},i=Object.entries(n.results).filter(([,s])=>s.startsWith(o.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(o.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.run!="function"))throw new Error("Transform results are 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(p){x.error(`Transform error for result '${s}':`,p),e[s]=null}return e},Ft=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 Lt(n,t,r,e=5){let i=await ct(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 nt(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return Lt(n,i,r,5)}function it(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function Hr(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await nt(n,r,e),p=await t(i);return it(n,p,s,a)}function Fr(n){let t=new Date(n).getTime();return Date.now()<t}function Lr(n){try{let t=JSON.parse(n);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var Ot=n=>n?typeof n=="string"?n:n.address:null,b=(n,t)=>Ot(n.user?.wallets?.[t]||null),jt=n=>n?typeof n=="string"?n:n.privateKey:null,Dt=n=>n?typeof n=="string"?n:n.mnemonic:null,jr=(n,t)=>jt(n.user?.wallets?.[t]||null)?.trim()||null,Dr=(n,t)=>Dt(n.user?.wallets?.[t]||null)?.trim()||null;var y=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===d.Tuple&&Array.isArray(r)){if(r.length===0)return t+o.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(o.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(o.ArgCompositeSeparator)})${o.ArgParamsSeparator}${s.join(o.ArgListSeparator)}`}return t+o.ArgParamsSeparator+r.join(o.ArgListSeparator)}if(t===d.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(p=>p!=="_name");if(s.length===0)return`${t}(${i})${o.ArgParamsSeparator}`;let a=s.map(p=>{let[l,c]=this.getTypeAndValue(e[p]);return`(${p}${o.ArgParamsSeparator}${l})${c}`});return`${t}(${i})${o.ArgParamsSeparator}${a.join(o.ArgListSeparator)}`}if(t===d.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${o.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(o.ArgParamsSeparator))){let e=r[0],i=e.indexOf(o.ArgParamsSeparator),s=e.substring(0,i),a=r.map(l=>{let c=l.indexOf(o.ArgParamsSeparator),u=l.substring(c+1);return s.startsWith(d.Tuple)?u.replace(o.ArgListSeparator,o.ArgCompositeSeparator):u}),p=s.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator;return t+o.ArgParamsSeparator+s+o.ArgParamsSeparator+a.join(p)}return t+o.ArgParamsSeparator+r.join(o.ArgListSeparator)}if(t===d.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?d.Asset+o.ArgParamsSeparator+r.identifier+o.ArgCompositeSeparator+String(r.amount)+o.ArgCompositeSeparator+String(r.decimals):d.Asset+o.ArgParamsSeparator+r.identifier+o.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+o.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(o.ArgParamsSeparator),e=r[0],i=r.slice(1).join(o.ArgParamsSeparator);if(e==="null")return[e,null];if(e===d.Option){let[s,a]=i.split(o.ArgParamsSeparator);return[d.Option+o.ArgParamsSeparator+s,a||null]}if(e===d.Vector){let s=i.indexOf(o.ArgParamsSeparator),a=i.substring(0,s),p=i.substring(s+1),l=a.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator,u=(p?p.split(l):[]).map(f=>this.stringToNative(a+o.ArgParamsSeparator+f)[1]);return[d.Vector+o.ArgParamsSeparator+a,u]}else if(e.startsWith(d.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(o.ArgCompositeSeparator),p=i.split(o.ArgCompositeSeparator).map((l,c)=>this.stringToNative(`${s[c]}${o.IdentifierParamSeparator}${l}`)[1]);return[e,p]}else if(e.startsWith(d.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:s[1]};return i&&i.split(o.ArgListSeparator).forEach(l=>{let c=l.match(new RegExp(`^\\(([^${o.ArgParamsSeparator}]+)${o.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(c){let[,u,f,g]=c;p[u]=this.stringToNative(`${f}${o.IdentifierParamSeparator}${g}`)[1]}}),[e,p]}else{if(e===d.String)return[e,i];if(e===d.Uint8||e===d.Uint16||e===d.Uint32)return[e,Number(i)];if(e===d.Uint64||e===d.Uint128||e===d.Uint256||e===d.Biguint)return[e,BigInt(i||0)];if(e===d.Bool)return[e,i==="true"];if(e===d.Address)return[e,i];if(e===d.Hex)return[e,i];if(e===d.Asset){let[s,a]=i.split(o.ArgCompositeSeparator),p={identifier:s,amount:BigInt(a)};return[e,p]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let p=s.stringToNative(i);return[e,p]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[p,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(o.ArgParamsSeparator)){let[r,e]=t.split(o.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[d.Uint32,t]:typeof t=="bigint"?[d.Uint64,t]:typeof t=="boolean"?[d.Bool,t]:[typeof t,t]}};var Jr=n=>new y().nativeToString(d.String,n),Qr=n=>new y().nativeToString(d.Uint8,n),Kr=n=>new y().nativeToString(d.Uint16,n),Xr=n=>new y().nativeToString(d.Uint32,n),_r=n=>new y().nativeToString(d.Uint64,n),Zr=n=>new y().nativeToString(d.Biguint,n),Yr=n=>new y().nativeToString(d.Bool,n),te=n=>new y().nativeToString(d.Address,n),mt=n=>new y().nativeToString(d.Asset,n),re=n=>new y().nativeToString(d.Hex,n),ee=(n,t)=>{if(t===null)return d.Option+o.ArgParamsSeparator;let r=n(t),e=r.indexOf(o.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return d.Option+o.ArgParamsSeparator+i+o.ArgParamsSeparator+s},ne=(...n)=>new y().nativeToString(d.Tuple,n),ie=n=>new y().nativeToString(d.Struct,n),ae=n=>new y().nativeToString(d.Vector,n);import qt from"ajv";var Wt=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.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),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}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||E.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new qt,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import Mt from"ajv";var z=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}=_(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.results,"Result"),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.results||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.results&&!i&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||E.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new Mt({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 yt=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.ensure(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 lt(t,r)}ensure(t,r){if(!t)throw new Error(r)}async validate(t){let e=await new z(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
- `))}};var O=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,kt);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,zt))}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)}}},At=new y,zt=(n,t)=>typeof t=="bigint"?At.nativeToString("biguint",t):t,kt=(n,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?At.stringToNative(t)[1]:t;var T=class T{get(t){let r=T.cache.get(t);return r?Date.now()>r.expiresAt?(T.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;T.cache.set(t,{value:r,expiresAt:i})}forget(t){T.cache.delete(t)}clear(){T.cache.clear()}};T.cache=new Map;var j=T;var xt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},vt={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}`},k=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new O:t==="memory"?new j:typeof window<"u"&&window.localStorage?new O:new j}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 U=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r,e={}){let i=this.applyVars(t,r,e);return await this.applyGlobals(t,i)}async applyGlobals(t,r){let e={...r};return e.actions=await Promise.all(e.actions.map(async i=>await this.applyActionGlobals(i))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r,e={}){if(!r?.vars)return r;let i=b(t,this.adapter.chainInfo.name),s=JSON.stringify(r),a=(p,l)=>{s=s.replace(new RegExp(`{{${p.toUpperCase()}}}`,"g"),l.toString())};return Object.entries(r.vars).forEach(([p,l])=>{if(typeof l!="string")a(p,l);else if(l.startsWith(o.Vars.Query+o.ArgParamsSeparator)){let c=l.slice(o.Vars.Query.length+1),[u,f]=c.split(o.ArgCompositeSeparator),g=t.currentUrl?new URLSearchParams(t.currentUrl.split("?")[1]).get(u):null,C=e.queries?.[u]||null||g;C&&a(p,C)}else if(l.startsWith(o.Vars.Env+o.ArgParamsSeparator)){let c=l.slice(o.Vars.Env.length+1),[u,f]=c.split(o.ArgCompositeSeparator),h={...t.vars,...e.envs}?.[u];h&&a(p,h)}else l===o.Source.UserWallet&&i?a(p,i):a(p,l)}),JSON.parse(s)}async applyRootGlobals(t,r){let e=JSON.stringify(t),i={config:r,chain:this.adapter.chainInfo};return Object.values(o.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,chain:this.adapter.chainInfo};return Object.values(o.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}};var H=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 y,this.cache=new k(t.cache?.type)}getSerializer(){return this.serializer}async createExecutable(t,r,e,i={}){if(!S(t,r))throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),p=W(a.name,this.adapters),l=await new U(this.config,p).apply(this.config,t,i),c=S(l,r),u=this.getStringTypedInputs(c,e),f=await this.getResolvedInputs(a.name,c,u),g=this.getModifiedInputs(f),h=g.find(v=>v.input.position==="receiver")?.value,C=this.getDestinationFromAction(c),m=h?this.serializer.stringToNative(h)[1]:C;if(!m)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let A=this.getPreparedArgs(c,g),w=g.find(v=>v.input.position==="value")?.value||null,$="value"in c?c.value:null,D=BigInt(w?.split(o.ArgParamsSeparator)[1]||$||0),F=g.filter(v=>v.input.position==="transfer"&&v.value).map(v=>v.value),St=[...("transfers"in c?c.transfers:[])||[],...F||[]].map(v=>this.serializer.stringToNative(v)[1]),It=g.find(v=>v.input.position==="data")?.value,bt="data"in c?c.data||"":null,at={warp:l,chain:a,action:r,destination:m,args:A,value:D,transfers:St,data:It||bt||null,resolvedInputs:g};return this.cache.set(vt.WarpExecutable(this.config.env,l.meta?.hash||"",r),at.resolvedInputs,xt.OneWeek),at}async getChainInfoForWarp(t,r){if(t.chain)return W(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let e=t.inputs||[];return r.map((i,s)=>{let a=e[s];return!a||i.includes(o.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e){let i=r.inputs||[],s=await Promise.all(e.map(p=>this.preprocessInput(t,p))),a=(p,l)=>{if(p.source==="query"){let c=this.url.searchParams.get(p.name);return c?this.serializer.nativeToString(p.type,c):null}else if(p.source===o.Source.UserWallet){let c=b(this.config,t);return c?this.serializer.nativeToString("address",c):null}else return p.source==="hidden"?p.default!==void 0?this.serializer.nativeToString(p.type,p.default):null:s[l]||null};return i.map((p,l)=>{let c=a(p,l);return{input:p,value:c||(p.default!==void 0?this.serializer.nativeToString(p.type,p.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,i]=r.input.modifier.split(":");if(isNaN(Number(i))){let s=Number(t.find(l=>l.input.name===i)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let p=M(a,+s);return{...r,value:`${r.input.type}:${p}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=M(s,+i);return{...r,value:`${r.input.type}:${a}`}}}else return r})}async preprocessInput(t,r){try{let[e,i]=tt(r),s=W(t,this.adapters);if(e==="asset"){let[a,p,l]=i.split(o.ArgCompositeSeparator);if(l)return r;let c=await s.dataLoader.getAsset(a);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=M(p,c.decimals);return mt({...c,amount:u})}else return r}catch(e){throw x.warn("WarpFactory: Preprocess input failed",e),e}}getDestinationFromAction(t){return"address"in t&&t.address?t.address:"destination"in t&&t.destination?.url?t.destination.url:null}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:i,value:s})=>{if(!s||!i.position?.startsWith("arg:"))return;let a=Number(i.position.split(":")[1])-1;e.splice(a,0,s)}),e}async tryGetChainFromInputs(t,r){let e=t.actions.find(l=>l.inputs?.some(c=>c.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 W(a,this.adapters).chainInfo}};var G=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new H(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[];for(let p=1;p<=t.actions.length;p++){let l=S(t,p);if(!Z(l,t))continue;let{tx:c,chain:u,immediateExecution:f}=await this.executeAction(t,p,r,e);c&&i.push(c),u&&(s=u),f&&a.push(f)}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let p=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(p))}return{txs:i,chain:s,immediateExecutions:a}}async executeAction(t,r,e,i={}){let s=S(t,r);if(s.type==="link")return await this.callHandler(async()=>{let c=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(c):st.open(c,"_blank")}),{tx:null,chain:null,immediateExecution:null};let a=await this.factory.createExecutable(t,r,e,i);if(s.type==="collect"){let c=await this.executeCollect(a);return c.success?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c}):(this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null,immediateExecution:null})}let p=W(a.chain.name,this.adapters);if(s.type==="query"){let c=await p.executor.executeQuery(a);return c.success?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:c,tx:null})):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:a.chain,immediateExecution:c}}return{tx:await p.executor.createTransaction(a),chain:a.chain,immediateExecution:null}}async evaluateResults(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=W(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,p)=>{if(!Z(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let l=r[p],c=p+1,u=await i.results.getActionExecution(t,c,l);return u.success?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:c,chain:e,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.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=b(this.config,t.chain.name),i=S(t.warp,t.action),s=u=>{if(!u.value)return null;let f=this.factory.getSerializer().stringToNative(u.value)[1];if(u.input.type==="biguint")return f.toString();if(u.input.type==="asset"){let{identifier:g,amount:h}=f;return{identifier:g,amount:h.toString()}}else return f},a=new Headers;if(a.set("Content-Type","application/json"),a.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:u,nonce:f,expiresAt:g}=await nt(e,`${t.chain.name}-adapter`),h=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:u,chain:t.chain}));if(h){let C=it(e,h,f,g);Object.entries(C).forEach(([m,A])=>a.set(m,A))}}Object.entries(i.destination.headers||{}).forEach(([u,f])=>{a.set(u,f)});let p={};t.resolvedInputs.forEach(u=>{let f=u.input.as||u.input.name,g=s(u);if(u.input.position&&u.input.position.startsWith(o.Position.Payload)){let h=gt(u.input.position,f,g);p=et(p,h)}else p[f]=g});let l=i.destination.method||"GET",c=l==="GET"?void 0:JSON.stringify({...p,...r});x.debug("Executing collect",{url:i.destination.url,method:l,headers:a,body:c});try{let u=await fetch(i.destination.url,{method:l,headers:a,body:c});x.debug("Collect response status",{status:u.status});let f=await u.json();x.debug("Collect response content",{content:f});let{values:g,results:h}=await ht(t.warp,f,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config.transform?.runner),C=ft(this.config,this.adapters,t.warp,t.action,h);return{success:u.ok,warp:t.warp,action:t.action,user:b(this.config,t.chain.name),txHash:null,tx:null,next:C,values:g,results:{...h,_DATA:f},messages:ut(t.warp,h)}}catch(u){return x.error("WarpActionExecutor: Error executing collect",u),{success:!1,warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[]},results:{_DATA:u},messages:{}}}}async callHandler(t){if(t)return await t()}};var J=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}`);return(await i.json()).hits}catch(i){throw x.error("WarpIndex: Error searching for warps: ",i),i}}};var Q=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(o.HttpProtocolPrefix)?!!L(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),p=a.length>0,l=a.map(c=>({url:c.url,warp:c.warp}));return{match:p,results:l}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(o.HttpProtocolPrefix)?L(t):I(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,p=null,l=null,c=null,u=P(i.chainPrefix,this.adapters);if(s==="hash"){p=await u.builder().createFromTransactionHash(a,r);let g=await u.registry.getInfoByHash(a,r);l=g.registryInfo,c=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,r);l=g.registryInfo,c=g.brand,g.registryInfo&&(p=await u.builder().createFromTransactionHash(g.registryInfo.hash,r))}let f=p?await new U(this.config,u).apply(this.config,p):null;return f?{match:!0,url:t,warp:f,chain:u.chainInfo.name,registryInfo:l,brand:c}:e}catch(s){return x.error("Error detecting warp link",s),e}}};var Ct=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 G(this.config,this.adapters,t)}async detectWarp(t,r){return new Q(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"),p=s?t:null;if(!p&&a&&(p=await(await fetch(t)).json()),p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(e),{txs:c,chain:u,immediateExecutions:f}=await l.execute(p,r,{queries:i.queries});return{txs:c,chain:u,immediateExecutions:f,evaluateResults:async h=>{await l.evaluateResults(p,h)}}}createInscriptionTransaction(t,r){return W(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return W(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=I(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return P(e.chainPrefix,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!b(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(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 W(t,this.adapters).explorer}getResults(t){return W(t,this.adapters).results}async getRegistry(t){let r=W(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return W(t,this.adapters).dataLoader}getWallet(t){return W(t,this.adapters).wallet}get factory(){return new H(this.config,this.adapters)}get index(){return new J(this.config)}get linkBuilder(){return new N(this.config,this.adapters)}createBuilder(t){return W(t,this.adapters).builder()}createAbiBuilder(t){return W(t,this.adapters).abiBuilder()}createBrandBuilder(t){return W(t,this.adapters).brandBuilder()}createSerializer(t){return W(t,this.adapters).serializer}};var wt=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{K as BrowserCryptoProvider,xt as CacheTtl,X as NodeCryptoProvider,Wt as WarpBrandBuilder,yt as WarpBuilder,k as WarpCache,vt as WarpCacheKey,Pt as WarpChainName,Ct as WarpClient,E as WarpConfig,o as WarpConstants,G as WarpExecutor,H as WarpFactory,J as WarpIndex,d as WarpInputTypes,U as WarpInterpolator,N as WarpLinkBuilder,Q as WarpLinkDetecter,x as WarpLogger,V as WarpProtocolVersions,y as WarpSerializer,wt as WarpTypeRegistry,z as WarpValidator,te as address,ut as applyResultsToMessages,mt as asset,Zr as biguint,Yr as bool,gt as buildNestedPayload,Yt as bytesToBase64,Tt as bytesToHex,it as createAuthHeaders,nt as createAuthMessage,rr as createCryptoProvider,Hr as createHttpAuthHeaders,Lt as createSignableMessage,Nt as evaluateResultsCommon,ht as extractCollectResults,L as extractIdentifierInfoFromUrl,ir as extractWarpSecrets,P as findWarpAdapterByPrefix,W as findWarpAdapterForChain,ot as getCryptoProvider,q as getLatestProtocolIdentifier,ft as getNextInfo,Pr as getProviderConfig,br as getProviderUrl,pt as getRandomBytes,ct as getRandomHex,S as getWarpActionByIndex,I as getWarpInfoFromIdentifier,_ as getWarpPrimaryAction,Ot as getWarpWalletAddress,b as getWarpWalletAddressFromConfig,Dt as getWarpWalletMnemonic,Dr as getWarpWalletMnemonicFromConfig,jt as getWarpWalletPrivateKey,jr as getWarpWalletPrivateKeyFromConfig,ur as hasInputPrefix,re as hex,Z as isWarpActionAutoExecute,et as mergeNestedPayload,ee as option,Ft as parseResultsOutIndex,Lr as parseSignedMessage,Y as replacePlaceholders,st as safeWindow,Zt as setCryptoProvider,M as shiftBigintBy,tt as splitInput,Jr as string,ie as struct,tr as testCryptoAvailability,lt as toPreviewText,ne as tuple,Kr as uint16,Xr as uint32,_r as uint64,Qr as uint8,Fr as validateSignedMessage,ae as vector};
1
+ var Pr=(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))(Pr||{}),o={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},d={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"},sr=typeof window<"u"?window:{open:()=>{}};var V={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},E={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${V.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${V.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",o.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 K=class{async getRandomBytes(r){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let t=new Uint8Array(r);return window.crypto.getRandomValues(t),t}},X=class{async getRandomBytes(r){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let t=await import("crypto");return new Uint8Array(t.randomBytes(r))}catch(t){throw new Error(`Node.js crypto not available: ${t instanceof Error?t.message:"Unknown error"}`)}}},R=null;function or(){if(R)return R;if(typeof window<"u"&&window.crypto)return R=new K,R;if(typeof process<"u"&&process.versions?.node)return R=new X,R;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Zr(n){R=n}async function pr(n,r){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(r||or()).getRandomBytes(n)}function Tr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let r=new Array(n.length*2);for(let t=0;t<n.length;t++){let e=n[t];r[t*2]=(e>>>4).toString(16),r[t*2+1]=(e&15).toString(16)}return r.join("")}function Yr(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 r=String.fromCharCode.apply(null,Array.from(n));return btoa(r)}else throw new Error("Base64 encoding not available in this environment")}async function cr(n,r){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let t=await pr(n/2,r);return Tr(t)}async function rt(){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 pr(16),n.randomBytes=!0}catch{}return n}function tt(){return or()}var it=n=>Object.values(n.vars||{}).filter(r=>r.startsWith(`${o.Vars.Env}:`)).map(r=>{let t=r.replace(`${o.Vars.Env}:`,"").trim(),[e,i]=t.split(o.ArgCompositeSeparator);return{key:e,description:i||null}});var W=(n,r)=>{let t=r.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${n}`);return t},P=(n,r)=>{let t=r.find(e=>e.prefix.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for prefix: ${n}`);return t},q=n=>{if(n==="warp")return`warp:${V.Warp}`;if(n==="brand")return`brand:${V.Brand}`;if(n==="abi")return`abi:${V.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},S=(n,r)=>n?.actions[r-1],_=n=>{let r=n.actions.find(a=>a.primary===!0);if(r)return{action:r,index:n.actions.indexOf(r)};let t=["transfer","contract","query","collect"],e=n.actions.filter(a=>!t.includes(a.type));if(e.length>0){let a=e[e.length-1];return{action:a,index:n.actions.indexOf(a)}}let s=[...n.actions].reverse().find(a=>t.includes(a.type));if(!s)throw new Error(`Warp has no primary action: ${n.meta?.hash}`);return{action:s,index:n.actions.indexOf(s)}},Z=(n,r)=>{if(n.auto===!1)return!1;if(n.type==="link"){let{action:t}=_(r);return n===t||n.auto===!0}return!0},M=(n,r)=>{let t=n.toString(),[e,i=""]=t.split("."),s=Math.abs(r);if(r>0)return BigInt(e+i.padEnd(s,"0"));if(r<0){let a=e+i;if(s>=a.length)return 0n;let p=a.slice(0,-s)||"0";return BigInt(p)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},lr=(n,r=100)=>{if(!n)return"";let t=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return t=t.startsWith("- ")?t.slice(2):t,t=t.length>r?t.substring(0,t.lastIndexOf(" ",r))+"...":t,t},Y=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(t,e)=>r[e]||""),ur=(n,r)=>{let t=Object.entries(n.messages||{}).map(([e,i])=>[e,Y(i,r)]);return Object.fromEntries(t)};var pt=(n,r,t)=>{let e=r||t?.preferences?.language||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(e in n)return n[e];if("en"in n)return n.en;let i=Object.keys(n);if(i.length>0)return n[i[0]]}return""},ct=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,lt=n=>n;var Er=(n,r)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Rr=n=>{let r=o.IdentifierParamSeparator,t=n.indexOf(r);return t!==-1?{separator:r,index:t}:null},dr=n=>{let r=Rr(n);if(!r)return[n];let{separator:t,index:e}=r,i=n.substring(0,e),s=n.substring(e+t.length),a=dr(s);return[i,...a]},I=n=>{let r=decodeURIComponent(n).trim(),t=r.split("?")[0],e=dr(t);if(t.length===64&&/^[a-fA-F0-9]+$/.test(t))return{chainPrefix:o.IdentifierChainDefault,type:o.IdentifierType.Hash,identifier:r,identifierBase:t};if(e.length===2&&/^[a-zA-Z0-9]{62}$/.test(e[0])&&/^[a-zA-Z0-9]{2}$/.test(e[1]))return null;if(e.length===3){let[i,s,a]=e;if(s===o.IdentifierType.Alias||s===o.IdentifierType.Hash){let p=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chainPrefix:i,type:s,identifier:p,identifierBase:a}}}if(e.length===2){let[i,s]=e;if(i===o.IdentifierType.Alias||i===o.IdentifierType.Hash){let a=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:o.IdentifierChainDefault,type:i,identifier:a,identifierBase:s}}}if(e.length===2){let[i,s]=e;if(i!==o.IdentifierType.Alias&&i!==o.IdentifierType.Hash){let a=r.includes("?")?s+r.substring(r.indexOf("?")):s,p=Er(s,i)?o.IdentifierType.Hash:o.IdentifierType.Alias;return{chainPrefix:i,type:p,identifier:a,identifierBase:s}}}return{chainPrefix:o.IdentifierChainDefault,type:o.IdentifierType.Alias,identifier:r,identifierBase:t}},F=n=>{let r=new URL(n),e=r.searchParams.get(o.IdentifierParamName);if(e||(e=r.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return I(i)};var rr=n=>{let[r,...t]=n.split(/:(.*)/,2);return[r,t[0]||""]},ht=n=>{let r=new Set(Object.values(d));if(!n.includes(o.ArgParamsSeparator))return!1;let t=rr(n)[0];return r.has(t)};import Br from"qr-code-styling";var N=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(o.HttpProtocolPrefix)?!!F(r):!1}build(r,t,e){let i=this.config.clientUrl||E.DefaultClientUrl(this.config.env),s=W(r,this.adapters),a=t===o.IdentifierType.Alias?e:t+o.IdentifierParamSeparator+e,p=s.prefix+o.IdentifierParamSeparator+a,l=encodeURIComponent(p);return E.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${o.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(r){let t=I(r);if(!t)return null;let e=P(t.chainPrefix,this.adapters);return e?this.build(e.chainInfo.name,t.type,t.identifierBase):null}generateQrCode(r,t,e,i=512,s="white",a="black",p="#23F7DD"){let l=W(r,this.adapters),c=this.build(l.chainInfo.name,t,e);return new Br({type:"svg",width:i,height:i,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var $r="https://",fr=(n,r,t,e,i)=>{let s=t.actions?.[e]?.next||t.next||null;if(!s)return null;if(s.startsWith($r))return[{identifier:null,url:s}];let[a,p]=s.split("?");if(!p)return[{identifier:a,url:tr(r,a,n)}];let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let m=Y(p,{...t.vars,...i}),A=m?`${a}?${m}`:a;return[{identifier:A,url:tr(r,A,n)}]}let c=l[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let g=Array.isArray(i[f])?i[f]:[i[f]];if(g.length===0)return[];let h=l.filter(m=>m.includes(`{{${f}[]`)).map(m=>{let A=m.match(/\[\](\.[^}]+)?}}/),w=A&&A[1]||"";return{placeholder:m,field:w?w.slice(1):"",regex:new RegExp(m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return g.map(m=>{let A=p;for(let{regex:$,field:D}of h){let L=D?Vr(m,D):m;if(L==null)return null;A=A.replace($,L)}if(A.includes("{{")||A.includes("}}"))return null;let w=A?`${a}?${A}`:a;return{identifier:w,url:tr(r,w,n)}}).filter(m=>m!==null)},tr=(n,r,t)=>{let[e,i]=r.split("?"),s=I(e)||{chainPrefix:o.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=P(s.chainPrefix,n);if(!a)throw new Error(`Adapter not found for chain ${s.chainPrefix}`);let p=new N(t,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((c,u)=>l.searchParams.set(u,c)),l.toString().replace(/\/\?/,"?")},Vr=(n,r)=>r.split(".").reduce((t,e)=>t?.[e],n);function gr(n,r,t){return n.startsWith(o.Position.Payload)?n.slice(o.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[r]:t}:e}),{}):{[r]:t}}function er(n,r){if(!n)return{...r};if(!r)return{...n};let t={...n};return Object.keys(r).forEach(e=>{t[e]&&typeof t[e]=="object"&&typeof r[e]=="object"?t[e]=er(t[e],r[e]):t[e]=r[e]}),t}var Rt=(n,r,t,e)=>{let i=n.providers?.[r];return i?.[t]?i[t]:e},Bt=(n,r)=>n.providers?.[r];var B=class B{static debug(...r){B.isTestEnv||console.debug(...r)}static info(...r){B.isTestEnv||console.info(...r)}static warn(...r){B.isTestEnv||console.warn(...r)}static error(...r){B.isTestEnv||console.error(...r)}};B.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=B;var hr=async(n,r,t,e,i,s)=>{let a=[],p=[],l={};for(let[c,u]of Object.entries(n.results||{})){if(u.startsWith(o.Transform.Prefix))continue;let f=Lr(u);if(f!==null&&f!==t){l[c]=null;continue}let[g,...h]=u.split("."),C=(m,A)=>A.reduce((w,$)=>w&&w[$]!==void 0?w[$]:null,m);if(g==="out"||g.startsWith("out[")){let m=h.length===0?r?.data||r:C(r,h);a.push(String(m)),p.push(m),l[c]=m}else l[c]=u}return{values:{string:a,native:p},results:await Nr(n,l,t,e,i,s)}},Nr=async(n,r,t,e,i,s)=>{if(!n.results)return r;let a={...r};return a=Ur(a,n,t,e,i),a=await Hr(n,a,s),a},Ur=(n,r,t,e,i)=>{let s={...n},a=S(r,t)?.inputs||[];for(let[p,l]of Object.entries(s))if(typeof l=="string"&&l.startsWith("input.")){let c=l.split(".")[1],u=a.findIndex(g=>g.as===c||g.name===c),f=u!==-1?e[u]?.value:null;s[p]=f?i.stringToNative(f)[1]:null}return s},Hr=async(n,r,t)=>{if(!n.results)return r;let e={...r},i=Object.entries(n.results).filter(([,s])=>s.startsWith(o.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(o.Transform.Prefix.length)}));if(i.length>0&&(!t||typeof t.run!="function"))throw new Error("Transform results are 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 t.run(a,e)}catch(p){x.error(`Transform error for result '${s}':`,p),e[s]=null}return e},Lr=n=>{if(n==="out")return 1;let r=n.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};async function Fr(n,r,t,e=5){let i=await cr(64,t),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:s,purpose:r}),nonce:i,expiresAt:s}}async function nr(n,r,t,e){let i=e||`prove-wallet-ownership for app "${r}"`;return Fr(n,i,t,5)}function ir(n,r,t,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":r,"X-Signer-Nonce":t,"X-Signer-ExpiresAt":e}}async function jt(n,r,t,e){let{message:i,nonce:s,expiresAt:a}=await nr(n,t,e),p=await r(i);return ir(n,p,s,a)}function Dt(n){let r=new Date(n).getTime();return Date.now()<r}function qt(n){try{let r=JSON.parse(n);if(!r.wallet||!r.nonce||!r.expiresAt||!r.purpose)throw new Error("Invalid signed message: missing required fields");return r}catch(r){throw new Error(`Failed to parse signed message: ${r instanceof Error?r.message:"Unknown error"}`)}}var Or=n=>n?typeof n=="string"?n:n.address:null,b=(n,r)=>Or(n.user?.wallets?.[r]||null),jr=n=>n?typeof n=="string"?n:n.privateKey:null,Dr=n=>n?typeof n=="string"?n:n.mnemonic:null,kt=(n,r)=>jr(n.user?.wallets?.[r]||null)?.trim()||null,zt=(n,r)=>Dr(n.user?.wallets?.[r]||null)?.trim()||null;var y=class{constructor(r){this.typeRegistry=r?.typeRegistry}nativeToString(r,t){if(r===d.Tuple&&Array.isArray(t)){if(t.length===0)return r+o.ArgParamsSeparator;if(t.every(e=>typeof e=="string"&&e.includes(o.ArgParamsSeparator))){let e=t.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${r}(${i.join(o.ArgCompositeSeparator)})${o.ArgParamsSeparator}${s.join(o.ArgListSeparator)}`}return r+o.ArgParamsSeparator+t.join(o.ArgListSeparator)}if(r===d.Struct&&typeof t=="object"&&t!==null&&!Array.isArray(t)){let e=t;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(p=>p!=="_name");if(s.length===0)return`${r}(${i})${o.ArgParamsSeparator}`;let a=s.map(p=>{let[l,c]=this.getTypeAndValue(e[p]);return`(${p}${o.ArgParamsSeparator}${l})${c}`});return`${r}(${i})${o.ArgParamsSeparator}${a.join(o.ArgListSeparator)}`}if(r===d.Vector&&Array.isArray(t)){if(t.length===0)return`${r}${o.ArgParamsSeparator}`;if(t.every(e=>typeof e=="string"&&e.includes(o.ArgParamsSeparator))){let e=t[0],i=e.indexOf(o.ArgParamsSeparator),s=e.substring(0,i),a=t.map(l=>{let c=l.indexOf(o.ArgParamsSeparator),u=l.substring(c+1);return s.startsWith(d.Tuple)?u.replace(o.ArgListSeparator,o.ArgCompositeSeparator):u}),p=s.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator;return r+o.ArgParamsSeparator+s+o.ArgParamsSeparator+a.join(p)}return r+o.ArgParamsSeparator+t.join(o.ArgListSeparator)}if(r===d.Asset&&typeof t=="object"&&t&&"identifier"in t&&"amount"in t)return"decimals"in t?d.Asset+o.ArgParamsSeparator+t.identifier+o.ArgCompositeSeparator+String(t.amount)+o.ArgCompositeSeparator+String(t.decimals):d.Asset+o.ArgParamsSeparator+t.identifier+o.ArgCompositeSeparator+String(t.amount);if(this.typeRegistry){let e=this.typeRegistry.getHandler(r);if(e)return e.nativeToString(t);let i=this.typeRegistry.resolveType(r);if(i!==r)return this.nativeToString(i,t)}return r+o.ArgParamsSeparator+(t?.toString()??"")}stringToNative(r){let t=r.split(o.ArgParamsSeparator),e=t[0],i=t.slice(1).join(o.ArgParamsSeparator);if(e==="null")return[e,null];if(e===d.Option){let[s,a]=i.split(o.ArgParamsSeparator);return[d.Option+o.ArgParamsSeparator+s,a||null]}if(e===d.Vector){let s=i.indexOf(o.ArgParamsSeparator),a=i.substring(0,s),p=i.substring(s+1),l=a.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator,u=(p?p.split(l):[]).map(f=>this.stringToNative(a+o.ArgParamsSeparator+f)[1]);return[d.Vector+o.ArgParamsSeparator+a,u]}else if(e.startsWith(d.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(o.ArgCompositeSeparator),p=i.split(o.ArgCompositeSeparator).map((l,c)=>this.stringToNative(`${s[c]}${o.IdentifierParamSeparator}${l}`)[1]);return[e,p]}else if(e.startsWith(d.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:s[1]};return i&&i.split(o.ArgListSeparator).forEach(l=>{let c=l.match(new RegExp(`^\\(([^${o.ArgParamsSeparator}]+)${o.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(c){let[,u,f,g]=c;p[u]=this.stringToNative(`${f}${o.IdentifierParamSeparator}${g}`)[1]}}),[e,p]}else{if(e===d.String)return[e,i];if(e===d.Uint8||e===d.Uint16||e===d.Uint32)return[e,Number(i)];if(e===d.Uint64||e===d.Uint128||e===d.Uint256||e===d.Biguint)return[e,BigInt(i||0)];if(e===d.Bool)return[e,i==="true"];if(e===d.Address)return[e,i];if(e===d.Hex)return[e,i];if(e===d.Asset){let[s,a]=i.split(o.ArgCompositeSeparator),p={identifier:s,amount:BigInt(a)};return[e,p]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let p=s.stringToNative(i);return[e,p]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[p,l]=this.stringToNative(`${a}:${i}`);return[e,l]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(r){if(typeof r=="string"&&r.includes(o.ArgParamsSeparator)){let[t,e]=r.split(o.ArgParamsSeparator);return[t,e]}return typeof r=="number"?[d.Uint32,r]:typeof r=="bigint"?[d.Uint64,r]:typeof r=="boolean"?[d.Bool,r]:[typeof r,r]}};var _t=n=>new y().nativeToString(d.String,n),Zt=n=>new y().nativeToString(d.Uint8,n),Yt=n=>new y().nativeToString(d.Uint16,n),re=n=>new y().nativeToString(d.Uint32,n),te=n=>new y().nativeToString(d.Uint64,n),ee=n=>new y().nativeToString(d.Biguint,n),ne=n=>new y().nativeToString(d.Bool,n),ie=n=>new y().nativeToString(d.Address,n),mr=n=>new y().nativeToString(d.Asset,n),ae=n=>new y().nativeToString(d.Hex,n),se=(n,r)=>{if(r===null)return d.Option+o.ArgParamsSeparator;let t=n(r),e=t.indexOf(o.ArgParamsSeparator),i=t.substring(0,e),s=t.substring(e+1);return d.Option+o.ArgParamsSeparator+i+o.ArgParamsSeparator+s},oe=(...n)=>new y().nativeToString(d.Tuple,n),pe=n=>new y().nativeToString(d.Struct,n),ce=n=>new y().nativeToString(d.Vector,n);import qr from"ajv";var Wr=class{constructor(r){this.pendingBrand={protocol:q("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.schema?.brand||E.LatestBrandSchemaUrl,i=await(await fetch(t)).json(),s=new qr,a=s.compile(i);if(!a(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import Mr from"ajv";var k=class{constructor(r){this.config=r;this.config=r}async validate(r){let t=[];return t.push(...this.validatePrimaryAction(r)),t.push(...this.validateMaxOneValuePosition(r)),t.push(...this.validateVariableNamesAndResultNamesUppercase(r)),t.push(...this.validateAbiIsSetIfApplicable(r)),t.push(...await this.validateSchema(r)),{valid:t.length===0,errors:t}}validatePrimaryAction(r){try{let{action:t}=_(r);return t?[]:["Primary action is required"]}catch(t){return[t instanceof Error?t.message:"Primary action is required"]}}validateMaxOneValuePosition(r){return r.actions.filter(e=>e.inputs?e.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],e=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&t.push(`${s} name '${a}' must be uppercase`)})};return e(r.vars,"Variable"),e(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(a=>a.type==="contract"),e=r.actions.some(a=>a.type==="query");if(!t&&!e)return[];let i=r.actions.some(a=>a.abi),s=Object.values(r.results||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return r.results&&!i&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||E.LatestWarpSchemaUrl,i=await(await fetch(t)).json(),s=new Mr({strict:!1}),a=s.compile(i);return a(r)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var yr=class{constructor(r){this.config=r;this.pendingWarp={protocol:q("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.validate(e),e}async createFromUrl(r){return await(await fetch(r)).json()}setChain(r){return this.pendingWarp.chain=r,this}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),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(r,t=100){return lr(r,t)}ensure(r,t){if(!r)throw new Error(t)}ensureWarpText(r,t){if(!r)throw new Error(t);if(typeof r=="object"&&!r.en)throw new Error(t)}async validate(r){let e=await new k(this.config).validate(r);if(!e.valid)throw new Error(e.errors.join(`
2
+ `))}};var O=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let t=localStorage.getItem(this.getKey(r));if(!t)return null;let e=JSON.parse(t,zr);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(r)),null):e.value}catch{return null}}set(r,t,e){let i={value:t,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(i,kr))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let t=localStorage.key(r);t?.startsWith(this.prefix)&&localStorage.removeItem(t)}}},Ar=new y,kr=(n,r)=>typeof r=="bigint"?Ar.nativeToString("biguint",r):r,zr=(n,r)=>typeof r=="string"&&r.startsWith(d.Biguint+":")?Ar.stringToNative(r)[1]:r;var T=class T{get(r){let t=T.cache.get(r);return t?Date.now()>t.expiresAt?(T.cache.delete(r),null):t.value:null}set(r,t,e){let i=Date.now()+e*1e3;T.cache.set(r,{value:t,expiresAt:i})}forget(r){T.cache.delete(r)}clear(){T.cache.clear()}};T.cache=new Map;var j=T;var xr={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},vr={Warp:(n,r)=>`warp:${n}:${r}`,WarpAbi:(n,r)=>`warp-abi:${n}:${r}`,WarpExecutable:(n,r,t)=>`warp-exec:${n}:${r}:${t}`,RegistryInfo:(n,r)=>`registry-info:${n}:${r}`,Brand:(n,r)=>`brand:${n}:${r}`,Asset:(n,r,t)=>`asset:${n}:${r}:${t}`},z=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new O:r==="memory"?new j:typeof window<"u"&&window.localStorage?new O:new j}set(r,t,e){this.strategy.set(r,t,e)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var U=class{constructor(r,t){this.config=r;this.adapter=t}async apply(r,t,e={}){let i=this.applyVars(r,t,e);return await this.applyGlobals(r,i)}async applyGlobals(r,t){let e={...t};return e.actions=await Promise.all(e.actions.map(async i=>await this.applyActionGlobals(i))),e=await this.applyRootGlobals(e,r),e}applyVars(r,t,e={}){if(!t?.vars)return t;let i=b(r,this.adapter.chainInfo.name),s=JSON.stringify(t),a=(p,l)=>{s=s.replace(new RegExp(`{{${p.toUpperCase()}}}`,"g"),l.toString())};return Object.entries(t.vars).forEach(([p,l])=>{if(typeof l!="string")a(p,l);else if(l.startsWith(o.Vars.Query+o.ArgParamsSeparator)){let c=l.slice(o.Vars.Query.length+1),[u,f]=c.split(o.ArgCompositeSeparator),g=r.currentUrl?new URLSearchParams(r.currentUrl.split("?")[1]).get(u):null,C=e.queries?.[u]||null||g;C&&a(p,C)}else if(l.startsWith(o.Vars.Env+o.ArgParamsSeparator)){let c=l.slice(o.Vars.Env.length+1),[u,f]=c.split(o.ArgCompositeSeparator),h={...r.vars,...e.envs}?.[u];h&&a(p,h)}else l===o.Source.UserWallet&&i?a(p,i):a(p,l)}),JSON.parse(s)}async applyRootGlobals(r,t){let e=JSON.stringify(r),i={config:t,chain:this.adapter.chainInfo};return Object.values(o.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(e)}async applyActionGlobals(r){let t=JSON.stringify(r),e={config:this.config,chain:this.adapter.chainInfo};return Object.values(o.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(t=t.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(t)}};var H=class{constructor(r,t){this.config=r;this.adapters=t;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new y,this.cache=new z(r.cache?.type)}getSerializer(){return this.serializer}async createExecutable(r,t,e,i={}){if(!S(r,t))throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(r,e),p=W(a.name,this.adapters),l=await new U(this.config,p).apply(this.config,r,i),c=S(l,t),u=this.getStringTypedInputs(c,e),f=await this.getResolvedInputs(a.name,c,u),g=this.getModifiedInputs(f),h=g.find(v=>v.input.position==="receiver")?.value,C=this.getDestinationFromAction(c),m=h?this.serializer.stringToNative(h)[1]:C;if(!m)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let A=this.getPreparedArgs(c,g),w=g.find(v=>v.input.position==="value")?.value||null,$="value"in c?c.value:null,D=BigInt(w?.split(o.ArgParamsSeparator)[1]||$||0),L=g.filter(v=>v.input.position==="transfer"&&v.value).map(v=>v.value),Sr=[...("transfers"in c?c.transfers:[])||[],...L||[]].map(v=>this.serializer.stringToNative(v)[1]),Ir=g.find(v=>v.input.position==="data")?.value,br="data"in c?c.data||"":null,ar={warp:l,chain:a,action:t,destination:m,args:A,value:D,transfers:Sr,data:Ir||br||null,resolvedInputs:g};return this.cache.set(vr.WarpExecutable(this.config.env,l.meta?.hash||"",t),ar.resolvedInputs,xr.OneWeek),ar}async getChainInfoForWarp(r,t){if(r.chain)return W(r.chain,this.adapters).chainInfo;if(t){let i=await this.tryGetChainFromInputs(r,t);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(r,t){let e=r.inputs||[];return t.map((i,s)=>{let a=e[s];return!a||i.includes(o.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(r,t,e){let i=t.inputs||[],s=await Promise.all(e.map(p=>this.preprocessInput(r,p))),a=(p,l)=>{if(p.source==="query"){let c=this.url.searchParams.get(p.name);return c?this.serializer.nativeToString(p.type,c):null}else if(p.source===o.Source.UserWallet){let c=b(this.config,r);return c?this.serializer.nativeToString("address",c):null}else return p.source==="hidden"?p.default!==void 0?this.serializer.nativeToString(p.type,p.default):null:s[l]||null};return i.map((p,l)=>{let c=a(p,l);return{input:p,value:c||(p.default!==void 0?this.serializer.nativeToString(p.type,p.default):null)}})}getModifiedInputs(r){return r.map((t,e)=>{if(t.input.modifier?.startsWith("scale:")){let[,i]=t.input.modifier.split(":");if(isNaN(Number(i))){let s=Number(r.find(l=>l.input.name===i)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=t.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let p=M(a,+s);return{...t,value:`${t.input.type}:${p}`}}else{let s=t.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=M(s,+i);return{...t,value:`${t.input.type}:${a}`}}}else return t})}async preprocessInput(r,t){try{let[e,i]=rr(t),s=W(r,this.adapters);if(e==="asset"){let[a,p,l]=i.split(o.ArgCompositeSeparator);if(l)return t;let c=await s.dataLoader.getAsset(a);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=M(p,c.decimals);return mr({...c,amount:u})}else return t}catch(e){throw x.warn("WarpFactory: Preprocess input failed",e),e}}getDestinationFromAction(r){return"address"in r&&r.address?r.address:"destination"in r&&r.destination?.url?r.destination.url:null}getPreparedArgs(r,t){let e="args"in r?r.args||[]:[];return t.forEach(({input:i,value:s})=>{if(!s||!i.position?.startsWith("arg:"))return;let a=Number(i.position.split(":")[1])-1;e.splice(a,0,s)}),e}async tryGetChainFromInputs(r,t){let e=r.actions.find(l=>l.inputs?.some(c=>c.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=t[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return W(a,this.adapters).chainInfo}};var G=class{constructor(r,t,e){this.config=r;this.adapters=t;this.handlers=e;this.handlers=e,this.factory=new H(r,t)}async execute(r,t,e={}){let i=[],s=null,a=[];for(let p=1;p<=r.actions.length;p++){let l=S(r,p);if(!Z(l,r))continue;let{tx:c,chain:u,immediateExecution:f}=await this.executeAction(r,p,t,e);c&&i.push(c),u&&(s=u),f&&a.push(f)}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let p=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(p))}return{txs:i,chain:s,immediateExecutions:a}}async executeAction(r,t,e,i={}){let s=S(r,t);if(s.type==="link")return await this.callHandler(async()=>{let c=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(c):sr.open(c,"_blank")}),{tx:null,chain:null,immediateExecution:null};let a=await this.factory.createExecutable(r,t,e,i);if(s.type==="collect"){let c=await this.executeCollect(a);return c.success?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:t,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c}):(this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null,immediateExecution:null})}let p=W(a.chain.name,this.adapters);if(s.type==="query"){let c=await p.executor.executeQuery(a);return c.success?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:t,chain:a.chain,execution:c,tx:null})):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:a.chain,immediateExecution:c}}return{tx:await p.executor.createTransaction(a),chain:a.chain,immediateExecution:null}}async evaluateResults(r,t){if(t.length===0||r.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(r),i=W(e.name,this.adapters),s=(await Promise.all(r.actions.map(async(a,p)=>{if(!Z(a,r)||a.type!=="transfer"&&a.type!=="contract")return null;let l=t[p],c=p+1,u=await i.results.getActionExecution(r,c,l);return u.success?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:c,chain:e,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.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(r,t){let e=b(this.config,r.chain.name),i=S(r.warp,r.action),s=u=>{if(!u.value)return null;let f=this.factory.getSerializer().stringToNative(u.value)[1];if(u.input.type==="biguint")return f.toString();if(u.input.type==="asset"){let{identifier:g,amount:h}=f;return{identifier:g,amount:h.toString()}}else return f},a=new Headers;if(a.set("Content-Type","application/json"),a.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${r.chain.name}`);let{message:u,nonce:f,expiresAt:g}=await nr(e,`${r.chain.name}-adapter`),h=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:u,chain:r.chain}));if(h){let C=ir(e,h,f,g);Object.entries(C).forEach(([m,A])=>a.set(m,A))}}Object.entries(i.destination.headers||{}).forEach(([u,f])=>{a.set(u,f)});let p={};r.resolvedInputs.forEach(u=>{let f=u.input.as||u.input.name,g=s(u);if(u.input.position&&u.input.position.startsWith(o.Position.Payload)){let h=gr(u.input.position,f,g);p=er(p,h)}else p[f]=g});let l=i.destination.method||"GET",c=l==="GET"?void 0:JSON.stringify({...p,...t});x.debug("Executing collect",{url:i.destination.url,method:l,headers:a,body:c});try{let u=await fetch(i.destination.url,{method:l,headers:a,body:c});x.debug("Collect response status",{status:u.status});let f=await u.json();x.debug("Collect response content",{content:f});let{values:g,results:h}=await hr(r.warp,f,r.action,r.resolvedInputs,this.factory.getSerializer(),this.config.transform?.runner),C=fr(this.config,this.adapters,r.warp,r.action,h);return{success:u.ok,warp:r.warp,action:r.action,user:b(this.config,r.chain.name),txHash:null,tx:null,next:C,values:g,results:{...h,_DATA:f},messages:ur(r.warp,h)}}catch(u){return x.error("WarpActionExecutor: Error executing collect",u),{success:!1,warp:r.warp,action:r.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[]},results:{_DATA:u},messages:{}}}}async callHandler(r){if(r)return await r()}};var J=class{constructor(r){this.config=r}async search(r,t,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"]:r,...t})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}`);return(await i.json()).hits}catch(i){throw x.error("WarpIndex: Error searching for warps: ",i),i}}};var Q=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(o.HttpProtocolPrefix)?!!F(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let i=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),p=a.length>0,l=a.map(c=>({url:c.url,warp:c.warp}));return{match:p,results:l}}async detect(r,t){let e={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},i=r.startsWith(o.HttpProtocolPrefix)?F(r):I(r);if(!i)return e;try{let{type:s,identifierBase:a}=i,p=null,l=null,c=null,u=P(i.chainPrefix,this.adapters);if(s==="hash"){p=await u.builder().createFromTransactionHash(a,t);let g=await u.registry.getInfoByHash(a,t);l=g.registryInfo,c=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,t);l=g.registryInfo,c=g.brand,g.registryInfo&&(p=await u.builder().createFromTransactionHash(g.registryInfo.hash,t))}let f=p?await new U(this.config,u).apply(this.config,p):null;return f?{match:!0,url:r,warp:f,chain:u.chainInfo.name,registryInfo:l,brand:c}:e}catch(s){return x.error("Error detecting warp link",s),e}}};var Cr=class{constructor(r,t){this.config=r;this.adapters=t}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new G(this.config,this.adapters,r)}async detectWarp(r,t){return new Q(this.config,this.adapters).detect(r,t)}async executeWarp(r,t,e,i={}){let s=typeof r=="object",a=!s&&r.startsWith("http")&&r.endsWith(".json"),p=s?r:null;if(!p&&a&&(p=await(await fetch(r)).json()),p||(p=(await this.detectWarp(r,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(e),{txs:c,chain:u,immediateExecutions:f}=await l.execute(p,t,{queries:i.queries});return{txs:c,chain:u,immediateExecutions:f,evaluateResults:async h=>{await l.evaluateResults(p,h)}}}createInscriptionTransaction(r,t){return W(r,this.adapters).builder().createInscriptionTransaction(t)}async createFromTransaction(r,t,e=!1){return W(r,this.adapters).builder().createFromTransaction(t,e)}async createFromTransactionHash(r,t){let e=I(r);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return P(e.chainPrefix,this.adapters).builder().createFromTransactionHash(r,t)}async signMessage(r,t){if(!b(this.config,r))throw new Error(`No wallet configured for chain ${r}`);return W(r,this.adapters).wallet.signMessage(t)}async getActions(r,t,e=!1){let i=this.getDataLoader(r);return(await Promise.all(t.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(r){return W(r,this.adapters).explorer}getResults(r){return W(r,this.adapters).results}async getRegistry(r){let t=W(r,this.adapters).registry;return await t.init(),t}getDataLoader(r){return W(r,this.adapters).dataLoader}getWallet(r){return W(r,this.adapters).wallet}get factory(){return new H(this.config,this.adapters)}get index(){return new J(this.config)}get linkBuilder(){return new N(this.config,this.adapters)}createBuilder(r){return W(r,this.adapters).builder()}createAbiBuilder(r){return W(r,this.adapters).abiBuilder()}createBrandBuilder(r){return W(r,this.adapters).brandBuilder()}createSerializer(r){return W(r,this.adapters).serializer}};var wr=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(r,t){this.typeHandlers.set(r,t)}registerTypeAlias(r,t){this.typeAliases.set(r,t)}hasType(r){return this.typeHandlers.has(r)||this.typeAliases.has(r)}getHandler(r){let t=this.typeAliases.get(r);return t?this.getHandler(t):this.typeHandlers.get(r)}getAlias(r){return this.typeAliases.get(r)}resolveType(r){let t=this.typeAliases.get(r);return t?this.resolveType(t):r}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{K as BrowserCryptoProvider,xr as CacheTtl,X as NodeCryptoProvider,Wr as WarpBrandBuilder,yr as WarpBuilder,z as WarpCache,vr as WarpCacheKey,Pr as WarpChainName,Cr as WarpClient,E as WarpConfig,o as WarpConstants,G as WarpExecutor,H as WarpFactory,J as WarpIndex,d as WarpInputTypes,U as WarpInterpolator,N as WarpLinkBuilder,Q as WarpLinkDetecter,x as WarpLogger,V as WarpProtocolVersions,y as WarpSerializer,wr as WarpTypeRegistry,k as WarpValidator,ie as address,ur as applyResultsToMessages,mr as asset,ee as biguint,ne as bool,gr as buildNestedPayload,Yr as bytesToBase64,Tr as bytesToHex,ir as createAuthHeaders,nr as createAuthMessage,tt as createCryptoProvider,jt as createHttpAuthHeaders,Fr as createSignableMessage,lt as createWarpI18nText,Nr as evaluateResultsCommon,hr as extractCollectResults,F as extractIdentifierInfoFromUrl,it as extractWarpSecrets,P as findWarpAdapterByPrefix,W as findWarpAdapterForChain,or as getCryptoProvider,q as getLatestProtocolIdentifier,fr as getNextInfo,Bt as getProviderConfig,Rt as getProviderUrl,pr as getRandomBytes,cr as getRandomHex,S as getWarpActionByIndex,I as getWarpInfoFromIdentifier,_ as getWarpPrimaryAction,Or as getWarpWalletAddress,b as getWarpWalletAddressFromConfig,Dr as getWarpWalletMnemonic,zt as getWarpWalletMnemonicFromConfig,jr as getWarpWalletPrivateKey,kt as getWarpWalletPrivateKeyFromConfig,ht as hasInputPrefix,ae as hex,Z as isWarpActionAutoExecute,ct as isWarpI18nText,er as mergeNestedPayload,se as option,Lr as parseResultsOutIndex,qt as parseSignedMessage,Y as replacePlaceholders,pt as resolveWarpText,sr as safeWindow,Zr as setCryptoProvider,M as shiftBigintBy,rr as splitInput,_t as string,pe as struct,rt as testCryptoAvailability,lr as toPreviewText,oe as tuple,Yt as uint16,re as uint32,te as uint64,Zt as uint8,Dt as validateSignedMessage,ce as vector};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "3.0.0-alpha.122",
3
+ "version": "3.0.0-alpha.123",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",