@vleap/warps 3.0.0-alpha.55 → 3.0.0-alpha.56

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.mts CHANGED
@@ -260,22 +260,44 @@ type WarpCacheConfig = {
260
260
  type Adapter = {
261
261
  chain: WarpChain;
262
262
  prefix: string;
263
- builder: AdapterWarpBuilder;
263
+ builder: () => CombinedWarpBuilder;
264
264
  executor: AdapterWarpExecutor;
265
265
  results: AdapterWarpResults;
266
266
  serializer: AdapterWarpSerializer;
267
267
  registry: AdapterWarpRegistry;
268
268
  explorer: (chainInfo: WarpChainInfo) => AdapterWarpExplorer;
269
+ abiBuilder: () => AdapterWarpAbiBuilder;
270
+ brandBuilder: () => AdapterWarpBrandBuilder;
269
271
  };
270
272
  type WarpAdapterGenericTransaction = any;
271
273
  type WarpAdapterGenericRemoteTransaction = any;
272
274
  type WarpAdapterGenericValue = any;
273
275
  type WarpAdapterGenericType = any;
276
+ interface BaseWarpBuilder {
277
+ createFromRaw(encoded: string): Promise<Warp>;
278
+ setTitle(title: string): BaseWarpBuilder;
279
+ setDescription(description: string): BaseWarpBuilder;
280
+ setPreview(preview: string): BaseWarpBuilder;
281
+ setActions(actions: WarpAction[]): BaseWarpBuilder;
282
+ addAction(action: WarpAction): BaseWarpBuilder;
283
+ build(): Promise<Warp>;
284
+ }
274
285
  interface AdapterWarpBuilder {
275
286
  createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
276
287
  createFromTransaction(tx: WarpAdapterGenericTransaction, validate?: boolean): Promise<Warp>;
277
288
  createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
278
289
  }
290
+ type CombinedWarpBuilder = AdapterWarpBuilder & BaseWarpBuilder;
291
+ interface AdapterWarpAbiBuilder {
292
+ createFromRaw(encoded: string): Promise<any>;
293
+ createFromTransaction(tx: WarpAdapterGenericTransaction): Promise<any>;
294
+ createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<any | null>;
295
+ }
296
+ interface AdapterWarpBrandBuilder {
297
+ createInscriptionTransaction(brand: WarpBrand): WarpAdapterGenericTransaction;
298
+ createFromTransaction(tx: WarpAdapterGenericTransaction, validate?: boolean): Promise<WarpBrand>;
299
+ createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<WarpBrand | null>;
300
+ }
279
301
  interface AdapterWarpExecutor {
280
302
  createTransaction(executable: WarpExecutable): Promise<WarpAdapterGenericTransaction>;
281
303
  preprocessInput(chain: WarpChainInfo, input: string, type: WarpActionInputType, value: string): Promise<string>;
@@ -370,7 +392,8 @@ declare const WarpConfig: {
370
392
  declare const WarpConstants: {
371
393
  HttpProtocolPrefix: string;
372
394
  IdentifierParamName: string;
373
- IdentifierParamSeparator: string;
395
+ IdentifierParamSeparator: string[];
396
+ IdentifierParamSeparatorDefault: string;
374
397
  IdentifierChainDefault: string;
375
398
  IdentifierType: {
376
399
  Alias: WarpIdType;
@@ -430,7 +453,10 @@ declare const findWarpAdapterByPrefix: (prefix: string, adapters: Adapter[]) =>
430
453
  declare const getMainChainInfo: (config: WarpClientConfig) => WarpChainInfo;
431
454
  declare const getLatestProtocolIdentifier: (name: ProtocolName) => string;
432
455
  declare const getWarpActionByIndex: (warp: Warp, index: number) => WarpAction;
433
- declare const findWarpExecutableAction: (warp: Warp) => [WarpAction, WarpActionIndex];
456
+ declare const findWarpExecutableAction: (warp: Warp) => {
457
+ action: WarpAction;
458
+ actionIndex: WarpActionIndex;
459
+ };
434
460
  declare const toTypedChainInfo: (chainInfo: any) => WarpChainInfo;
435
461
  declare const shiftBigintBy: (value: bigint | string, decimals: number) => bigint;
436
462
  declare const toPreviewText: (text: string, maxChars?: number) => string;
@@ -450,7 +476,7 @@ declare const extractIdentifierInfoFromUrl: (url: string) => {
450
476
  identifierBase: string;
451
477
  } | null;
452
478
 
453
- declare const getNextInfo: (config: WarpClientConfig, warp: Warp, actionIndex: number, results: WarpExecutionResults) => WarpExecutionNextInfo | null;
479
+ declare const getNextInfo: (config: WarpClientConfig, adapter: Adapter, warp: Warp, actionIndex: number, results: WarpExecutionResults) => WarpExecutionNextInfo | null;
454
480
 
455
481
  declare const extractCollectResults: (warp: Warp, response: any, actionIndex: number, inputs: ResolvedInput[]) => Promise<{
456
482
  values: any[];
@@ -497,8 +523,8 @@ declare class WarpBrandBuilder {
497
523
  private ensureValidSchema;
498
524
  }
499
525
 
500
- declare class WarpBuilder {
501
- private config;
526
+ declare class WarpBuilder implements BaseWarpBuilder {
527
+ protected readonly config: WarpClientConfig;
502
528
  private pendingWarp;
503
529
  constructor(config: WarpClientConfig);
504
530
  createFromRaw(encoded: string, validate?: boolean): Promise<Warp>;
@@ -584,6 +610,16 @@ declare class WarpIndex {
584
610
  search(query: string, params?: Record<string, any>, headers?: Record<string, string>): Promise<WarpSearchHit[]>;
585
611
  }
586
612
 
613
+ declare class WarpLinkBuilder {
614
+ private readonly config;
615
+ private readonly adapters;
616
+ constructor(config: WarpClientConfig, adapters: Adapter[]);
617
+ isValid(url: string): boolean;
618
+ build(chain: WarpChain, type: WarpIdType, id: string): string;
619
+ buildFromPrefixedIdentifier(identifier: string): string | null;
620
+ generateQrCode(chain: WarpChain, type: WarpIdType, id: string, size?: number, background?: string, color?: string, logoColor?: string): QRCodeStyling;
621
+ }
622
+
587
623
  type DetectionResult = {
588
624
  match: boolean;
589
625
  url: string;
@@ -615,7 +651,6 @@ declare class WarpClient {
615
651
  setConfig(config: WarpClientConfig): WarpClient;
616
652
  getAdapters(): Adapter[];
617
653
  addAdapter(adapter: Adapter): WarpClient;
618
- createBuilder(): WarpBuilder;
619
654
  createExecutor(handlers?: ExecutionHandlers): WarpExecutor;
620
655
  detectWarp(urlOrId: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
621
656
  executeWarp(identifier: string, inputs: string[], handlers?: ExecutionHandlers, options?: {
@@ -633,6 +668,10 @@ declare class WarpClient {
633
668
  getRegistry(chain: WarpChain): Promise<AdapterWarpRegistry>;
634
669
  get factory(): WarpFactory;
635
670
  get index(): WarpIndex;
671
+ get linkBuilder(): WarpLinkBuilder;
672
+ createBuilder(chain: WarpChain): CombinedWarpBuilder;
673
+ createAbiBuilder(chain: WarpChain): AdapterWarpAbiBuilder;
674
+ createBrandBuilder(chain: WarpChain): AdapterWarpBrandBuilder;
636
675
  }
637
676
 
638
677
  declare class WarpInterpolator {
@@ -646,15 +685,6 @@ declare class WarpInterpolator {
646
685
  private applyActionGlobals;
647
686
  }
648
687
 
649
- declare class WarpLinkBuilder {
650
- private config;
651
- constructor(config: WarpClientConfig);
652
- isValid(url: string): boolean;
653
- build(type: WarpIdType, id: string): string;
654
- buildFromPrefixedIdentifier(identifier: string): string;
655
- generateQrCode(type: WarpIdType, id: string, size?: number, background?: string, color?: string, logoColor?: string): QRCodeStyling;
656
- }
657
-
658
688
  declare class WarpLogger {
659
689
  private static isTestEnv;
660
690
  static info(...args: any[]): void;
@@ -682,4 +712,4 @@ declare class WarpValidator {
682
712
  private validateSchema;
683
713
  }
684
714
 
685
- export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, CacheTtl, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, 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 WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
715
+ export { type Adapter, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, type BaseWarpBuilder, CacheTtl, type CombinedWarpBuilder, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, 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 WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
package/dist/index.d.ts CHANGED
@@ -260,22 +260,44 @@ type WarpCacheConfig = {
260
260
  type Adapter = {
261
261
  chain: WarpChain;
262
262
  prefix: string;
263
- builder: AdapterWarpBuilder;
263
+ builder: () => CombinedWarpBuilder;
264
264
  executor: AdapterWarpExecutor;
265
265
  results: AdapterWarpResults;
266
266
  serializer: AdapterWarpSerializer;
267
267
  registry: AdapterWarpRegistry;
268
268
  explorer: (chainInfo: WarpChainInfo) => AdapterWarpExplorer;
269
+ abiBuilder: () => AdapterWarpAbiBuilder;
270
+ brandBuilder: () => AdapterWarpBrandBuilder;
269
271
  };
270
272
  type WarpAdapterGenericTransaction = any;
271
273
  type WarpAdapterGenericRemoteTransaction = any;
272
274
  type WarpAdapterGenericValue = any;
273
275
  type WarpAdapterGenericType = any;
276
+ interface BaseWarpBuilder {
277
+ createFromRaw(encoded: string): Promise<Warp>;
278
+ setTitle(title: string): BaseWarpBuilder;
279
+ setDescription(description: string): BaseWarpBuilder;
280
+ setPreview(preview: string): BaseWarpBuilder;
281
+ setActions(actions: WarpAction[]): BaseWarpBuilder;
282
+ addAction(action: WarpAction): BaseWarpBuilder;
283
+ build(): Promise<Warp>;
284
+ }
274
285
  interface AdapterWarpBuilder {
275
286
  createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
276
287
  createFromTransaction(tx: WarpAdapterGenericTransaction, validate?: boolean): Promise<Warp>;
277
288
  createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
278
289
  }
290
+ type CombinedWarpBuilder = AdapterWarpBuilder & BaseWarpBuilder;
291
+ interface AdapterWarpAbiBuilder {
292
+ createFromRaw(encoded: string): Promise<any>;
293
+ createFromTransaction(tx: WarpAdapterGenericTransaction): Promise<any>;
294
+ createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<any | null>;
295
+ }
296
+ interface AdapterWarpBrandBuilder {
297
+ createInscriptionTransaction(brand: WarpBrand): WarpAdapterGenericTransaction;
298
+ createFromTransaction(tx: WarpAdapterGenericTransaction, validate?: boolean): Promise<WarpBrand>;
299
+ createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<WarpBrand | null>;
300
+ }
279
301
  interface AdapterWarpExecutor {
280
302
  createTransaction(executable: WarpExecutable): Promise<WarpAdapterGenericTransaction>;
281
303
  preprocessInput(chain: WarpChainInfo, input: string, type: WarpActionInputType, value: string): Promise<string>;
@@ -370,7 +392,8 @@ declare const WarpConfig: {
370
392
  declare const WarpConstants: {
371
393
  HttpProtocolPrefix: string;
372
394
  IdentifierParamName: string;
373
- IdentifierParamSeparator: string;
395
+ IdentifierParamSeparator: string[];
396
+ IdentifierParamSeparatorDefault: string;
374
397
  IdentifierChainDefault: string;
375
398
  IdentifierType: {
376
399
  Alias: WarpIdType;
@@ -430,7 +453,10 @@ declare const findWarpAdapterByPrefix: (prefix: string, adapters: Adapter[]) =>
430
453
  declare const getMainChainInfo: (config: WarpClientConfig) => WarpChainInfo;
431
454
  declare const getLatestProtocolIdentifier: (name: ProtocolName) => string;
432
455
  declare const getWarpActionByIndex: (warp: Warp, index: number) => WarpAction;
433
- declare const findWarpExecutableAction: (warp: Warp) => [WarpAction, WarpActionIndex];
456
+ declare const findWarpExecutableAction: (warp: Warp) => {
457
+ action: WarpAction;
458
+ actionIndex: WarpActionIndex;
459
+ };
434
460
  declare const toTypedChainInfo: (chainInfo: any) => WarpChainInfo;
435
461
  declare const shiftBigintBy: (value: bigint | string, decimals: number) => bigint;
436
462
  declare const toPreviewText: (text: string, maxChars?: number) => string;
@@ -450,7 +476,7 @@ declare const extractIdentifierInfoFromUrl: (url: string) => {
450
476
  identifierBase: string;
451
477
  } | null;
452
478
 
453
- declare const getNextInfo: (config: WarpClientConfig, warp: Warp, actionIndex: number, results: WarpExecutionResults) => WarpExecutionNextInfo | null;
479
+ declare const getNextInfo: (config: WarpClientConfig, adapter: Adapter, warp: Warp, actionIndex: number, results: WarpExecutionResults) => WarpExecutionNextInfo | null;
454
480
 
455
481
  declare const extractCollectResults: (warp: Warp, response: any, actionIndex: number, inputs: ResolvedInput[]) => Promise<{
456
482
  values: any[];
@@ -497,8 +523,8 @@ declare class WarpBrandBuilder {
497
523
  private ensureValidSchema;
498
524
  }
499
525
 
500
- declare class WarpBuilder {
501
- private config;
526
+ declare class WarpBuilder implements BaseWarpBuilder {
527
+ protected readonly config: WarpClientConfig;
502
528
  private pendingWarp;
503
529
  constructor(config: WarpClientConfig);
504
530
  createFromRaw(encoded: string, validate?: boolean): Promise<Warp>;
@@ -584,6 +610,16 @@ declare class WarpIndex {
584
610
  search(query: string, params?: Record<string, any>, headers?: Record<string, string>): Promise<WarpSearchHit[]>;
585
611
  }
586
612
 
613
+ declare class WarpLinkBuilder {
614
+ private readonly config;
615
+ private readonly adapters;
616
+ constructor(config: WarpClientConfig, adapters: Adapter[]);
617
+ isValid(url: string): boolean;
618
+ build(chain: WarpChain, type: WarpIdType, id: string): string;
619
+ buildFromPrefixedIdentifier(identifier: string): string | null;
620
+ generateQrCode(chain: WarpChain, type: WarpIdType, id: string, size?: number, background?: string, color?: string, logoColor?: string): QRCodeStyling;
621
+ }
622
+
587
623
  type DetectionResult = {
588
624
  match: boolean;
589
625
  url: string;
@@ -615,7 +651,6 @@ declare class WarpClient {
615
651
  setConfig(config: WarpClientConfig): WarpClient;
616
652
  getAdapters(): Adapter[];
617
653
  addAdapter(adapter: Adapter): WarpClient;
618
- createBuilder(): WarpBuilder;
619
654
  createExecutor(handlers?: ExecutionHandlers): WarpExecutor;
620
655
  detectWarp(urlOrId: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
621
656
  executeWarp(identifier: string, inputs: string[], handlers?: ExecutionHandlers, options?: {
@@ -633,6 +668,10 @@ declare class WarpClient {
633
668
  getRegistry(chain: WarpChain): Promise<AdapterWarpRegistry>;
634
669
  get factory(): WarpFactory;
635
670
  get index(): WarpIndex;
671
+ get linkBuilder(): WarpLinkBuilder;
672
+ createBuilder(chain: WarpChain): CombinedWarpBuilder;
673
+ createAbiBuilder(chain: WarpChain): AdapterWarpAbiBuilder;
674
+ createBrandBuilder(chain: WarpChain): AdapterWarpBrandBuilder;
636
675
  }
637
676
 
638
677
  declare class WarpInterpolator {
@@ -646,15 +685,6 @@ declare class WarpInterpolator {
646
685
  private applyActionGlobals;
647
686
  }
648
687
 
649
- declare class WarpLinkBuilder {
650
- private config;
651
- constructor(config: WarpClientConfig);
652
- isValid(url: string): boolean;
653
- build(type: WarpIdType, id: string): string;
654
- buildFromPrefixedIdentifier(identifier: string): string;
655
- generateQrCode(type: WarpIdType, id: string, size?: number, background?: string, color?: string, logoColor?: string): QRCodeStyling;
656
- }
657
-
658
688
  declare class WarpLogger {
659
689
  private static isTestEnv;
660
690
  static info(...args: any[]): void;
@@ -682,4 +712,4 @@ declare class WarpValidator {
682
712
  private validateSchema;
683
713
  }
684
714
 
685
- export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, CacheTtl, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, 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 WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
715
+ export { type Adapter, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, type BaseWarpBuilder, CacheTtl, type CombinedWarpBuilder, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, 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 WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Ar=Object.create;var K=Object.defineProperty;var br=Object.getOwnPropertyDescriptor;var Er=Object.getOwnPropertyNames;var Tr=Object.getPrototypeOf,Pr=Object.prototype.hasOwnProperty;var dr=(n,r)=>()=>(n&&(r=n(n=0)),r);var Z=(n,r)=>{for(var t in r)K(n,t,{get:r[t],enumerable:!0})},fr=(n,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Er(r))!Pr.call(n,a)&&a!==t&&K(n,a,{get:()=>r[a],enumerable:!(e=br(r,a))||e.enumerable});return n};var Y=(n,r,t)=>(t=n!=null?Ar(Tr(n)):{},fr(r||!n||!n.__esModule?K(t,"default",{value:n,enumerable:!0}):t,n)),Rr=n=>fr(K({},"__esModule",{value:!0}),n);var mr={};Z(mr,{runInVm:()=>Nr});var Ur,Nr,gr=dr(()=>{"use strict";Ur=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),Nr=async(n,r)=>{let t;try{t=Ur("vm2").VM}catch{throw new Error('The optional dependency "vm2" is not installed. To use runInVm in Node.js, please install vm2: npm install vm2 --save.')}let e=new t({timeout:2e3,sandbox:{result:r},eval:!1,wasm:!1});return n.trim().startsWith("(")&&n.includes("=>")?e.run(`(${n})(result)`):null}});var Wr={};Z(Wr,{runInVm:()=>Vr});var Vr,yr=dr(()=>{"use strict";Vr=async(n,r)=>new Promise((t,e)=>{try{let a=new Blob([`
1
+ "use strict";var br=Object.create;var J=Object.defineProperty;var Er=Object.getOwnPropertyDescriptor;var Tr=Object.getOwnPropertyNames;var Pr=Object.getPrototypeOf,Rr=Object.prototype.hasOwnProperty;var dr=(n,r)=>()=>(n&&(r=n(n=0)),r);var X=(n,r)=>{for(var t in r)J(n,t,{get:r[t],enumerable:!0})},fr=(n,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Tr(r))!Rr.call(n,a)&&a!==t&&J(n,a,{get:()=>r[a],enumerable:!(e=Er(r,a))||e.enumerable});return n};var Z=(n,r,t)=>(t=n!=null?br(Pr(n)):{},fr(r||!n||!n.__esModule?J(t,"default",{value:n,enumerable:!0}):t,n)),Sr=n=>fr(J({},"__esModule",{value:!0}),n);var gr={};X(gr,{runInVm:()=>Vr});var Lr,Vr,Wr=dr(()=>{"use strict";Lr=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),Vr=async(n,r)=>{let t;try{t=Lr("vm2").VM}catch{throw new Error('The optional dependency "vm2" is not installed. To use runInVm in Node.js, please install vm2: npm install vm2 --save.')}let e=new t({timeout:2e3,sandbox:{result:r},eval:!1,wasm:!1});return n.trim().startsWith("(")&&n.includes("=>")?e.run(`(${n})(result)`):null}});var yr={};X(yr,{runInVm:()=>Or});var Or,xr=dr(()=>{"use strict";Or=async(n,r)=>new Promise((t,e)=>{try{let a=new Blob([`
2
2
  self.onmessage = function(e) {
3
3
  try {
4
4
  const result = e.data;
@@ -8,5 +8,5 @@
8
8
  self.postMessage({ error: error.toString() });
9
9
  }
10
10
  };
11
- `],{type:"application/javascript"}),s=URL.createObjectURL(a),i=new Worker(s);i.onmessage=function(o){o.data.error?e(new Error(o.data.error)):t(o.data.result),i.terminate(),URL.revokeObjectURL(s)},i.onerror=function(o){e(new Error(`Error in transform: ${o.message}`)),i.terminate(),URL.revokeObjectURL(s)},i.postMessage(r)}catch(a){return e(a)}})});var Kr={};Z(Kr,{CacheTtl:()=>X,KnownTokens:()=>Cr,WarpBrandBuilder:()=>or,WarpBuilder:()=>F,WarpCache:()=>q,WarpCacheKey:()=>pr,WarpClient:()=>lr,WarpConfig:()=>g,WarpConstants:()=>p,WarpExecutor:()=>G,WarpFactory:()=>B,WarpIndex:()=>z,WarpInputTypes:()=>C,WarpInterpolator:()=>$,WarpLinkBuilder:()=>H,WarpLinkDetecter:()=>J,WarpLogger:()=>x,WarpProtocolVersions:()=>S,WarpSerializer:()=>T,WarpValidator:()=>k,address:()=>zr,applyResultsToMessages:()=>nr,biguint:()=>qr,boolean:()=>Gr,evaluateResultsCommon:()=>vr,extractCollectResults:()=>sr,extractIdentifierInfoFromUrl:()=>N,findKnownTokenById:()=>Dr,findWarpAdapterByPrefix:()=>O,findWarpAdapterForChain:()=>v,findWarpDefaultAdapter:()=>rr,findWarpExecutableAction:()=>tr,getLatestProtocolIdentifier:()=>D,getMainChainInfo:()=>U,getNextInfo:()=>ir,getWarpActionByIndex:()=>E,getWarpInfoFromIdentifier:()=>b,hex:()=>Jr,parseResultsOutIndex:()=>xr,replacePlaceholders:()=>_,shiftBigintBy:()=>Q,string:()=>Hr,toPreviewText:()=>er,toTypedChainInfo:()=>Sr,u16:()=>Fr,u32:()=>Mr,u64:()=>jr,u8:()=>kr});module.exports=Rr(Kr);var p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:n=>n.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},C={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var S={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},g={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${S.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${S.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"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:n=>n==="devnet"?"https://devnet-api.multiversx.com":n==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:n=>n==="devnet"?"https://devnet-explorer.multiversx.com":n==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:n=>6e3,AddressHrp:"erd",ChainId:n=>n==="devnet"?"D":n==="testnet"?"T":"1",NativeToken:"EGLD"},AvailableActionInputSources:["field","query",p.Source.UserWallet],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 rr=n=>{let r=n.find(t=>t.chain.toLowerCase()===g.MainChain.Name.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${g.MainChain.Name}`);return r},v=(n,r)=>{let t=r.find(e=>e.chain.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${n}`);return t},O=(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},U=n=>({name:g.MainChain.Name,displayName:g.MainChain.DisplayName,chainId:g.MainChain.ChainId(n.env),blockTime:g.MainChain.BlockTime(n.env),addressHrp:g.MainChain.AddressHrp,apiUrl:g.MainChain.ApiUrl(n.env),explorerUrl:g.MainChain.ExplorerUrl(n.env),nativeToken:g.MainChain.NativeToken}),D=n=>{if(n==="warp")return`warp:${S.Warp}`;if(n==="brand")return`brand:${S.Brand}`;if(n==="abi")return`abi:${S.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},E=(n,r)=>n?.actions[r-1],tr=n=>(n.actions.forEach((r,t)=>{if(r.type!=="link")return[r,t]}),[E(n,1),1]),Sr=n=>({name:n.name.toString(),displayName:n.display_name.toString(),chainId:n.chain_id.toString(),blockTime:n.block_time.toNumber(),addressHrp:n.address_hrp.toString(),apiUrl:n.api_url.toString(),explorerUrl:n.explorer_url.toString(),nativeToken:n.native_token.toString()}),Q=(n,r)=>{let t=n.toString(),[e,a=""]=t.split("."),s=Math.abs(r);if(r>0)return BigInt(e+a.padEnd(s,"0"));if(r<0){let i=e+a;if(s>=i.length)return 0n;let o=i.slice(0,-s)||"0";return BigInt(o)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},er=(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},_=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(t,e)=>r[e]||""),nr=(n,r)=>{let t=Object.entries(n.messages||{}).map(([e,a])=>[e,_(a,r)]);return Object.fromEntries(t)};var b=n=>{let r=decodeURIComponent(n).trim(),t=r.split(p.IdentifierParamSeparator),e=r.split("?")[0];return t.length===3&&(t[1]===p.IdentifierType.Alias||t[1]===p.IdentifierType.Hash)?{chainPrefix:t[0],type:t[1],identifier:t[2],identifierBase:t[2].split("?")[0]}:t.length===2&&(t[0]===p.IdentifierType.Alias||t[0]===p.IdentifierType.Hash)?{chainPrefix:p.IdentifierChainDefault,type:t[0],identifier:t[1],identifierBase:t[1].split("?")[0]}:t.length===2&&/^[a-zA-Z0-9]{62}$/.test(t[0])&&/^[a-zA-Z0-9]{2}$/.test(t[1])?null:t.length===2&&t[0]!==p.IdentifierType.Alias&&t[0]!==p.IdentifierType.Hash?{chainPrefix:t[0],type:p.IdentifierType.Alias,identifier:t[1],identifierBase:t[1].split("?")[0]}:e.length===64?{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:r,identifierBase:e}:{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:e}},N=n=>{let r=new URL(n),e=r.searchParams.get(p.IdentifierParamName);if(e||(e=r.pathname.split("/")[1]),!e)return null;let a=decodeURIComponent(e);return b(a)};var hr=Y(require("qr-code-styling"));var H=class{constructor(r){this.config=r;this.config=r}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!N(r):!1}build(r,t){let e=this.config.clientUrl||g.DefaultClientUrl(this.config.env),a=r===p.IdentifierType.Alias?encodeURIComponent(t):encodeURIComponent(r+p.IdentifierParamSeparator+t);return g.SuperClientUrls.includes(e)?`${e}/${a}`:`${e}?${p.IdentifierParamName}=${a}`}buildFromPrefixedIdentifier(r){let t=b(r);return t?this.build(t.type,t.identifierBase):""}generateQrCode(r,t,e=512,a="white",s="black",i="#23F7DD"){let o=this.build(r,t);return new hr.default({type:"svg",width:e,height:e,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(i)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Br="https://",ir=(n,r,t,e)=>{let a=r.actions?.[t]?.next||r.next||null;if(!a)return null;if(a.startsWith(Br))return[{identifier:null,url:a}];let[s,i]=a.split("?");if(!i)return[{identifier:s,url:ar(s,n)}];let o=i.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let f=_(i,{...r.vars,...e}),h=f?`${s}?${f}`:s;return[{identifier:h,url:ar(h,n)}]}let l=o[0];if(!l)return[];let c=l.match(/{{([^[]+)\[\]/),u=c?c[1]:null;if(!u||e[u]===void 0)return[];let W=Array.isArray(e[u])?e[u]:[e[u]];if(W.length===0)return[];let d=o.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let h=f.match(/\[\](\.[^}]+)?}}/),w=h&&h[1]||"";return{placeholder:f,field:w?w.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return W.map(f=>{let h=i;for(let{regex:m,field:y}of d){let R=y?$r(f,y):f;if(R==null)return null;h=h.replace(m,R)}if(h.includes("{{")||h.includes("}}"))return null;let w=h?`${s}?${h}`:s;return{identifier:w,url:ar(w,n)}}).filter(f=>f!==null)},ar=(n,r)=>{let[t,e]=n.split("?"),a=b(t)||{type:"alias",identifier:t,identifierBase:t},i=new H(r).build(a.type,a.identifierBase);if(!e)return i;let o=new URL(i);return new URLSearchParams(e).forEach((l,c)=>o.searchParams.set(c,l)),o.toString().replace(/\/\?/,"?")},$r=(n,r)=>r.split(".").reduce((t,e)=>t?.[e],n);var V=class V{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 T=class{nativeToString(r,t){return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(p.ArgParamsSeparator),e=t[0],a=t.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[s,i]=a.split(p.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(e==="optional"){let[s,i]=a.split(p.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(e==="list"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,c]}else if(e==="variadic"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,c]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=a.split(p.ArgCompositeSeparator).map((l,c)=>this.stringToNative(`${s[c]}:${l}`)[1]);return[e,o]}else{if(e==="string")return[e,a];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(a)];if(e==="uint64"||e==="biguint")return[e,BigInt(a||0)];if(e==="bool")return[e,a==="true"];if(e==="address")return[e,a];if(e==="token")return[e,a];if(e==="hex")return[e,a];if(e==="codemeta")return[e,a];if(e==="esdt"){let[s,i,o]=a.split(p.ArgCompositeSeparator);return[e,`${s}|${i}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var sr=async(n,r,t,e)=>{let a=[],s={};for(let[i,o]of Object.entries(n.results||{})){if(o.startsWith(p.Transform.Prefix))continue;let l=xr(o);if(l!==null&&l!==t){s[i]=null;continue}let[c,...u]=o.split("."),W=(d,I)=>I.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d);if(c==="out"||c.startsWith("out[")){let d=u.length===0?r?.data||r:W(r,u);a.push(d),s[i]=d}else s[i]=o}return{values:a,results:await vr(n,s,t,e)}},vr=async(n,r,t,e)=>{if(!n.results)return r;let a={...r};return a=Lr(a,n,t,e),a=await Or(n,a),a},Lr=(n,r,t,e)=>{let a={...n},s=E(r,t)?.inputs||[],i=new T;for(let[o,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("input.")){let c=l.split(".")[1],u=s.findIndex(d=>d.as===c||d.name===c),W=u!==-1?e[u]?.value:null;a[o]=W?i.stringToNative(W)[1]:null}return a},Or=async(n,r)=>{if(!n.results)return r;let t={...r},e=Object.entries(n.results).filter(([,a])=>a.startsWith(p.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(p.Transform.Prefix.length)}));for(let{key:a,code:s}of e)try{let i;typeof window>"u"?i=(await Promise.resolve().then(()=>(gr(),mr))).runInVm:i=(await Promise.resolve().then(()=>(yr(),Wr))).runInVm,t[a]=await i(s,t)}catch(i){x.error(`Transform error for result '${a}':`,i),t[a]=null}return t},xr=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)};var Cr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Dr=n=>Cr.find(r=>r.id===n)||null;var Hr=n=>`${C.String}:${n}`,kr=n=>`${C.U8}:${n}`,Fr=n=>`${C.U16}:${n}`,Mr=n=>`${C.U32}:${n}`,jr=n=>`${C.U64}:${n}`,qr=n=>`${C.Biguint}:${n}`,Gr=n=>`${C.Boolean}:${n}`,zr=n=>`${C.Address}:${n}`,Jr=n=>`${C.Hex}:${n}`;var Ir=Y(require("ajv"));var or=class{constructor(r){this.pendingBrand={protocol:D("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||g.LatestBrandSchemaUrl,a=await(await fetch(t)).json(),s=new Ir.default,i=s.compile(a);if(!i(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};var wr=Y(require("ajv"));var k=class{constructor(r){this.config=r;this.config=r}async validate(r){let t=[];return 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}}validateMaxOneValuePosition(r){return r.actions.filter(e=>e.inputs?e.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],e=(a,s)=>{a&&Object.keys(a).forEach(i=>{i!==i.toUpperCase()&&t.push(`${s} name '${i}' must be uppercase`)})};return e(r.vars,"Variable"),e(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(i=>i.type==="contract"),e=r.actions.some(i=>i.type==="query");if(!t&&!e)return[];let a=r.actions.some(i=>i.abi),s=Object.values(r.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return r.results&&!a&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||g.LatestWarpSchemaUrl,a=await(await fetch(t)).json(),s=new wr.default({strict:!1}),i=s.compile(a);return i(r)?[]:[`Schema validation failed: ${s.errorsText(i.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var F=class{constructor(r){this.config=r;this.pendingWarp={protocol:D("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.validate(e),e}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.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(r,t=100){return er(r,t)}ensure(r,t){if(!r)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(`
12
- `))}};var M=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);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(r)),null):e.value}catch{return null}}set(r,t,e){let a={value:t,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(a))}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)}}};var P=class P{get(r){let t=P.cache.get(r);return t?Date.now()>t.expiresAt?(P.cache.delete(r),null):t.value:null}set(r,t,e){let a=Date.now()+e*1e3;P.cache.set(r,{value:t,expiresAt:a})}forget(r){P.cache.delete(r)}clear(){P.cache.clear()}};P.cache=new Map;var j=P;var X={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},pr={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}`,ChainInfo:(n,r)=>`chain:${n}:${r}`,ChainInfos:n=>`chains:${n}`},q=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new M:r==="memory"?new j:typeof window<"u"&&window.localStorage?new M: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 B=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 T,this.cache=new q(r.cache?.type)}async createExecutable(r,t,e){let a=E(r,t);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForAction(a,e),i=await this.getResolvedInputs(s,a,e),o=this.getModifiedInputs(i),l=o.find(A=>A.input.position==="receiver")?.value,c="address"in a?a.address:null,u=l?.split(":")[1]||c;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let W=u,d=this.getPreparedArgs(a,o),I=o.find(A=>A.input.position==="value")?.value||null,f="value"in a?a.value:null,h=BigInt(I?.split(":")[1]||f||0),w=o.filter(A=>A.input.position==="transfer"&&A.value).map(A=>A.value),y=[...("transfers"in a?a.transfers:[])||[],...w||[]],R=o.find(A=>A.input.position==="data")?.value,L="data"in a?a.data||"":null,ur={warp:r,chain:s,action:t,destination:W,args:d,value:h,transfers:y,data:R||L||null,resolvedInputs:o};return this.cache.set(pr.WarpExecutable(this.config.env,r.meta?.hash||"",t),ur.resolvedInputs,X.OneWeek),ur}async getChainInfoForAction(r,t){if(t){let e=await this.tryGetChainFromInputs(r,t);if(e)return e}return this.getDefaultChainInfo(r)}async getResolvedInputs(r,t,e){let a=t.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(r,o))),i=(o,l)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===p.Source.UserWallet?this.config.user?.wallets?.[r.name]?this.serializer.nativeToString("address",this.config.user.wallets[r.name]):null:s[l]||null};return a.map((o,l)=>{let c=i(o,l);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((t,e)=>{if(t.input.modifier?.startsWith("scale:")){let[,a]=t.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(r.find(l=>l.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let i=t.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=Q(i,+s);return{...t,value:`${t.input.type}:${o}`}}else{let s=t.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let i=Q(s,+a);return{...t,value:`${t.input.type}:${i}`}}}else return t})}async preprocessInput(r,t){try{let[e,a]=t.split(p.ArgParamsSeparator,2);return v(r.name,this.adapters).executor.preprocessInput(r,t,e,a)}catch{return t}}getPreparedArgs(r,t){let e="args"in r?r.args||[]:[];return t.forEach(({input:a,value:s})=>{if(!s||!a.position?.startsWith("arg:"))return;let i=Number(a.position.split(":")[1])-1;e.splice(i,0,s)}),e}async tryGetChainFromInputs(r,t){let e=r.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let a=t[e];if(!a)throw new Error("WarpUtils: Chain input not found");let i=new T().stringToNative(a)[1],l=await v(i,this.adapters).registry.getChainInfo(i);if(!l)throw new Error(`WarpUtils: Chain info not found for ${i}`);return l}async getDefaultChainInfo(r){if(!r.chain)return U(this.config);let e=await rr(this.adapters).registry.getChainInfo(r.chain,{ttl:X.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${r.chain}`);return e}};var $=class{constructor(r,t){this.config=r;this.adapter=t}async apply(r,t){let e=this.applyVars(r,t);return await this.applyGlobals(r,e)}async applyGlobals(r,t){let e={...t};return e.actions=await Promise.all(e.actions.map(async a=>await this.applyActionGlobals(a))),e=await this.applyRootGlobals(e,r),e}applyVars(r,t){if(!t?.vars)return t;let e=JSON.stringify(t),a=(s,i)=>{e=e.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(t.vars).forEach(([s,i])=>{if(typeof i!="string")a(s,i);else if(i.startsWith(`${p.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${p.Vars.Query}:`)[1],l=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);l&&a(s,l)}else if(i.startsWith(`${p.Vars.Env}:`)){let o=i.split(`${p.Vars.Env}:`)[1],l=r.vars?.[o];l&&a(s,l)}else if(i===p.Source.UserWallet&&r.user?.wallets?.[this.adapter.chain]){let o=r.user.wallets[this.adapter.chain];o&&a(s,o)}else a(s,i)}),JSON.parse(e)}async applyRootGlobals(r,t){let e=JSON.stringify(r),a={config:t,chain:U(t)};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}async applyActionGlobals(r){let t=r.chain?await this.adapter.registry.getChainInfo(r.chain):U(this.config);if(!t)throw new Error(`Chain info not found for ${r.chain}`);let e=JSON.stringify(r),a={config:this.config,chain:t};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}};var G=class{constructor(r,t,e){this.config=r;this.adapters=t;this.handlers=e;this.factory=new B(r,t),this.handlers=e}async execute(r,t){let[e,a]=tr(r);if(e.type==="collect"){let c=await this.executeCollect(r,a,t);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let s=await this.factory.createExecutable(r,a,t),i=s.chain.name.toLowerCase(),o=this.adapters.find(c=>c.chain.toLowerCase()===i);if(!o)throw new Error(`No adapter registered for chain: ${i}`);return{tx:await o.executor.createTransaction(s),chain:s.chain}}async evaluateResults(r,t,e){let a=this.adapters.find(i=>i.chain.toLowerCase()===t.name.toLowerCase());if(!a)throw new Error(`No adapter registered for chain: ${t.name}`);let s=await a.results.getTransactionExecutionResults(r,e);this.handlers?.onExecuted?.(s)}async executeCollect(r,t,e,a){let s=E(r,t);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=v(i.name,this.adapters),l=await new $(this.config,o).apply(this.config,r),c=await this.factory.getResolvedInputs(i,s,e),u=this.factory.getModifiedInputs(c),W=this.factory.serializer,d=m=>{if(!m.value)return null;let y=W.stringToNative(m.value)[1];return m.input.type==="biguint"?y.toString():m.input.type==="esdt"?{}:y},I=new Headers;I.set("Content-Type","application/json"),I.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([m,y])=>{I.set(m,y)});let f=Object.fromEntries(u.map(m=>[m.input.as||m.input.name,d(m)])),h=s.destination.method||"GET",w=h==="GET"?void 0:JSON.stringify({...f,...a});x.info("Executing collect",{url:s.destination.url,method:h,headers:I,body:w});try{let m=await fetch(s.destination.url,{method:h,headers:I,body:w}),y=await m.json(),{values:R,results:L}=await sr(l,y,t,u),cr=ir(this.config,l,t,L);return{success:m.ok,warp:l,action:t,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:cr,values:R,results:{...L,_DATA:y},messages:nr(l,L)}}catch(m){return x.error("WarpActionExecutor: Error executing collect",m),{success:!1,warp:l,action:t,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:null,values:[],results:{_DATA:m},messages:{}}}}};var z=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 a=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(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw x.error("WarpIndex: Error searching for warps: ",a),a}}};var J=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!N(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let a=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),i=(await Promise.all(a)).filter(c=>c.match),o=i.length>0,l=i.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:l}}async detect(r,t){let e={match:!1,url:r,warp:null,registryInfo:null,brand:null},a=r.startsWith(p.HttpProtocolPrefix)?N(r):b(r);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,l=null,c=null,u=O(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder.createFromTransactionHash(i,t);let d=await u.registry.getInfoByHash(i,t);l=d.registryInfo,c=d.brand}else if(s==="alias"){let d=await u.registry.getInfoByAlias(i,t);l=d.registryInfo,c=d.brand,d.registryInfo&&(o=await u.builder.createFromTransactionHash(d.registryInfo.hash,t))}let W=o?await new $(this.config,u).apply(this.config,o):null;return W?{match:!0,url:r,warp:W,registryInfo:l,brand:c}:e}catch(s){return x.error("Error detecting warp link",s),e}}};var lr=class{constructor(r,t){this.config=r;this.adapters=t}getConfig(){return this.config}setConfig(r){return this.config=r,this}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createBuilder(){return new F(this.config)}createExecutor(r){return new G(this.config,this.adapters,r)}async detectWarp(r,t){return new J(this.config,this.adapters).detect(r,t)}async executeWarp(r,t,e,a={}){let s=await this.detectWarp(r,a.cache);if(!s.match||!s.warp)throw new Error("Warp not found");let i=this.createExecutor(e),{tx:o,chain:l}=await i.execute(s.warp,t);return{tx:o,chain:l,evaluateResults:async u=>{if(!l||!o||!s.warp)throw new Error("Warp not found");await i.evaluateResults(s.warp,l,u)}}}createInscriptionTransaction(r,t){return v(r,this.adapters).builder.createInscriptionTransaction(t)}async createFromTransaction(r,t,e=!1){return v(r,this.adapters).builder.createFromTransaction(t,e)}async createFromTransactionHash(r,t){let e=b(r);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return O(e.chainPrefix,this.adapters).builder.createFromTransactionHash(r,t)}getExplorer(r){return v(r.name,this.adapters).explorer(r)}getResults(r){return v(r.name,this.adapters).results}async getRegistry(r){let t=v(r,this.adapters).registry;return await t.init(),t}get factory(){return new B(this.config,this.adapters)}get index(){return new z(this.config)}};0&&(module.exports={CacheTtl,KnownTokens,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpValidator,address,applyResultsToMessages,biguint,boolean,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,findKnownTokenById,findWarpAdapterByPrefix,findWarpAdapterForChain,findWarpDefaultAdapter,findWarpExecutableAction,getLatestProtocolIdentifier,getMainChainInfo,getNextInfo,getWarpActionByIndex,getWarpInfoFromIdentifier,hex,parseResultsOutIndex,replacePlaceholders,shiftBigintBy,string,toPreviewText,toTypedChainInfo,u16,u32,u64,u8});
11
+ `],{type:"application/javascript"}),s=URL.createObjectURL(a),i=new Worker(s);i.onmessage=function(o){o.data.error?e(new Error(o.data.error)):t(o.data.result),i.terminate(),URL.revokeObjectURL(s)},i.onerror=function(o){e(new Error(`Error in transform: ${o.message}`)),i.terminate(),URL.revokeObjectURL(s)},i.postMessage(r)}catch(a){return e(a)}})});var _r={};X(_r,{CacheTtl:()=>_,KnownTokens:()=>Ir,WarpBrandBuilder:()=>sr,WarpBuilder:()=>or,WarpCache:()=>j,WarpCacheKey:()=>pr,WarpClient:()=>lr,WarpConfig:()=>m,WarpConstants:()=>l,WarpExecutor:()=>q,WarpFactory:()=>U,WarpIndex:()=>G,WarpInputTypes:()=>I,WarpInterpolator:()=>N,WarpLinkBuilder:()=>$,WarpLinkDetecter:()=>z,WarpLogger:()=>x,WarpProtocolVersions:()=>S,WarpSerializer:()=>P,WarpValidator:()=>k,address:()=>Kr,applyResultsToMessages:()=>er,biguint:()=>zr,boolean:()=>Jr,evaluateResultsCommon:()=>vr,extractCollectResults:()=>ir,extractIdentifierInfoFromUrl:()=>O,findKnownTokenById:()=>kr,findWarpAdapterByPrefix:()=>B,findWarpAdapterForChain:()=>W,findWarpDefaultAdapter:()=>Y,findWarpExecutableAction:()=>rr,getLatestProtocolIdentifier:()=>F,getMainChainInfo:()=>V,getNextInfo:()=>ar,getWarpActionByIndex:()=>T,getWarpInfoFromIdentifier:()=>A,hex:()=>Qr,parseResultsOutIndex:()=>Cr,replacePlaceholders:()=>Q,shiftBigintBy:()=>K,string:()=>Hr,toPreviewText:()=>tr,toTypedChainInfo:()=>Br,u16:()=>jr,u32:()=>qr,u64:()=>Gr,u8:()=>Mr});module.exports=Sr(_r);var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:n=>n.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},I={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var S={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},m={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${S.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${S.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"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:n=>n==="devnet"?"https://devnet-api.multiversx.com":n==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:n=>n==="devnet"?"https://devnet-explorer.multiversx.com":n==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:n=>6e3,AddressHrp:"erd",ChainId:n=>n==="devnet"?"D":n==="testnet"?"T":"1",NativeToken:"EGLD"},AvailableActionInputSources:["field","query",l.Source.UserWallet],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 Y=n=>{let r=n.find(t=>t.chain.toLowerCase()===m.MainChain.Name.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${m.MainChain.Name}`);return r},W=(n,r)=>{let t=r.find(e=>e.chain.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${n}`);return t},B=(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},V=n=>({name:m.MainChain.Name,displayName:m.MainChain.DisplayName,chainId:m.MainChain.ChainId(n.env),blockTime:m.MainChain.BlockTime(n.env),addressHrp:m.MainChain.AddressHrp,apiUrl:m.MainChain.ApiUrl(n.env),explorerUrl:m.MainChain.ExplorerUrl(n.env),nativeToken:m.MainChain.NativeToken}),F=n=>{if(n==="warp")return`warp:${S.Warp}`;if(n==="brand")return`brand:${S.Brand}`;if(n==="abi")return`abi:${S.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},T=(n,r)=>n?.actions[r-1],rr=n=>(n.actions.forEach((r,t)=>{if(r.type!=="link")return{action:r,actionIndex:t}}),{action:T(n,1),actionIndex:1}),Br=n=>({name:n.name.toString(),displayName:n.display_name.toString(),chainId:n.chain_id.toString(),blockTime:n.block_time.toNumber(),addressHrp:n.address_hrp.toString(),apiUrl:n.api_url.toString(),explorerUrl:n.explorer_url.toString(),nativeToken:n.native_token.toString()}),K=(n,r)=>{let t=n.toString(),[e,a=""]=t.split("."),s=Math.abs(r);if(r>0)return BigInt(e+a.padEnd(s,"0"));if(r<0){let i=e+a;if(s>=i.length)return 0n;let o=i.slice(0,-s)||"0";return BigInt(o)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},tr=(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},Q=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(t,e)=>r[e]||""),er=(n,r)=>{let t=Object.entries(n.messages||{}).map(([e,a])=>[e,Q(a,r)]);return Object.fromEntries(t)};var $r=n=>{let r=l.IdentifierParamSeparator,t=-1,e="";for(let a of r){let s=n.indexOf(a);s!==-1&&(t===-1||s<t)&&(t=s,e=a)}return t!==-1?{separator:e,index:t}:null},hr=n=>{let r=$r(n);if(!r)return[n];let{separator:t,index:e}=r,a=n.substring(0,e),s=n.substring(e+t.length),i=hr(s);return[a,...i]},A=n=>{let r=decodeURIComponent(n).trim(),t=r.split("?")[0],e=hr(t);if(t.length===64&&/^[a-fA-F0-9]+$/.test(t))return{chainPrefix:l.IdentifierChainDefault,type:l.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[a,s,i]=e;if(s===l.IdentifierType.Alias||s===l.IdentifierType.Hash){let o=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:a,type:s,identifier:o,identifierBase:i}}}if(e.length===2){let[a,s]=e;if(a===l.IdentifierType.Alias||a===l.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:l.IdentifierChainDefault,type:a,identifier:i,identifierBase:s}}}if(e.length===2){let[a,s]=e;if(a!==l.IdentifierType.Alias&&a!==l.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:a,type:l.IdentifierType.Alias,identifier:i,identifierBase:s}}}return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:r,identifierBase:t}},O=n=>{let r=new URL(n),e=r.searchParams.get(l.IdentifierParamName);if(e||(e=r.pathname.split("/")[1]),!e)return null;let a=decodeURIComponent(e);return A(a)};var mr=Z(require("qr-code-styling"));var $=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!O(r):!1}build(r,t,e){let a=this.config.clientUrl||m.DefaultClientUrl(this.config.env),s=W(r,this.adapters),i=t===l.IdentifierType.Alias?e:t+l.IdentifierParamSeparatorDefault+e,o=s.prefix+l.IdentifierParamSeparatorDefault+i,p=encodeURIComponent(o);return m.SuperClientUrls.includes(a)?`${a}/${p}`:`${a}?${l.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(r){let t=A(r);if(!t)return null;let e=B(t.chainPrefix,this.adapters);return e?this.build(e.chain,t.type,t.identifierBase):null}generateQrCode(r,t,e,a=512,s="white",i="black",o="#23F7DD"){let p=W(r,this.adapters),c=this.build(p.chain,t,e);return new mr.default({type:"svg",width:a,height:a,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Ur="https://",ar=(n,r,t,e,a)=>{let s=t.actions?.[e]?.next||t.next||null;if(!s)return null;if(s.startsWith(Ur))return[{identifier:null,url:s}];let[i,o]=s.split("?");if(!o)return[{identifier:i,url:nr(r,i,n)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let h=Q(o,{...t.vars,...a}),y=h?`${i}?${h}`:i;return[{identifier:y,url:nr(r,y,n)}]}let c=p[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),g=u?u[1]:null;if(!g||a[g]===void 0)return[];let f=Array.isArray(a[g])?a[g]:[a[g]];if(f.length===0)return[];let v=p.filter(h=>h.includes(`{{${g}[]`)).map(h=>{let y=h.match(/\[\](\.[^}]+)?}}/),d=y&&y[1]||"";return{placeholder:h,field:d?d.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(h=>{let y=o;for(let{regex:C,field:L}of v){let b=L?Nr(h,L):h;if(b==null)return null;y=y.replace(C,b)}if(y.includes("{{")||y.includes("}}"))return null;let d=y?`${i}?${y}`:i;return{identifier:d,url:nr(r,d,n)}}).filter(h=>h!==null)},nr=(n,r,t)=>{let[e,a]=r.split("?"),s=A(e)||{type:"alias",identifier:e,identifierBase:e},i=new $(t,[n]).build(n.chain,s.type,s.identifierBase);if(!a)return i;let o=new URL(i);return new URLSearchParams(a).forEach((p,c)=>o.searchParams.set(c,p)),o.toString().replace(/\/\?/,"?")},Nr=(n,r)=>r.split(".").reduce((t,e)=>t?.[e],n);var D=class D{static info(...r){D.isTestEnv||console.info(...r)}static warn(...r){D.isTestEnv||console.warn(...r)}static error(...r){D.isTestEnv||console.error(...r)}};D.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=D;var P=class{nativeToString(r,t){return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(l.ArgParamsSeparator),e=t[0],a=t.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[s,i]=a.split(l.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(e==="optional"){let[s,i]=a.split(l.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(e==="list"){let s=a.split(l.ArgParamsSeparator),i=s.slice(0,-1).join(l.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,c]}else if(e==="variadic"){let s=a.split(l.ArgParamsSeparator),i=s.slice(0,-1).join(l.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,c]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=a.split(l.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${s[c]}:${p}`)[1]);return[e,o]}else{if(e==="string")return[e,a];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(a)];if(e==="uint64"||e==="biguint")return[e,BigInt(a||0)];if(e==="bool")return[e,a==="true"];if(e==="address")return[e,a];if(e==="token")return[e,a];if(e==="hex")return[e,a];if(e==="codemeta")return[e,a];if(e==="esdt"){let[s,i,o]=a.split(l.ArgCompositeSeparator);return[e,`${s}|${i}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var ir=async(n,r,t,e)=>{let a=[],s={};for(let[i,o]of Object.entries(n.results||{})){if(o.startsWith(l.Transform.Prefix))continue;let p=Cr(o);if(p!==null&&p!==t){s[i]=null;continue}let[c,...u]=o.split("."),g=(f,v)=>v.reduce((E,h)=>E&&E[h]!==void 0?E[h]:null,f);if(c==="out"||c.startsWith("out[")){let f=u.length===0?r?.data||r:g(r,u);a.push(f),s[i]=f}else s[i]=o}return{values:a,results:await vr(n,s,t,e)}},vr=async(n,r,t,e)=>{if(!n.results)return r;let a={...r};return a=Dr(a,n,t,e),a=await Fr(n,a),a},Dr=(n,r,t,e)=>{let a={...n},s=T(r,t)?.inputs||[],i=new P;for(let[o,p]of Object.entries(a))if(typeof p=="string"&&p.startsWith("input.")){let c=p.split(".")[1],u=s.findIndex(f=>f.as===c||f.name===c),g=u!==-1?e[u]?.value:null;a[o]=g?i.stringToNative(g)[1]:null}return a},Fr=async(n,r)=>{if(!n.results)return r;let t={...r},e=Object.entries(n.results).filter(([,a])=>a.startsWith(l.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(l.Transform.Prefix.length)}));for(let{key:a,code:s}of e)try{let i;typeof window>"u"?i=(await Promise.resolve().then(()=>(Wr(),gr))).runInVm:i=(await Promise.resolve().then(()=>(xr(),yr))).runInVm,t[a]=await i(s,t)}catch(i){x.error(`Transform error for result '${a}':`,i),t[a]=null}return t},Cr=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)};var Ir=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],kr=n=>Ir.find(r=>r.id===n)||null;var Hr=n=>`${I.String}:${n}`,Mr=n=>`${I.U8}:${n}`,jr=n=>`${I.U16}:${n}`,qr=n=>`${I.U32}:${n}`,Gr=n=>`${I.U64}:${n}`,zr=n=>`${I.Biguint}:${n}`,Jr=n=>`${I.Boolean}:${n}`,Kr=n=>`${I.Address}:${n}`,Qr=n=>`${I.Hex}:${n}`;var wr=Z(require("ajv"));var sr=class{constructor(r){this.pendingBrand={protocol:F("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||m.LatestBrandSchemaUrl,a=await(await fetch(t)).json(),s=new wr.default,i=s.compile(a);if(!i(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};var Ar=Z(require("ajv"));var k=class{constructor(r){this.config=r;this.config=r}async validate(r){let t=[];return 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}}validateMaxOneValuePosition(r){return r.actions.filter(e=>e.inputs?e.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],e=(a,s)=>{a&&Object.keys(a).forEach(i=>{i!==i.toUpperCase()&&t.push(`${s} name '${i}' must be uppercase`)})};return e(r.vars,"Variable"),e(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(i=>i.type==="contract"),e=r.actions.some(i=>i.type==="query");if(!t&&!e)return[];let a=r.actions.some(i=>i.abi),s=Object.values(r.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return r.results&&!a&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||m.LatestWarpSchemaUrl,a=await(await fetch(t)).json(),s=new Ar.default({strict:!1}),i=s.compile(a);return i(r)?[]:[`Schema validation failed: ${s.errorsText(i.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var or=class{constructor(r){this.config=r;this.pendingWarp={protocol:F("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.validate(e),e}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.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(r,t=100){return tr(r,t)}ensure(r,t){if(!r)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(`
12
+ `))}};var H=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);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(r)),null):e.value}catch{return null}}set(r,t,e){let a={value:t,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(a))}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)}}};var R=class R{get(r){let t=R.cache.get(r);return t?Date.now()>t.expiresAt?(R.cache.delete(r),null):t.value:null}set(r,t,e){let a=Date.now()+e*1e3;R.cache.set(r,{value:t,expiresAt:a})}forget(r){R.cache.delete(r)}clear(){R.cache.clear()}};R.cache=new Map;var M=R;var _={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},pr={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}`,ChainInfo:(n,r)=>`chain:${n}:${r}`,ChainInfos:n=>`chains:${n}`},j=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new H:r==="memory"?new M:typeof window<"u"&&window.localStorage?new H: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 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 P,this.cache=new j(r.cache?.type)}async createExecutable(r,t,e){let a=T(r,t);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForAction(a,e),i=await this.getResolvedInputs(s,a,e),o=this.getModifiedInputs(i),p=o.find(w=>w.input.position==="receiver")?.value,c="address"in a?a.address:null,u=p?.split(":")[1]||c;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let g=u,f=this.getPreparedArgs(a,o),v=o.find(w=>w.input.position==="value")?.value||null,E="value"in a?a.value:null,h=BigInt(v?.split(":")[1]||E||0),y=o.filter(w=>w.input.position==="transfer"&&w.value).map(w=>w.value),C=[...("transfers"in a?a.transfers:[])||[],...y||[]],L=o.find(w=>w.input.position==="data")?.value,b="data"in a?a.data||"":null,ur={warp:r,chain:s,action:t,destination:g,args:f,value:h,transfers:C,data:L||b||null,resolvedInputs:o};return this.cache.set(pr.WarpExecutable(this.config.env,r.meta?.hash||"",t),ur.resolvedInputs,_.OneWeek),ur}async getChainInfoForAction(r,t){if(t){let e=await this.tryGetChainFromInputs(r,t);if(e)return e}return this.getDefaultChainInfo(r)}async getResolvedInputs(r,t,e){let a=t.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(r,o))),i=(o,p)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===l.Source.UserWallet?this.config.user?.wallets?.[r.name]?this.serializer.nativeToString("address",this.config.user.wallets[r.name]):null:s[p]||null};return a.map((o,p)=>{let c=i(o,p);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((t,e)=>{if(t.input.modifier?.startsWith("scale:")){let[,a]=t.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(r.find(p=>p.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let i=t.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=K(i,+s);return{...t,value:`${t.input.type}:${o}`}}else{let s=t.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let i=K(s,+a);return{...t,value:`${t.input.type}:${i}`}}}else return t})}async preprocessInput(r,t){try{let[e,a]=t.split(l.ArgParamsSeparator,2);return W(r.name,this.adapters).executor.preprocessInput(r,t,e,a)}catch{return t}}getPreparedArgs(r,t){let e="args"in r?r.args||[]:[];return t.forEach(({input:a,value:s})=>{if(!s||!a.position?.startsWith("arg:"))return;let i=Number(a.position.split(":")[1])-1;e.splice(i,0,s)}),e}async tryGetChainFromInputs(r,t){let e=r.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let a=t[e];if(!a)throw new Error("WarpUtils: Chain input not found");let i=new P().stringToNative(a)[1],p=await W(i,this.adapters).registry.getChainInfo(i);if(!p)throw new Error(`WarpUtils: Chain info not found for ${i}`);return p}async getDefaultChainInfo(r){if(!r.chain)return V(this.config);let e=await Y(this.adapters).registry.getChainInfo(r.chain,{ttl:_.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${r.chain}`);return e}};var N=class{constructor(r,t){this.config=r;this.adapter=t}async apply(r,t){let e=this.applyVars(r,t);return await this.applyGlobals(r,e)}async applyGlobals(r,t){let e={...t};return e.actions=await Promise.all(e.actions.map(async a=>await this.applyActionGlobals(a))),e=await this.applyRootGlobals(e,r),e}applyVars(r,t){if(!t?.vars)return t;let e=JSON.stringify(t),a=(s,i)=>{e=e.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(t.vars).forEach(([s,i])=>{if(typeof i!="string")a(s,i);else if(i.startsWith(`${l.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${l.Vars.Query}:`)[1],p=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);p&&a(s,p)}else if(i.startsWith(`${l.Vars.Env}:`)){let o=i.split(`${l.Vars.Env}:`)[1],p=r.vars?.[o];p&&a(s,p)}else if(i===l.Source.UserWallet&&r.user?.wallets?.[this.adapter.chain]){let o=r.user.wallets[this.adapter.chain];o&&a(s,o)}else a(s,i)}),JSON.parse(e)}async applyRootGlobals(r,t){let e=JSON.stringify(r),a={config:t,chain:V(t)};return Object.values(l.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}async applyActionGlobals(r){let t=r.chain?await this.adapter.registry.getChainInfo(r.chain):V(this.config);if(!t)throw new Error(`Chain info not found for ${r.chain}`);let e=JSON.stringify(r),a={config:this.config,chain:t};return Object.values(l.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}};var q=class{constructor(r,t,e){this.config=r;this.adapters=t;this.handlers=e;this.factory=new U(r,t),this.handlers=e}async execute(r,t){let{action:e,actionIndex:a}=rr(r);if(e.type==="collect"){let c=await this.executeCollect(r,a,t);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let s=await this.factory.createExecutable(r,a,t),i=s.chain.name.toLowerCase(),o=this.adapters.find(c=>c.chain.toLowerCase()===i);if(!o)throw new Error(`No adapter registered for chain: ${i}`);return{tx:await o.executor.createTransaction(s),chain:s.chain}}async evaluateResults(r,t,e){let a=this.adapters.find(i=>i.chain.toLowerCase()===t.name.toLowerCase());if(!a)throw new Error(`No adapter registered for chain: ${t.name}`);let s=await a.results.getTransactionExecutionResults(r,e);this.handlers?.onExecuted?.(s)}async executeCollect(r,t,e,a){let s=T(r,t);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=W(i.name,this.adapters),p=await new N(this.config,o).apply(this.config,r),c=await this.factory.getResolvedInputs(i,s,e),u=this.factory.getModifiedInputs(c),g=this.factory.serializer,f=d=>{if(!d.value)return null;let C=g.stringToNative(d.value)[1];return d.input.type==="biguint"?C.toString():d.input.type==="esdt"?{}:C},v=new Headers;v.set("Content-Type","application/json"),v.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([d,C])=>{v.set(d,C)});let E=Object.fromEntries(u.map(d=>[d.input.as||d.input.name,f(d)])),h=s.destination.method||"GET",y=h==="GET"?void 0:JSON.stringify({...E,...a});x.info("Executing collect",{url:s.destination.url,method:h,headers:v,body:y});try{let d=await fetch(s.destination.url,{method:h,headers:v,body:y}),C=await d.json(),{values:L,results:b}=await ir(p,C,t,u),cr=ar(this.config,o,p,t,b);return{success:d.ok,warp:p,action:t,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:cr,values:L,results:{...b,_DATA:C},messages:er(p,b)}}catch(d){return x.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:p,action:t,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};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 a=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(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw x.error("WarpIndex: Error searching for warps: ",a),a}}};var z=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!O(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let a=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),i=(await Promise.all(a)).filter(c=>c.match),o=i.length>0,p=i.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(r,t){let e={match:!1,url:r,warp:null,registryInfo:null,brand:null},a=r.startsWith(l.HttpProtocolPrefix)?O(r):A(r);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,p=null,c=null,u=B(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder().createFromTransactionHash(i,t);let f=await u.registry.getInfoByHash(i,t);p=f.registryInfo,c=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(i,t);p=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,t))}let g=o?await new N(this.config,u).apply(this.config,o):null;return g?{match:!0,url:r,warp:g,registryInfo:p,brand:c}:e}catch(s){return x.error("Error detecting warp link",s),e}}};var lr=class{constructor(r,t){this.config=r;this.adapters=t}getConfig(){return this.config}setConfig(r){return this.config=r,this}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new q(this.config,this.adapters,r)}async detectWarp(r,t){return new z(this.config,this.adapters).detect(r,t)}async executeWarp(r,t,e,a={}){let s=await this.detectWarp(r,a.cache);if(!s.match||!s.warp)throw new Error("Warp not found");let i=this.createExecutor(e),{tx:o,chain:p}=await i.execute(s.warp,t);return{tx:o,chain:p,evaluateResults:async u=>{if(!p||!o||!s.warp)throw new Error("Warp not found");await i.evaluateResults(s.warp,p,u)}}}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=A(r);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return B(e.chainPrefix,this.adapters).builder().createFromTransactionHash(r,t)}getExplorer(r){return W(r.name,this.adapters).explorer(r)}getResults(r){return W(r.name,this.adapters).results}async getRegistry(r){let t=W(r,this.adapters).registry;return await t.init(),t}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 W(r,this.adapters).builder()}createAbiBuilder(r){return W(r,this.adapters).abiBuilder()}createBrandBuilder(r){return W(r,this.adapters).brandBuilder()}};0&&(module.exports={CacheTtl,KnownTokens,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpValidator,address,applyResultsToMessages,biguint,boolean,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,findKnownTokenById,findWarpAdapterByPrefix,findWarpAdapterForChain,findWarpDefaultAdapter,findWarpExecutableAction,getLatestProtocolIdentifier,getMainChainInfo,getNextInfo,getWarpActionByIndex,getWarpInfoFromIdentifier,hex,parseResultsOutIndex,replacePlaceholders,shiftBigintBy,string,toPreviewText,toTypedChainInfo,u16,u32,u64,u8});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import"./chunk-3SAEGOMQ.mjs";var p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:n=>n.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},A={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var S={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},g={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${S.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${S.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"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:n=>n==="devnet"?"https://devnet-api.multiversx.com":n==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:n=>n==="devnet"?"https://devnet-explorer.multiversx.com":n==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:n=>6e3,AddressHrp:"erd",ChainId:n=>n==="devnet"?"D":n==="testnet"?"T":"1",NativeToken:"EGLD"},AvailableActionInputSources:["field","query",p.Source.UserWallet],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 tt=n=>{let t=n.find(r=>r.chain.toLowerCase()===g.MainChain.Name.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${g.MainChain.Name}`);return t},x=(n,t)=>{let r=t.find(e=>e.chain.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},H=(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},V=n=>({name:g.MainChain.Name,displayName:g.MainChain.DisplayName,chainId:g.MainChain.ChainId(n.env),blockTime:g.MainChain.BlockTime(n.env),addressHrp:g.MainChain.AddressHrp,apiUrl:g.MainChain.ApiUrl(n.env),explorerUrl:g.MainChain.ExplorerUrl(n.env),nativeToken:g.MainChain.NativeToken}),F=n=>{if(n==="warp")return`warp:${S.Warp}`;if(n==="brand")return`brand:${S.Brand}`;if(n==="abi")return`abi:${S.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},P=(n,t)=>n?.actions[t-1],rt=n=>(n.actions.forEach((t,r)=>{if(t.type!=="link")return[t,r]}),[P(n,1),1]),wt=n=>({name:n.name.toString(),displayName:n.display_name.toString(),chainId:n.chain_id.toString(),blockTime:n.block_time.toNumber(),addressHrp:n.address_hrp.toString(),apiUrl:n.api_url.toString(),explorerUrl:n.explorer_url.toString(),nativeToken:n.native_token.toString()}),K=(n,t)=>{let r=n.toString(),[e,a=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+a.padEnd(s,"0"));if(t<0){let i=e+a;if(s>=i.length)return 0n;let o=i.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},et=(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},Q=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),nt=(n,t)=>{let r=Object.entries(n.messages||{}).map(([e,a])=>[e,Q(a,t)]);return Object.fromEntries(r)};var b=n=>{let t=decodeURIComponent(n).trim(),r=t.split(p.IdentifierParamSeparator),e=t.split("?")[0];return r.length===3&&(r[1]===p.IdentifierType.Alias||r[1]===p.IdentifierType.Hash)?{chainPrefix:r[0],type:r[1],identifier:r[2],identifierBase:r[2].split("?")[0]}:r.length===2&&(r[0]===p.IdentifierType.Alias||r[0]===p.IdentifierType.Hash)?{chainPrefix:p.IdentifierChainDefault,type:r[0],identifier:r[1],identifierBase:r[1].split("?")[0]}:r.length===2&&/^[a-zA-Z0-9]{62}$/.test(r[0])&&/^[a-zA-Z0-9]{2}$/.test(r[1])?null:r.length===2&&r[0]!==p.IdentifierType.Alias&&r[0]!==p.IdentifierType.Hash?{chainPrefix:r[0],type:p.IdentifierType.Alias,identifier:r[1],identifierBase:r[1].split("?")[0]}:e.length===64?{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:t,identifierBase:e}:{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:t,identifierBase:e}},L=n=>{let t=new URL(n),e=t.searchParams.get(p.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let a=decodeURIComponent(e);return b(a)};import lt from"qr-code-styling";var k=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!L(t):!1}build(t,r){let e=this.config.clientUrl||g.DefaultClientUrl(this.config.env),a=t===p.IdentifierType.Alias?encodeURIComponent(r):encodeURIComponent(t+p.IdentifierParamSeparator+r);return g.SuperClientUrls.includes(e)?`${e}/${a}`:`${e}?${p.IdentifierParamName}=${a}`}buildFromPrefixedIdentifier(t){let r=b(t);return r?this.build(r.type,r.identifierBase):""}generateQrCode(t,r,e=512,a="white",s="black",i="#23F7DD"){let o=this.build(t,r);return new lt({type:"svg",width:e,height:e,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(i)}" 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 ct="https://",at=(n,t,r,e)=>{let a=t.actions?.[r]?.next||t.next||null;if(!a)return null;if(a.startsWith(ct))return[{identifier:null,url:a}];let[s,i]=a.split("?");if(!i)return[{identifier:s,url:_(s,n)}];let o=i.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let f=Q(i,{...t.vars,...e}),h=f?`${s}?${f}`:s;return[{identifier:h,url:_(h,n)}]}let l=o[0];if(!l)return[];let c=l.match(/{{([^[]+)\[\]/),u=c?c[1]:null;if(!u||e[u]===void 0)return[];let W=Array.isArray(e[u])?e[u]:[e[u]];if(W.length===0)return[];let d=o.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let h=f.match(/\[\](\.[^}]+)?}}/),I=h&&h[1]||"";return{placeholder:f,field:I?I.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return W.map(f=>{let h=i;for(let{regex:m,field:y}of d){let T=y?ut(f,y):f;if(T==null)return null;h=h.replace(m,T)}if(h.includes("{{")||h.includes("}}"))return null;let I=h?`${s}?${h}`:s;return{identifier:I,url:_(I,n)}}).filter(f=>f!==null)},_=(n,t)=>{let[r,e]=n.split("?"),a=b(r)||{type:"alias",identifier:r,identifierBase:r},i=new k(t).build(a.type,a.identifierBase);if(!e)return i;let o=new URL(i);return new URLSearchParams(e).forEach((l,c)=>o.searchParams.set(c,l)),o.toString().replace(/\/\?/,"?")},ut=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);var B=class B{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 v=B;var R=class{nativeToString(t,r){return`${t}:${r?.toString()??""}`}stringToNative(t){let r=t.split(p.ArgParamsSeparator),e=r[0],a=r.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[s,i]=a.split(p.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(e==="optional"){let[s,i]=a.split(p.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(e==="list"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,c]}else if(e==="variadic"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,c]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=a.split(p.ArgCompositeSeparator).map((l,c)=>this.stringToNative(`${s[c]}:${l}`)[1]);return[e,o]}else{if(e==="string")return[e,a];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(a)];if(e==="uint64"||e==="biguint")return[e,BigInt(a||0)];if(e==="bool")return[e,a==="true"];if(e==="address")return[e,a];if(e==="token")return[e,a];if(e==="hex")return[e,a];if(e==="codemeta")return[e,a];if(e==="esdt"){let[s,i,o]=a.split(p.ArgCompositeSeparator);return[e,`${s}|${i}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var it=async(n,t,r,e)=>{let a=[],s={};for(let[i,o]of Object.entries(n.results||{})){if(o.startsWith(p.Transform.Prefix))continue;let l=mt(o);if(l!==null&&l!==r){s[i]=null;continue}let[c,...u]=o.split("."),W=(d,C)=>C.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d);if(c==="out"||c.startsWith("out[")){let d=u.length===0?t?.data||t:W(t,u);a.push(d),s[i]=d}else s[i]=o}return{values:a,results:await dt(n,s,r,e)}},dt=async(n,t,r,e)=>{if(!n.results)return t;let a={...t};return a=ft(a,n,r,e),a=await ht(n,a),a},ft=(n,t,r,e)=>{let a={...n},s=P(t,r)?.inputs||[],i=new R;for(let[o,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("input.")){let c=l.split(".")[1],u=s.findIndex(d=>d.as===c||d.name===c),W=u!==-1?e[u]?.value:null;a[o]=W?i.stringToNative(W)[1]:null}return a},ht=async(n,t)=>{if(!n.results)return t;let r={...t},e=Object.entries(n.results).filter(([,a])=>a.startsWith(p.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(p.Transform.Prefix.length)}));for(let{key:a,code:s}of e)try{let i;typeof window>"u"?i=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:i=(await import("./runInVm-5YQ766M3.mjs")).runInVm,r[a]=await i(s,r)}catch(i){v.error(`Transform error for result '${a}':`,i),r[a]=null}return r},mt=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};var gt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Qt=n=>gt.find(t=>t.id===n)||null;var or=n=>`${A.String}:${n}`,pr=n=>`${A.U8}:${n}`,lr=n=>`${A.U16}:${n}`,cr=n=>`${A.U32}:${n}`,ur=n=>`${A.U64}:${n}`,dr=n=>`${A.Biguint}:${n}`,fr=n=>`${A.Boolean}:${n}`,hr=n=>`${A.Address}:${n}`,mr=n=>`${A.Hex}:${n}`;import Wt from"ajv";var st=class{constructor(t){this.pendingBrand={protocol:F("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||g.LatestBrandSchemaUrl,a=await(await fetch(r)).json(),s=new Wt,i=s.compile(a);if(!i(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};import yt from"ajv";var M=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return 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}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(a,s)=>{a&&Object.keys(a).forEach(i=>{i!==i.toUpperCase()&&r.push(`${s} name '${i}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.results,"Result"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(i=>i.type==="contract"),e=t.actions.some(i=>i.type==="query");if(!r&&!e)return[];let a=t.actions.some(i=>i.abi),s=Object.values(t.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return t.results&&!a&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||g.LatestWarpSchemaUrl,a=await(await fetch(r)).json(),s=new yt({strict:!1}),i=s.compile(a);return i(t)?[]:[`Schema validation failed: ${s.errorsText(i.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var G=class{constructor(t){this.config=t;this.pendingWarp={protocol:F("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}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 et(t,r)}ensure(t,r){if(!t)throw new Error(r)}async validate(t){let e=await new M(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);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let a={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(a))}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)}}};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 a=Date.now()+e*1e3;E.cache.set(t,{value:r,expiresAt:a})}forget(t){E.cache.delete(t)}clear(){E.cache.clear()}};E.cache=new Map;var D=E;var X={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},ot={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}`,ChainInfo:(n,t)=>`chain:${n}:${t}`,ChainInfos:n=>`chains:${n}`},j=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new O:t==="memory"?new D:typeof window<"u"&&window.localStorage?new O:new D}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 $=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 R,this.cache=new j(t.cache?.type)}async createExecutable(t,r,e){let a=P(t,r);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForAction(a,e),i=await this.getResolvedInputs(s,a,e),o=this.getModifiedInputs(i),l=o.find(w=>w.input.position==="receiver")?.value,c="address"in a?a.address:null,u=l?.split(":")[1]||c;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let W=u,d=this.getPreparedArgs(a,o),C=o.find(w=>w.input.position==="value")?.value||null,f="value"in a?a.value:null,h=BigInt(C?.split(":")[1]||f||0),I=o.filter(w=>w.input.position==="transfer"&&w.value).map(w=>w.value),y=[...("transfers"in a?a.transfers:[])||[],...I||[]],T=o.find(w=>w.input.position==="data")?.value,U="data"in a?a.data||"":null,Y={warp:t,chain:s,action:r,destination:W,args:d,value:h,transfers:y,data:T||U||null,resolvedInputs:o};return this.cache.set(ot.WarpExecutable(this.config.env,t.meta?.hash||"",r),Y.resolvedInputs,X.OneWeek),Y}async getChainInfoForAction(t,r){if(r){let e=await this.tryGetChainFromInputs(t,r);if(e)return e}return this.getDefaultChainInfo(t)}async getResolvedInputs(t,r,e){let a=r.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(t,o))),i=(o,l)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===p.Source.UserWallet?this.config.user?.wallets?.[t.name]?this.serializer.nativeToString("address",this.config.user.wallets[t.name]):null:s[l]||null};return a.map((o,l)=>{let c=i(o,l);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,a]=r.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(l=>l.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let i=r.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=K(i,+s);return{...r,value:`${r.input.type}:${o}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let i=K(s,+a);return{...r,value:`${r.input.type}:${i}`}}}else return r})}async preprocessInput(t,r){try{let[e,a]=r.split(p.ArgParamsSeparator,2);return x(t.name,this.adapters).executor.preprocessInput(t,r,e,a)}catch{return r}}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:a,value:s})=>{if(!s||!a.position?.startsWith("arg:"))return;let i=Number(a.position.split(":")[1])-1;e.splice(i,0,s)}),e}async tryGetChainFromInputs(t,r){let e=t.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let a=r[e];if(!a)throw new Error("WarpUtils: Chain input not found");let i=new R().stringToNative(a)[1],l=await x(i,this.adapters).registry.getChainInfo(i);if(!l)throw new Error(`WarpUtils: Chain info not found for ${i}`);return l}async getDefaultChainInfo(t){if(!t.chain)return V(this.config);let e=await tt(this.adapters).registry.getChainInfo(t.chain,{ttl:X.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${t.chain}`);return e}};var N=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r){let e=this.applyVars(t,r);return await this.applyGlobals(t,e)}async applyGlobals(t,r){let e={...r};return e.actions=await Promise.all(e.actions.map(async a=>await this.applyActionGlobals(a))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r){if(!r?.vars)return r;let e=JSON.stringify(r),a=(s,i)=>{e=e.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(r.vars).forEach(([s,i])=>{if(typeof i!="string")a(s,i);else if(i.startsWith(`${p.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${p.Vars.Query}:`)[1],l=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);l&&a(s,l)}else if(i.startsWith(`${p.Vars.Env}:`)){let o=i.split(`${p.Vars.Env}:`)[1],l=t.vars?.[o];l&&a(s,l)}else if(i===p.Source.UserWallet&&t.user?.wallets?.[this.adapter.chain]){let o=t.user.wallets[this.adapter.chain];o&&a(s,o)}else a(s,i)}),JSON.parse(e)}async applyRootGlobals(t,r){let e=JSON.stringify(t),a={config:r,chain:V(r)};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=t.chain?await this.adapter.registry.getChainInfo(t.chain):V(this.config);if(!r)throw new Error(`Chain info not found for ${t.chain}`);let e=JSON.stringify(t),a={config:this.config,chain:r};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}};var q=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.factory=new $(t,r),this.handlers=e}async execute(t,r){let[e,a]=rt(t);if(e.type==="collect"){let c=await this.executeCollect(t,a,r);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let s=await this.factory.createExecutable(t,a,r),i=s.chain.name.toLowerCase(),o=this.adapters.find(c=>c.chain.toLowerCase()===i);if(!o)throw new Error(`No adapter registered for chain: ${i}`);return{tx:await o.executor.createTransaction(s),chain:s.chain}}async evaluateResults(t,r,e){let a=this.adapters.find(i=>i.chain.toLowerCase()===r.name.toLowerCase());if(!a)throw new Error(`No adapter registered for chain: ${r.name}`);let s=await a.results.getTransactionExecutionResults(t,e);this.handlers?.onExecuted?.(s)}async executeCollect(t,r,e,a){let s=P(t,r);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=x(i.name,this.adapters),l=await new N(this.config,o).apply(this.config,t),c=await this.factory.getResolvedInputs(i,s,e),u=this.factory.getModifiedInputs(c),W=this.factory.serializer,d=m=>{if(!m.value)return null;let y=W.stringToNative(m.value)[1];return m.input.type==="biguint"?y.toString():m.input.type==="esdt"?{}:y},C=new Headers;C.set("Content-Type","application/json"),C.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([m,y])=>{C.set(m,y)});let f=Object.fromEntries(u.map(m=>[m.input.as||m.input.name,d(m)])),h=s.destination.method||"GET",I=h==="GET"?void 0:JSON.stringify({...f,...a});v.info("Executing collect",{url:s.destination.url,method:h,headers:C,body:I});try{let m=await fetch(s.destination.url,{method:h,headers:C,body:I}),y=await m.json(),{values:T,results:U}=await it(l,y,r,u),Z=at(this.config,l,r,U);return{success:m.ok,warp:l,action:r,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:Z,values:T,results:{...U,_DATA:y},messages:nt(l,U)}}catch(m){return v.error("WarpActionExecutor: Error executing collect",m),{success:!1,warp:l,action:r,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:null,values:[],results:{_DATA:m},messages:{}}}}};var z=class{constructor(t){this.config=t}async search(t,r,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let a=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(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw v.error("WarpIndex: Error searching for warps: ",a),a}}};var J=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!L(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let a=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),i=(await Promise.all(a)).filter(c=>c.match),o=i.length>0,l=i.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:l}}async detect(t,r){let e={match:!1,url:t,warp:null,registryInfo:null,brand:null},a=t.startsWith(p.HttpProtocolPrefix)?L(t):b(t);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,l=null,c=null,u=H(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder.createFromTransactionHash(i,r);let d=await u.registry.getInfoByHash(i,r);l=d.registryInfo,c=d.brand}else if(s==="alias"){let d=await u.registry.getInfoByAlias(i,r);l=d.registryInfo,c=d.brand,d.registryInfo&&(o=await u.builder.createFromTransactionHash(d.registryInfo.hash,r))}let W=o?await new N(this.config,u).apply(this.config,o):null;return W?{match:!0,url:t,warp:W,registryInfo:l,brand:c}:e}catch(s){return v.error("Error detecting warp link",s),e}}};var pt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}setConfig(t){return this.config=t,this}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createBuilder(){return new G(this.config)}createExecutor(t){return new q(this.config,this.adapters,t)}async detectWarp(t,r){return new J(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,a={}){let s=await this.detectWarp(t,a.cache);if(!s.match||!s.warp)throw new Error("Warp not found");let i=this.createExecutor(e),{tx:o,chain:l}=await i.execute(s.warp,r);return{tx:o,chain:l,evaluateResults:async u=>{if(!l||!o||!s.warp)throw new Error("Warp not found");await i.evaluateResults(s.warp,l,u)}}}createInscriptionTransaction(t,r){return x(t,this.adapters).builder.createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return x(t,this.adapters).builder.createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=b(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return H(e.chainPrefix,this.adapters).builder.createFromTransactionHash(t,r)}getExplorer(t){return x(t.name,this.adapters).explorer(t)}getResults(t){return x(t.name,this.adapters).results}async getRegistry(t){let r=x(t,this.adapters).registry;return await r.init(),r}get factory(){return new $(this.config,this.adapters)}get index(){return new z(this.config)}};export{X as CacheTtl,gt as KnownTokens,st as WarpBrandBuilder,G as WarpBuilder,j as WarpCache,ot as WarpCacheKey,pt as WarpClient,g as WarpConfig,p as WarpConstants,q as WarpExecutor,$ as WarpFactory,z as WarpIndex,A as WarpInputTypes,N as WarpInterpolator,k as WarpLinkBuilder,J as WarpLinkDetecter,v as WarpLogger,S as WarpProtocolVersions,R as WarpSerializer,M as WarpValidator,hr as address,nt as applyResultsToMessages,dr as biguint,fr as boolean,dt as evaluateResultsCommon,it as extractCollectResults,L as extractIdentifierInfoFromUrl,Qt as findKnownTokenById,H as findWarpAdapterByPrefix,x as findWarpAdapterForChain,tt as findWarpDefaultAdapter,rt as findWarpExecutableAction,F as getLatestProtocolIdentifier,V as getMainChainInfo,at as getNextInfo,P as getWarpActionByIndex,b as getWarpInfoFromIdentifier,mr as hex,mt as parseResultsOutIndex,Q as replacePlaceholders,K as shiftBigintBy,or as string,et as toPreviewText,wt as toTypedChainInfo,lr as u16,cr as u32,ur as u64,pr as u8};
1
+ import"./chunk-3SAEGOMQ.mjs";var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:a=>a.config.user?.wallets?.[a.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:a=>a.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:a=>a.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:a=>a.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},A={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var B={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},m={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${B.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${B.Brand}.schema.json`,DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:a=>a==="devnet"?"https://devnet-explorer.multiversx.com":a==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:a=>6e3,AddressHrp:"erd",ChainId:a=>a==="devnet"?"D":a==="testnet"?"T":"1",NativeToken:"EGLD"},AvailableActionInputSources:["field","query",l.Source.UserWallet],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 Y=a=>{let t=a.find(r=>r.chain.toLowerCase()===m.MainChain.Name.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${m.MainChain.Name}`);return t},y=(a,t)=>{let r=t.find(e=>e.chain.toLowerCase()===a.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${a}`);return r},$=(a,t)=>{let r=t.find(e=>e.prefix.toLowerCase()===a.toLowerCase());if(!r)throw new Error(`Adapter not found for prefix: ${a}`);return r},O=a=>({name:m.MainChain.Name,displayName:m.MainChain.DisplayName,chainId:m.MainChain.ChainId(a.env),blockTime:m.MainChain.BlockTime(a.env),addressHrp:m.MainChain.AddressHrp,apiUrl:m.MainChain.ApiUrl(a.env),explorerUrl:m.MainChain.ExplorerUrl(a.env),nativeToken:m.MainChain.NativeToken}),k=a=>{if(a==="warp")return`warp:${B.Warp}`;if(a==="brand")return`brand:${B.Brand}`;if(a==="abi")return`abi:${B.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${a}`)},P=(a,t)=>a?.actions[t-1],tt=a=>(a.actions.forEach((t,r)=>{if(t.type!=="link")return{action:t,actionIndex:r}}),{action:P(a,1),actionIndex:1}),bt=a=>({name:a.name.toString(),displayName:a.display_name.toString(),chainId:a.chain_id.toString(),blockTime:a.block_time.toNumber(),addressHrp:a.address_hrp.toString(),apiUrl:a.api_url.toString(),explorerUrl:a.explorer_url.toString(),nativeToken:a.native_token.toString()}),J=(a,t)=>{let r=a.toString(),[e,n=""]=r.split("."),i=Math.abs(t);if(t>0)return BigInt(e+n.padEnd(i,"0"));if(t<0){let s=e+n;if(i>=s.length)return 0n;let o=s.slice(0,-i)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},rt=(a,t=100)=>{if(!a)return"";let r=a.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},K=(a,t)=>a.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),et=(a,t)=>{let r=Object.entries(a.messages||{}).map(([e,n])=>[e,K(n,t)]);return Object.fromEntries(r)};var ct=a=>{let t=l.IdentifierParamSeparator,r=-1,e="";for(let n of t){let i=a.indexOf(n);i!==-1&&(r===-1||i<r)&&(r=i,e=n)}return r!==-1?{separator:e,index:r}:null},nt=a=>{let t=ct(a);if(!t)return[a];let{separator:r,index:e}=t,n=a.substring(0,e),i=a.substring(e+r.length),s=nt(i);return[n,...s]},b=a=>{let t=decodeURIComponent(a).trim(),r=t.split("?")[0],e=nt(r);if(r.length===64&&/^[a-fA-F0-9]+$/.test(r))return{chainPrefix:l.IdentifierChainDefault,type:l.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[n,i,s]=e;if(i===l.IdentifierType.Alias||i===l.IdentifierType.Hash){let o=t.includes("?")?s+t.substring(t.indexOf("?")):s;return{chainPrefix:n,type:i,identifier:o,identifierBase:s}}}if(e.length===2){let[n,i]=e;if(n===l.IdentifierType.Alias||n===l.IdentifierType.Hash){let s=t.includes("?")?i+t.substring(t.indexOf("?")):i;return{chainPrefix:l.IdentifierChainDefault,type:n,identifier:s,identifierBase:i}}}if(e.length===2){let[n,i]=e;if(n!==l.IdentifierType.Alias&&n!==l.IdentifierType.Hash){let s=t.includes("?")?i+t.substring(t.indexOf("?")):i;return{chainPrefix:n,type:l.IdentifierType.Alias,identifier:s,identifierBase:i}}}return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:t,identifierBase:r}},D=a=>{let t=new URL(a),e=t.searchParams.get(l.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let n=decodeURIComponent(e);return b(n)};import ut from"qr-code-styling";var N=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!D(t):!1}build(t,r,e){let n=this.config.clientUrl||m.DefaultClientUrl(this.config.env),i=y(t,this.adapters),s=r===l.IdentifierType.Alias?e:r+l.IdentifierParamSeparatorDefault+e,o=i.prefix+l.IdentifierParamSeparatorDefault+s,p=encodeURIComponent(o);return m.SuperClientUrls.includes(n)?`${n}/${p}`:`${n}?${l.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let r=b(t);if(!r)return null;let e=$(r.chainPrefix,this.adapters);return e?this.build(e.chain,r.type,r.identifierBase):null}generateQrCode(t,r,e,n=512,i="white",s="black",o="#23F7DD"){let p=y(t,this.adapters),c=this.build(p.chain,r,e);return new ut({type:"svg",width:n,height:n,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var dt="https://",at=(a,t,r,e,n)=>{let i=r.actions?.[e]?.next||r.next||null;if(!i)return null;if(i.startsWith(dt))return[{identifier:null,url:i}];let[s,o]=i.split("?");if(!o)return[{identifier:s,url:Q(t,s,a)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let h=K(o,{...r.vars,...n}),W=h?`${s}?${h}`:s;return[{identifier:W,url:Q(t,W,a)}]}let c=p[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),g=u?u[1]:null;if(!g||n[g]===void 0)return[];let f=Array.isArray(n[g])?n[g]:[n[g]];if(f.length===0)return[];let x=p.filter(h=>h.includes(`{{${g}[]`)).map(h=>{let W=h.match(/\[\](\.[^}]+)?}}/),d=W&&W[1]||"";return{placeholder:h,field:d?d.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(h=>{let W=o;for(let{regex:v,field:S}of x){let w=S?ft(h,S):h;if(w==null)return null;W=W.replace(v,w)}if(W.includes("{{")||W.includes("}}"))return null;let d=W?`${s}?${W}`:s;return{identifier:d,url:Q(t,d,a)}}).filter(h=>h!==null)},Q=(a,t,r)=>{let[e,n]=t.split("?"),i=b(e)||{type:"alias",identifier:e,identifierBase:e},s=new N(r,[a]).build(a.chain,i.type,i.identifierBase);if(!n)return s;let o=new URL(s);return new URLSearchParams(n).forEach((p,c)=>o.searchParams.set(c,p)),o.toString().replace(/\/\?/,"?")},ft=(a,t)=>t.split(".").reduce((r,e)=>r?.[e],a);var U=class U{static info(...t){U.isTestEnv||console.info(...t)}static warn(...t){U.isTestEnv||console.warn(...t)}static error(...t){U.isTestEnv||console.error(...t)}};U.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=U;var R=class{nativeToString(t,r){return`${t}:${r?.toString()??""}`}stringToNative(t){let r=t.split(l.ArgParamsSeparator),e=r[0],n=r.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[i,s]=n.split(l.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(e==="optional"){let[i,s]=n.split(l.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(e==="list"){let i=n.split(l.ArgParamsSeparator),s=i.slice(0,-1).join(l.ArgParamsSeparator),o=i[i.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`list:${s}`,c]}else if(e==="variadic"){let i=n.split(l.ArgParamsSeparator),s=i.slice(0,-1).join(l.ArgParamsSeparator),o=i[i.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`variadic:${s}`,c]}else if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=n.split(l.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${i[c]}:${p}`)[1]);return[e,o]}else{if(e==="string")return[e,n];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(n)];if(e==="uint64"||e==="biguint")return[e,BigInt(n||0)];if(e==="bool")return[e,n==="true"];if(e==="address")return[e,n];if(e==="token")return[e,n];if(e==="hex")return[e,n];if(e==="codemeta")return[e,n];if(e==="esdt"){let[i,s,o]=n.split(l.ArgCompositeSeparator);return[e,`${i}|${s}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var it=async(a,t,r,e)=>{let n=[],i={};for(let[s,o]of Object.entries(a.results||{})){if(o.startsWith(l.Transform.Prefix))continue;let p=Wt(o);if(p!==null&&p!==r){i[s]=null;continue}let[c,...u]=o.split("."),g=(f,x)=>x.reduce((E,h)=>E&&E[h]!==void 0?E[h]:null,f);if(c==="out"||c.startsWith("out[")){let f=u.length===0?t?.data||t:g(t,u);n.push(f),i[s]=f}else i[s]=o}return{values:n,results:await ht(a,i,r,e)}},ht=async(a,t,r,e)=>{if(!a.results)return t;let n={...t};return n=gt(n,a,r,e),n=await mt(a,n),n},gt=(a,t,r,e)=>{let n={...a},i=P(t,r)?.inputs||[],s=new R;for(let[o,p]of Object.entries(n))if(typeof p=="string"&&p.startsWith("input.")){let c=p.split(".")[1],u=i.findIndex(f=>f.as===c||f.name===c),g=u!==-1?e[u]?.value:null;n[o]=g?s.stringToNative(g)[1]:null}return n},mt=async(a,t)=>{if(!a.results)return t;let r={...t},e=Object.entries(a.results).filter(([,n])=>n.startsWith(l.Transform.Prefix)).map(([n,i])=>({key:n,code:i.substring(l.Transform.Prefix.length)}));for(let{key:n,code:i}of e)try{let s;typeof window>"u"?s=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:s=(await import("./runInVm-5YQ766M3.mjs")).runInVm,r[n]=await s(i,r)}catch(s){C.error(`Transform error for result '${n}':`,s),r[n]=null}return r},Wt=a=>{if(a==="out")return 1;let t=a.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(a.startsWith("out.")||a.startsWith("event."),null)};var yt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Zt=a=>yt.find(t=>t.id===a)||null;var cr=a=>`${A.String}:${a}`,ur=a=>`${A.U8}:${a}`,dr=a=>`${A.U16}:${a}`,fr=a=>`${A.U32}:${a}`,hr=a=>`${A.U64}:${a}`,gr=a=>`${A.Biguint}:${a}`,mr=a=>`${A.Boolean}:${a}`,Wr=a=>`${A.Address}:${a}`,yr=a=>`${A.Hex}:${a}`;import xt from"ajv";var st=class{constructor(t){this.pendingBrand={protocol:k("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.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||m.LatestBrandSchemaUrl,n=await(await fetch(r)).json(),i=new xt,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import vt from"ajv";var M=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return 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}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(n,i)=>{n&&Object.keys(n).forEach(s=>{s!==s.toUpperCase()&&r.push(`${i} name '${s}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.results,"Result"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(s=>s.type==="contract"),e=t.actions.some(s=>s.type==="query");if(!r&&!e)return[];let n=t.actions.some(s=>s.abi),i=Object.values(t.results||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.results&&!n&&i?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||m.LatestWarpSchemaUrl,n=await(await fetch(r)).json(),i=new vt({strict:!1}),s=i.compile(n);return s(t)?[]:[`Schema validation failed: ${i.errorsText(s.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var ot=class{constructor(t){this.config=t;this.pendingWarp={protocol:k("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}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 rt(t,r)}ensure(t,r){if(!t)throw new Error(r)}async validate(t){let e=await new M(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
+ `))}};var F=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);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let n={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}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)}}};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 n=Date.now()+e*1e3;T.cache.set(t,{value:r,expiresAt:n})}forget(t){T.cache.delete(t)}clear(){T.cache.clear()}};T.cache=new Map;var H=T;var _={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},pt={Warp:(a,t)=>`warp:${a}:${t}`,WarpAbi:(a,t)=>`warp-abi:${a}:${t}`,WarpExecutable:(a,t,r)=>`warp-exec:${a}:${t}:${r}`,RegistryInfo:(a,t)=>`registry-info:${a}:${t}`,Brand:(a,t)=>`brand:${a}:${t}`,ChainInfo:(a,t)=>`chain:${a}:${t}`,ChainInfos:a=>`chains:${a}`},G=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new F:t==="memory"?new H:typeof window<"u"&&window.localStorage?new F:new H}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 V=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 R,this.cache=new G(t.cache?.type)}async createExecutable(t,r,e){let n=P(t,r);if(!n)throw new Error("WarpFactory: Action not found");let i=await this.getChainInfoForAction(n,e),s=await this.getResolvedInputs(i,n,e),o=this.getModifiedInputs(s),p=o.find(I=>I.input.position==="receiver")?.value,c="address"in n?n.address:null,u=p?.split(":")[1]||c;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let g=u,f=this.getPreparedArgs(n,o),x=o.find(I=>I.input.position==="value")?.value||null,E="value"in n?n.value:null,h=BigInt(x?.split(":")[1]||E||0),W=o.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),v=[...("transfers"in n?n.transfers:[])||[],...W||[]],S=o.find(I=>I.input.position==="data")?.value,w="data"in n?n.data||"":null,Z={warp:t,chain:i,action:r,destination:g,args:f,value:h,transfers:v,data:S||w||null,resolvedInputs:o};return this.cache.set(pt.WarpExecutable(this.config.env,t.meta?.hash||"",r),Z.resolvedInputs,_.OneWeek),Z}async getChainInfoForAction(t,r){if(r){let e=await this.tryGetChainFromInputs(t,r);if(e)return e}return this.getDefaultChainInfo(t)}async getResolvedInputs(t,r,e){let n=r.inputs||[],i=await Promise.all(e.map(o=>this.preprocessInput(t,o))),s=(o,p)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===l.Source.UserWallet?this.config.user?.wallets?.[t.name]?this.serializer.nativeToString("address",this.config.user.wallets[t.name]):null:i[p]||null};return n.map((o,p)=>{let c=s(o,p);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,n]=r.input.modifier.split(":");if(isNaN(Number(n))){let i=Number(t.find(p=>p.input.name===n)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=J(s,+i);return{...r,value:`${r.input.type}:${o}`}}else{let i=r.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=J(i,+n);return{...r,value:`${r.input.type}:${s}`}}}else return r})}async preprocessInput(t,r){try{let[e,n]=r.split(l.ArgParamsSeparator,2);return y(t.name,this.adapters).executor.preprocessInput(t,r,e,n)}catch{return r}}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:n,value:i})=>{if(!i||!n.position?.startsWith("arg:"))return;let s=Number(n.position.split(":")[1])-1;e.splice(s,0,i)}),e}async tryGetChainFromInputs(t,r){let e=t.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let n=r[e];if(!n)throw new Error("WarpUtils: Chain input not found");let s=new R().stringToNative(n)[1],p=await y(s,this.adapters).registry.getChainInfo(s);if(!p)throw new Error(`WarpUtils: Chain info not found for ${s}`);return p}async getDefaultChainInfo(t){if(!t.chain)return O(this.config);let e=await Y(this.adapters).registry.getChainInfo(t.chain,{ttl:_.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${t.chain}`);return e}};var L=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r){let e=this.applyVars(t,r);return await this.applyGlobals(t,e)}async applyGlobals(t,r){let e={...r};return e.actions=await Promise.all(e.actions.map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r){if(!r?.vars)return r;let e=JSON.stringify(r),n=(i,s)=>{e=e.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(r.vars).forEach(([i,s])=>{if(typeof s!="string")n(i,s);else if(s.startsWith(`${l.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${l.Vars.Query}:`)[1],p=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);p&&n(i,p)}else if(s.startsWith(`${l.Vars.Env}:`)){let o=s.split(`${l.Vars.Env}:`)[1],p=t.vars?.[o];p&&n(i,p)}else if(s===l.Source.UserWallet&&t.user?.wallets?.[this.adapter.chain]){let o=t.user.wallets[this.adapter.chain];o&&n(i,o)}else n(i,s)}),JSON.parse(e)}async applyRootGlobals(t,r){let e=JSON.stringify(t),n={config:r,chain:O(r)};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=t.chain?await this.adapter.registry.getChainInfo(t.chain):O(this.config);if(!r)throw new Error(`Chain info not found for ${t.chain}`);let e=JSON.stringify(t),n={config:this.config,chain:r};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(e)}};var j=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.factory=new V(t,r),this.handlers=e}async execute(t,r){let{action:e,actionIndex:n}=tt(t);if(e.type==="collect"){let c=await this.executeCollect(t,n,r);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let i=await this.factory.createExecutable(t,n,r),s=i.chain.name.toLowerCase(),o=this.adapters.find(c=>c.chain.toLowerCase()===s);if(!o)throw new Error(`No adapter registered for chain: ${s}`);return{tx:await o.executor.createTransaction(i),chain:i.chain}}async evaluateResults(t,r,e){let n=this.adapters.find(s=>s.chain.toLowerCase()===r.name.toLowerCase());if(!n)throw new Error(`No adapter registered for chain: ${r.name}`);let i=await n.results.getTransactionExecutionResults(t,e);this.handlers?.onExecuted?.(i)}async executeCollect(t,r,e,n){let i=P(t,r);if(!i)throw new Error("WarpActionExecutor: Action not found");let s=await this.factory.getChainInfoForAction(i),o=y(s.name,this.adapters),p=await new L(this.config,o).apply(this.config,t),c=await this.factory.getResolvedInputs(s,i,e),u=this.factory.getModifiedInputs(c),g=this.factory.serializer,f=d=>{if(!d.value)return null;let v=g.stringToNative(d.value)[1];return d.input.type==="biguint"?v.toString():d.input.type==="esdt"?{}:v},x=new Headers;x.set("Content-Type","application/json"),x.set("Accept","application/json"),Object.entries(i.destination.headers||{}).forEach(([d,v])=>{x.set(d,v)});let E=Object.fromEntries(u.map(d=>[d.input.as||d.input.name,f(d)])),h=i.destination.method||"GET",W=h==="GET"?void 0:JSON.stringify({...E,...n});C.info("Executing collect",{url:i.destination.url,method:h,headers:x,body:W});try{let d=await fetch(i.destination.url,{method:h,headers:x,body:W}),v=await d.json(),{values:S,results:w}=await it(p,v,r,u),X=at(this.config,o,p,r,w);return{success:d.ok,warp:p,action:r,user:this.config.user?.wallets?.[s.name]||null,txHash:null,next:X,values:S,results:{...w,_DATA:v},messages:et(p,w)}}catch(d){return C.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:p,action:r,user:this.config.user?.wallets?.[s.name]||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};var q=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 n=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(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw C.error("WarpIndex: Error searching for warps: ",n),n}}};var z=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!D(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),s=(await Promise.all(n)).filter(c=>c.match),o=s.length>0,p=s.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(t,r){let e={match:!1,url:t,warp:null,registryInfo:null,brand:null},n=t.startsWith(l.HttpProtocolPrefix)?D(t):b(t);if(!n)return e;try{let{type:i,identifierBase:s}=n,o=null,p=null,c=null,u=$(n.chainPrefix,this.adapters);if(i==="hash"){o=await u.builder().createFromTransactionHash(s,r);let f=await u.registry.getInfoByHash(s,r);p=f.registryInfo,c=f.brand}else if(i==="alias"){let f=await u.registry.getInfoByAlias(s,r);p=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,r))}let g=o?await new L(this.config,u).apply(this.config,o):null;return g?{match:!0,url:t,warp:g,registryInfo:p,brand:c}:e}catch(i){return C.error("Error detecting warp link",i),e}}};var lt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}setConfig(t){return this.config=t,this}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new j(this.config,this.adapters,t)}async detectWarp(t,r){return new z(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,n={}){let i=await this.detectWarp(t,n.cache);if(!i.match||!i.warp)throw new Error("Warp not found");let s=this.createExecutor(e),{tx:o,chain:p}=await s.execute(i.warp,r);return{tx:o,chain:p,evaluateResults:async u=>{if(!p||!o||!i.warp)throw new Error("Warp not found");await s.evaluateResults(i.warp,p,u)}}}createInscriptionTransaction(t,r){return y(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return y(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=b(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return $(e.chainPrefix,this.adapters).builder().createFromTransactionHash(t,r)}getExplorer(t){return y(t.name,this.adapters).explorer(t)}getResults(t){return y(t.name,this.adapters).results}async getRegistry(t){let r=y(t,this.adapters).registry;return await r.init(),r}get factory(){return new V(this.config,this.adapters)}get index(){return new q(this.config)}get linkBuilder(){return new N(this.config,this.adapters)}createBuilder(t){return y(t,this.adapters).builder()}createAbiBuilder(t){return y(t,this.adapters).abiBuilder()}createBrandBuilder(t){return y(t,this.adapters).brandBuilder()}};export{_ as CacheTtl,yt as KnownTokens,st as WarpBrandBuilder,ot as WarpBuilder,G as WarpCache,pt as WarpCacheKey,lt as WarpClient,m as WarpConfig,l as WarpConstants,j as WarpExecutor,V as WarpFactory,q as WarpIndex,A as WarpInputTypes,L as WarpInterpolator,N as WarpLinkBuilder,z as WarpLinkDetecter,C as WarpLogger,B as WarpProtocolVersions,R as WarpSerializer,M as WarpValidator,Wr as address,et as applyResultsToMessages,gr as biguint,mr as boolean,ht as evaluateResultsCommon,it as extractCollectResults,D as extractIdentifierInfoFromUrl,Zt as findKnownTokenById,$ as findWarpAdapterByPrefix,y as findWarpAdapterForChain,Y as findWarpDefaultAdapter,tt as findWarpExecutableAction,k as getLatestProtocolIdentifier,O as getMainChainInfo,at as getNextInfo,P as getWarpActionByIndex,b as getWarpInfoFromIdentifier,yr as hex,Wt as parseResultsOutIndex,K as replacePlaceholders,J as shiftBigintBy,cr as string,rt as toPreviewText,bt as toTypedChainInfo,dr as u16,fr as u32,hr as u64,ur as u8};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "3.0.0-alpha.55",
3
+ "version": "3.0.0-alpha.56",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",