@vleap/warps 3.0.0-alpha.44 → 3.0.0-alpha.46
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 +42 -32
- package/dist/index.d.ts +42 -32
- package/dist/index.js +4 -4
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -230,11 +230,7 @@ type WarpExecutionNextInfo = {
|
|
|
230
230
|
type WarpExecutionResults = Record<WarpResultName, any | null>;
|
|
231
231
|
type WarpExecutionMessages = Record<WarpMessageName, string | null>;
|
|
232
232
|
|
|
233
|
-
type WarpClientConfig =
|
|
234
|
-
repository: Adapter;
|
|
235
|
-
adapters: Adapter[];
|
|
236
|
-
};
|
|
237
|
-
type WarpInitConfig = {
|
|
233
|
+
type WarpClientConfig = {
|
|
238
234
|
env: WarpChainEnv;
|
|
239
235
|
clientUrl?: string;
|
|
240
236
|
currentUrl?: string;
|
|
@@ -264,11 +260,13 @@ type WarpCacheConfig = {
|
|
|
264
260
|
};
|
|
265
261
|
type Adapter = {
|
|
266
262
|
chain: WarpChain;
|
|
263
|
+
prefix: string;
|
|
267
264
|
builder: AdapterWarpBuilder;
|
|
268
265
|
executor: AdapterWarpExecutor;
|
|
269
266
|
results: AdapterWarpResults;
|
|
270
267
|
serializer: AdapterWarpSerializer;
|
|
271
268
|
registry: AdapterWarpRegistry;
|
|
269
|
+
explorer: (chainInfo: WarpChainInfo) => AdapterWarpExplorer;
|
|
272
270
|
};
|
|
273
271
|
type WarpAdapterGenericTransaction = any;
|
|
274
272
|
type WarpAdapterGenericRemoteTransaction = any;
|
|
@@ -318,9 +316,13 @@ interface AdapterWarpRegistry {
|
|
|
318
316
|
removeChain(chain: WarpChain): Promise<WarpAdapterGenericTransaction>;
|
|
319
317
|
fetchBrand(hash: string, cache?: WarpCacheConfig): Promise<WarpBrand | null>;
|
|
320
318
|
}
|
|
319
|
+
interface AdapterWarpExplorer {
|
|
320
|
+
getAccountUrl(address: string): string;
|
|
321
|
+
getTransactionUrl(hash: string): string;
|
|
322
|
+
}
|
|
321
323
|
|
|
322
324
|
type InterpolationBag = {
|
|
323
|
-
config:
|
|
325
|
+
config: WarpClientConfig;
|
|
324
326
|
chain: WarpChainInfo;
|
|
325
327
|
};
|
|
326
328
|
|
|
@@ -371,6 +373,7 @@ declare const WarpConstants: {
|
|
|
371
373
|
HttpProtocolPrefix: string;
|
|
372
374
|
IdentifierParamName: string;
|
|
373
375
|
IdentifierParamSeparator: string;
|
|
376
|
+
IdentifierChainDefault: string;
|
|
374
377
|
IdentifierType: {
|
|
375
378
|
Alias: WarpIdType;
|
|
376
379
|
Hash: WarpIdType;
|
|
@@ -423,8 +426,10 @@ declare const WarpInputTypes: {
|
|
|
423
426
|
Hex: string;
|
|
424
427
|
};
|
|
425
428
|
|
|
426
|
-
declare const
|
|
427
|
-
declare const
|
|
429
|
+
declare const findWarpDefaultAdapter: (adapters: Adapter[]) => Adapter;
|
|
430
|
+
declare const findWarpAdapterForChain: (chain: WarpChain, adapters: Adapter[]) => Adapter;
|
|
431
|
+
declare const findWarpAdapterByPrefix: (prefix: string, adapters: Adapter[]) => Adapter;
|
|
432
|
+
declare const getMainChainInfo: (config: WarpClientConfig) => WarpChainInfo;
|
|
428
433
|
declare const getLatestProtocolIdentifier: (name: ProtocolName) => string;
|
|
429
434
|
declare const getWarpActionByIndex: (warp: Warp, index: number) => WarpAction;
|
|
430
435
|
declare const findWarpExecutableAction: (warp: Warp) => [WarpAction, WarpActionIndex];
|
|
@@ -435,17 +440,19 @@ declare const replacePlaceholders: (message: string, bag: Record<string, any>) =
|
|
|
435
440
|
declare const applyResultsToMessages: (warp: Warp, results: Record<string, any>) => Record<string, string>;
|
|
436
441
|
|
|
437
442
|
declare const getWarpInfoFromIdentifier: (prefixedIdentifier: string) => {
|
|
443
|
+
chainPrefix: string;
|
|
438
444
|
type: WarpIdType;
|
|
439
445
|
identifier: string;
|
|
440
446
|
identifierBase: string;
|
|
441
447
|
} | null;
|
|
442
448
|
declare const extractIdentifierInfoFromUrl: (url: string) => {
|
|
449
|
+
chainPrefix: string;
|
|
443
450
|
type: WarpIdType;
|
|
444
451
|
identifier: string;
|
|
445
452
|
identifierBase: string;
|
|
446
453
|
} | null;
|
|
447
454
|
|
|
448
|
-
declare const getNextInfo: (config:
|
|
455
|
+
declare const getNextInfo: (config: WarpClientConfig, warp: Warp, actionIndex: number, results: WarpExecutionResults) => WarpExecutionNextInfo | null;
|
|
449
456
|
|
|
450
457
|
declare const extractCollectResults: (warp: Warp, response: any, actionIndex: number, inputs: ResolvedInput[]) => Promise<{
|
|
451
458
|
values: any[];
|
|
@@ -479,7 +486,7 @@ declare const hex: (value: string) => string;
|
|
|
479
486
|
declare class WarpBrandBuilder {
|
|
480
487
|
private config;
|
|
481
488
|
private pendingBrand;
|
|
482
|
-
constructor(config:
|
|
489
|
+
constructor(config: WarpClientConfig);
|
|
483
490
|
createFromRaw(encoded: string, validateSchema?: boolean): Promise<WarpBrand>;
|
|
484
491
|
setName(name: string): WarpBrandBuilder;
|
|
485
492
|
setDescription(description: string): WarpBrandBuilder;
|
|
@@ -495,7 +502,7 @@ declare class WarpBrandBuilder {
|
|
|
495
502
|
declare class WarpBuilder {
|
|
496
503
|
private config;
|
|
497
504
|
private pendingWarp;
|
|
498
|
-
constructor(config:
|
|
505
|
+
constructor(config: WarpClientConfig);
|
|
499
506
|
createFromRaw(encoded: string, validate?: boolean): Promise<Warp>;
|
|
500
507
|
setName(name: string): WarpBuilder;
|
|
501
508
|
setTitle(title: string): WarpBuilder;
|
|
@@ -541,10 +548,10 @@ type ExecutionHandlers = {
|
|
|
541
548
|
};
|
|
542
549
|
declare class WarpExecutor {
|
|
543
550
|
private config;
|
|
551
|
+
private adapters;
|
|
544
552
|
private handlers?;
|
|
545
553
|
private factory;
|
|
546
|
-
|
|
547
|
-
constructor(config: WarpClientConfig, handlers?: ExecutionHandlers | undefined);
|
|
554
|
+
constructor(config: WarpClientConfig, adapters: Adapter[], handlers?: ExecutionHandlers | undefined);
|
|
548
555
|
execute(warp: Warp, inputs: string[]): Promise<[WarpAdapterGenericTransaction | null, WarpChainInfo | null]>;
|
|
549
556
|
evaluateResults(warp: Warp, chain: WarpChainInfo, tx: WarpAdapterGenericRemoteTransaction): Promise<void>;
|
|
550
557
|
private executeCollect;
|
|
@@ -552,10 +559,11 @@ declare class WarpExecutor {
|
|
|
552
559
|
|
|
553
560
|
declare class WarpFactory {
|
|
554
561
|
private config;
|
|
562
|
+
private adapters;
|
|
555
563
|
private url;
|
|
556
564
|
private serializer;
|
|
557
565
|
private cache;
|
|
558
|
-
constructor(config: WarpClientConfig);
|
|
566
|
+
constructor(config: WarpClientConfig, adapters: Adapter[]);
|
|
559
567
|
createExecutable(warp: Warp, actionIndex: number, inputs: string[]): Promise<WarpExecutable>;
|
|
560
568
|
getChainInfoForAction(action: WarpAction, inputs?: string[]): Promise<WarpChainInfo>;
|
|
561
569
|
getResolvedInputs(chain: WarpChainInfo, action: WarpAction, inputArgs: string[]): Promise<ResolvedInput[]>;
|
|
@@ -582,9 +590,8 @@ type DetectionResultFromHtml = {
|
|
|
582
590
|
};
|
|
583
591
|
declare class WarpLinkDetecter {
|
|
584
592
|
private config;
|
|
585
|
-
private
|
|
586
|
-
|
|
587
|
-
constructor(config: WarpInitConfig, repository: Adapter);
|
|
593
|
+
private adapters;
|
|
594
|
+
constructor(config: WarpClientConfig, adapters: Adapter[]);
|
|
588
595
|
isValid(url: string): boolean;
|
|
589
596
|
detectFromHtml(content: string): Promise<DetectionResultFromHtml>;
|
|
590
597
|
detect(url: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
|
|
@@ -592,40 +599,43 @@ declare class WarpLinkDetecter {
|
|
|
592
599
|
|
|
593
600
|
declare class WarpClient {
|
|
594
601
|
private config;
|
|
595
|
-
|
|
602
|
+
private adapters;
|
|
603
|
+
constructor(config: WarpClientConfig, adapters: Adapter[]);
|
|
596
604
|
getConfig(): WarpClientConfig;
|
|
597
605
|
setConfig(config: WarpClientConfig): WarpClient;
|
|
606
|
+
addAdapter(adapter: Adapter): WarpClient;
|
|
598
607
|
createBuilder(): WarpBuilder;
|
|
599
608
|
createExecutor(handlers?: ExecutionHandlers): WarpExecutor;
|
|
600
609
|
detectWarp(url: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
|
|
601
|
-
createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
|
|
602
|
-
createFromTransaction(tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
|
|
603
|
-
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
610
|
+
createInscriptionTransaction(chain: WarpChain, warp: Warp): WarpAdapterGenericTransaction;
|
|
611
|
+
createFromTransaction(chain: WarpChain, tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
|
|
612
|
+
createFromTransactionHash(chain: WarpChain, hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
613
|
+
getExplorer(chain: WarpChainInfo): AdapterWarpExplorer;
|
|
614
|
+
getResults(chain: WarpChainInfo): AdapterWarpResults;
|
|
615
|
+
getRegistry(chain: WarpChain): AdapterWarpRegistry;
|
|
604
616
|
get factory(): WarpFactory;
|
|
605
|
-
get results(): AdapterWarpResults;
|
|
606
|
-
get registry(): AdapterWarpRegistry;
|
|
607
617
|
}
|
|
608
618
|
|
|
609
619
|
declare class WarpIndex {
|
|
610
620
|
private config;
|
|
611
|
-
constructor(config:
|
|
621
|
+
constructor(config: WarpClientConfig);
|
|
612
622
|
search(query: string, params?: Record<string, any>, headers?: Record<string, string>): Promise<WarpSearchHit[]>;
|
|
613
623
|
}
|
|
614
624
|
|
|
615
625
|
declare class WarpInterpolator {
|
|
616
626
|
private config;
|
|
617
|
-
private
|
|
618
|
-
constructor(config:
|
|
619
|
-
apply(config:
|
|
620
|
-
applyGlobals(config:
|
|
621
|
-
applyVars(config:
|
|
627
|
+
private adapter;
|
|
628
|
+
constructor(config: WarpClientConfig, adapter: Adapter);
|
|
629
|
+
apply(config: WarpClientConfig, warp: Warp): Promise<Warp>;
|
|
630
|
+
applyGlobals(config: WarpClientConfig, warp: Warp): Promise<Warp>;
|
|
631
|
+
applyVars(config: WarpClientConfig, warp: Warp): Warp;
|
|
622
632
|
private applyRootGlobals;
|
|
623
633
|
private applyActionGlobals;
|
|
624
634
|
}
|
|
625
635
|
|
|
626
636
|
declare class WarpLinkBuilder {
|
|
627
637
|
private config;
|
|
628
|
-
constructor(config:
|
|
638
|
+
constructor(config: WarpClientConfig);
|
|
629
639
|
isValid(url: string): boolean;
|
|
630
640
|
build(type: WarpIdType, id: string): string;
|
|
631
641
|
buildFromPrefixedIdentifier(identifier: string): string;
|
|
@@ -651,7 +661,7 @@ type ValidationResult = {
|
|
|
651
661
|
type ValidationError = string;
|
|
652
662
|
declare class WarpValidator {
|
|
653
663
|
private config;
|
|
654
|
-
constructor(config:
|
|
664
|
+
constructor(config: WarpClientConfig);
|
|
655
665
|
validate(warp: Warp): Promise<ValidationResult>;
|
|
656
666
|
private validateMaxOneValuePosition;
|
|
657
667
|
private validateVariableNamesAndResultNamesUppercase;
|
|
@@ -659,4 +669,4 @@ declare class WarpValidator {
|
|
|
659
669
|
private validateSchema;
|
|
660
670
|
}
|
|
661
671
|
|
|
662
|
-
export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, 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,
|
|
672
|
+
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, 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
|
@@ -230,11 +230,7 @@ type WarpExecutionNextInfo = {
|
|
|
230
230
|
type WarpExecutionResults = Record<WarpResultName, any | null>;
|
|
231
231
|
type WarpExecutionMessages = Record<WarpMessageName, string | null>;
|
|
232
232
|
|
|
233
|
-
type WarpClientConfig =
|
|
234
|
-
repository: Adapter;
|
|
235
|
-
adapters: Adapter[];
|
|
236
|
-
};
|
|
237
|
-
type WarpInitConfig = {
|
|
233
|
+
type WarpClientConfig = {
|
|
238
234
|
env: WarpChainEnv;
|
|
239
235
|
clientUrl?: string;
|
|
240
236
|
currentUrl?: string;
|
|
@@ -264,11 +260,13 @@ type WarpCacheConfig = {
|
|
|
264
260
|
};
|
|
265
261
|
type Adapter = {
|
|
266
262
|
chain: WarpChain;
|
|
263
|
+
prefix: string;
|
|
267
264
|
builder: AdapterWarpBuilder;
|
|
268
265
|
executor: AdapterWarpExecutor;
|
|
269
266
|
results: AdapterWarpResults;
|
|
270
267
|
serializer: AdapterWarpSerializer;
|
|
271
268
|
registry: AdapterWarpRegistry;
|
|
269
|
+
explorer: (chainInfo: WarpChainInfo) => AdapterWarpExplorer;
|
|
272
270
|
};
|
|
273
271
|
type WarpAdapterGenericTransaction = any;
|
|
274
272
|
type WarpAdapterGenericRemoteTransaction = any;
|
|
@@ -318,9 +316,13 @@ interface AdapterWarpRegistry {
|
|
|
318
316
|
removeChain(chain: WarpChain): Promise<WarpAdapterGenericTransaction>;
|
|
319
317
|
fetchBrand(hash: string, cache?: WarpCacheConfig): Promise<WarpBrand | null>;
|
|
320
318
|
}
|
|
319
|
+
interface AdapterWarpExplorer {
|
|
320
|
+
getAccountUrl(address: string): string;
|
|
321
|
+
getTransactionUrl(hash: string): string;
|
|
322
|
+
}
|
|
321
323
|
|
|
322
324
|
type InterpolationBag = {
|
|
323
|
-
config:
|
|
325
|
+
config: WarpClientConfig;
|
|
324
326
|
chain: WarpChainInfo;
|
|
325
327
|
};
|
|
326
328
|
|
|
@@ -371,6 +373,7 @@ declare const WarpConstants: {
|
|
|
371
373
|
HttpProtocolPrefix: string;
|
|
372
374
|
IdentifierParamName: string;
|
|
373
375
|
IdentifierParamSeparator: string;
|
|
376
|
+
IdentifierChainDefault: string;
|
|
374
377
|
IdentifierType: {
|
|
375
378
|
Alias: WarpIdType;
|
|
376
379
|
Hash: WarpIdType;
|
|
@@ -423,8 +426,10 @@ declare const WarpInputTypes: {
|
|
|
423
426
|
Hex: string;
|
|
424
427
|
};
|
|
425
428
|
|
|
426
|
-
declare const
|
|
427
|
-
declare const
|
|
429
|
+
declare const findWarpDefaultAdapter: (adapters: Adapter[]) => Adapter;
|
|
430
|
+
declare const findWarpAdapterForChain: (chain: WarpChain, adapters: Adapter[]) => Adapter;
|
|
431
|
+
declare const findWarpAdapterByPrefix: (prefix: string, adapters: Adapter[]) => Adapter;
|
|
432
|
+
declare const getMainChainInfo: (config: WarpClientConfig) => WarpChainInfo;
|
|
428
433
|
declare const getLatestProtocolIdentifier: (name: ProtocolName) => string;
|
|
429
434
|
declare const getWarpActionByIndex: (warp: Warp, index: number) => WarpAction;
|
|
430
435
|
declare const findWarpExecutableAction: (warp: Warp) => [WarpAction, WarpActionIndex];
|
|
@@ -435,17 +440,19 @@ declare const replacePlaceholders: (message: string, bag: Record<string, any>) =
|
|
|
435
440
|
declare const applyResultsToMessages: (warp: Warp, results: Record<string, any>) => Record<string, string>;
|
|
436
441
|
|
|
437
442
|
declare const getWarpInfoFromIdentifier: (prefixedIdentifier: string) => {
|
|
443
|
+
chainPrefix: string;
|
|
438
444
|
type: WarpIdType;
|
|
439
445
|
identifier: string;
|
|
440
446
|
identifierBase: string;
|
|
441
447
|
} | null;
|
|
442
448
|
declare const extractIdentifierInfoFromUrl: (url: string) => {
|
|
449
|
+
chainPrefix: string;
|
|
443
450
|
type: WarpIdType;
|
|
444
451
|
identifier: string;
|
|
445
452
|
identifierBase: string;
|
|
446
453
|
} | null;
|
|
447
454
|
|
|
448
|
-
declare const getNextInfo: (config:
|
|
455
|
+
declare const getNextInfo: (config: WarpClientConfig, warp: Warp, actionIndex: number, results: WarpExecutionResults) => WarpExecutionNextInfo | null;
|
|
449
456
|
|
|
450
457
|
declare const extractCollectResults: (warp: Warp, response: any, actionIndex: number, inputs: ResolvedInput[]) => Promise<{
|
|
451
458
|
values: any[];
|
|
@@ -479,7 +486,7 @@ declare const hex: (value: string) => string;
|
|
|
479
486
|
declare class WarpBrandBuilder {
|
|
480
487
|
private config;
|
|
481
488
|
private pendingBrand;
|
|
482
|
-
constructor(config:
|
|
489
|
+
constructor(config: WarpClientConfig);
|
|
483
490
|
createFromRaw(encoded: string, validateSchema?: boolean): Promise<WarpBrand>;
|
|
484
491
|
setName(name: string): WarpBrandBuilder;
|
|
485
492
|
setDescription(description: string): WarpBrandBuilder;
|
|
@@ -495,7 +502,7 @@ declare class WarpBrandBuilder {
|
|
|
495
502
|
declare class WarpBuilder {
|
|
496
503
|
private config;
|
|
497
504
|
private pendingWarp;
|
|
498
|
-
constructor(config:
|
|
505
|
+
constructor(config: WarpClientConfig);
|
|
499
506
|
createFromRaw(encoded: string, validate?: boolean): Promise<Warp>;
|
|
500
507
|
setName(name: string): WarpBuilder;
|
|
501
508
|
setTitle(title: string): WarpBuilder;
|
|
@@ -541,10 +548,10 @@ type ExecutionHandlers = {
|
|
|
541
548
|
};
|
|
542
549
|
declare class WarpExecutor {
|
|
543
550
|
private config;
|
|
551
|
+
private adapters;
|
|
544
552
|
private handlers?;
|
|
545
553
|
private factory;
|
|
546
|
-
|
|
547
|
-
constructor(config: WarpClientConfig, handlers?: ExecutionHandlers | undefined);
|
|
554
|
+
constructor(config: WarpClientConfig, adapters: Adapter[], handlers?: ExecutionHandlers | undefined);
|
|
548
555
|
execute(warp: Warp, inputs: string[]): Promise<[WarpAdapterGenericTransaction | null, WarpChainInfo | null]>;
|
|
549
556
|
evaluateResults(warp: Warp, chain: WarpChainInfo, tx: WarpAdapterGenericRemoteTransaction): Promise<void>;
|
|
550
557
|
private executeCollect;
|
|
@@ -552,10 +559,11 @@ declare class WarpExecutor {
|
|
|
552
559
|
|
|
553
560
|
declare class WarpFactory {
|
|
554
561
|
private config;
|
|
562
|
+
private adapters;
|
|
555
563
|
private url;
|
|
556
564
|
private serializer;
|
|
557
565
|
private cache;
|
|
558
|
-
constructor(config: WarpClientConfig);
|
|
566
|
+
constructor(config: WarpClientConfig, adapters: Adapter[]);
|
|
559
567
|
createExecutable(warp: Warp, actionIndex: number, inputs: string[]): Promise<WarpExecutable>;
|
|
560
568
|
getChainInfoForAction(action: WarpAction, inputs?: string[]): Promise<WarpChainInfo>;
|
|
561
569
|
getResolvedInputs(chain: WarpChainInfo, action: WarpAction, inputArgs: string[]): Promise<ResolvedInput[]>;
|
|
@@ -582,9 +590,8 @@ type DetectionResultFromHtml = {
|
|
|
582
590
|
};
|
|
583
591
|
declare class WarpLinkDetecter {
|
|
584
592
|
private config;
|
|
585
|
-
private
|
|
586
|
-
|
|
587
|
-
constructor(config: WarpInitConfig, repository: Adapter);
|
|
593
|
+
private adapters;
|
|
594
|
+
constructor(config: WarpClientConfig, adapters: Adapter[]);
|
|
588
595
|
isValid(url: string): boolean;
|
|
589
596
|
detectFromHtml(content: string): Promise<DetectionResultFromHtml>;
|
|
590
597
|
detect(url: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
|
|
@@ -592,40 +599,43 @@ declare class WarpLinkDetecter {
|
|
|
592
599
|
|
|
593
600
|
declare class WarpClient {
|
|
594
601
|
private config;
|
|
595
|
-
|
|
602
|
+
private adapters;
|
|
603
|
+
constructor(config: WarpClientConfig, adapters: Adapter[]);
|
|
596
604
|
getConfig(): WarpClientConfig;
|
|
597
605
|
setConfig(config: WarpClientConfig): WarpClient;
|
|
606
|
+
addAdapter(adapter: Adapter): WarpClient;
|
|
598
607
|
createBuilder(): WarpBuilder;
|
|
599
608
|
createExecutor(handlers?: ExecutionHandlers): WarpExecutor;
|
|
600
609
|
detectWarp(url: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
|
|
601
|
-
createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
|
|
602
|
-
createFromTransaction(tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
|
|
603
|
-
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
610
|
+
createInscriptionTransaction(chain: WarpChain, warp: Warp): WarpAdapterGenericTransaction;
|
|
611
|
+
createFromTransaction(chain: WarpChain, tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
|
|
612
|
+
createFromTransactionHash(chain: WarpChain, hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
613
|
+
getExplorer(chain: WarpChainInfo): AdapterWarpExplorer;
|
|
614
|
+
getResults(chain: WarpChainInfo): AdapterWarpResults;
|
|
615
|
+
getRegistry(chain: WarpChain): AdapterWarpRegistry;
|
|
604
616
|
get factory(): WarpFactory;
|
|
605
|
-
get results(): AdapterWarpResults;
|
|
606
|
-
get registry(): AdapterWarpRegistry;
|
|
607
617
|
}
|
|
608
618
|
|
|
609
619
|
declare class WarpIndex {
|
|
610
620
|
private config;
|
|
611
|
-
constructor(config:
|
|
621
|
+
constructor(config: WarpClientConfig);
|
|
612
622
|
search(query: string, params?: Record<string, any>, headers?: Record<string, string>): Promise<WarpSearchHit[]>;
|
|
613
623
|
}
|
|
614
624
|
|
|
615
625
|
declare class WarpInterpolator {
|
|
616
626
|
private config;
|
|
617
|
-
private
|
|
618
|
-
constructor(config:
|
|
619
|
-
apply(config:
|
|
620
|
-
applyGlobals(config:
|
|
621
|
-
applyVars(config:
|
|
627
|
+
private adapter;
|
|
628
|
+
constructor(config: WarpClientConfig, adapter: Adapter);
|
|
629
|
+
apply(config: WarpClientConfig, warp: Warp): Promise<Warp>;
|
|
630
|
+
applyGlobals(config: WarpClientConfig, warp: Warp): Promise<Warp>;
|
|
631
|
+
applyVars(config: WarpClientConfig, warp: Warp): Warp;
|
|
622
632
|
private applyRootGlobals;
|
|
623
633
|
private applyActionGlobals;
|
|
624
634
|
}
|
|
625
635
|
|
|
626
636
|
declare class WarpLinkBuilder {
|
|
627
637
|
private config;
|
|
628
|
-
constructor(config:
|
|
638
|
+
constructor(config: WarpClientConfig);
|
|
629
639
|
isValid(url: string): boolean;
|
|
630
640
|
build(type: WarpIdType, id: string): string;
|
|
631
641
|
buildFromPrefixedIdentifier(identifier: string): string;
|
|
@@ -651,7 +661,7 @@ type ValidationResult = {
|
|
|
651
661
|
type ValidationError = string;
|
|
652
662
|
declare class WarpValidator {
|
|
653
663
|
private config;
|
|
654
|
-
constructor(config:
|
|
664
|
+
constructor(config: WarpClientConfig);
|
|
655
665
|
validate(warp: Warp): Promise<ValidationResult>;
|
|
656
666
|
private validateMaxOneValuePosition;
|
|
657
667
|
private validateVariableNamesAndResultNamesUppercase;
|
|
@@ -659,4 +669,4 @@ declare class WarpValidator {
|
|
|
659
669
|
private validateSchema;
|
|
660
670
|
}
|
|
661
671
|
|
|
662
|
-
export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, 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,
|
|
672
|
+
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, 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,12 +1,12 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Ar=Object.create;var z=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 _=(n,r)=>{for(var t in r)z(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&&z(n,a,{get:()=>r[a],enumerable:!(e=br(r,a))||e.enumerable});return n};var X=(n,r,t)=>(t=n!=null?Ar(Tr(n)):{},fr(r||!n||!n.__esModule?z(t,"default",{value:n,enumerable:!0}):t,n)),Rr=n=>fr(z({},"__esModule",{value:!0}),n);var mr={};_(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={};_(Wr,{runInVm:()=>Vr});var Vr,yr=dr(()=>{"use strict";Vr=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;
|
|
5
|
-
const output = (${
|
|
5
|
+
const output = (${n})(result);
|
|
6
6
|
self.postMessage({ result: output });
|
|
7
7
|
} catch (error) {
|
|
8
8
|
self.postMessage({ error: error.toString() });
|
|
9
9
|
}
|
|
10
10
|
};
|
|
11
|
-
`],{type:"application/javascript"}),a=URL.createObjectURL(i),o=new Worker(a);o.onmessage=function(s){s.data.error?n(new Error(s.data.error)):t(s.data.result),o.terminate(),URL.revokeObjectURL(a)},o.onerror=function(s){n(new Error(`Error in transform: ${s.message}`)),o.terminate(),URL.revokeObjectURL(a)},o.postMessage(r)}catch(i){return n(i)}})});var Gr={};Q(Gr,{CacheTtl:()=>K,KnownTokens:()=>Wr,WarpBrandBuilder:()=>nr,WarpBuilder:()=>O,WarpCache:()=>D,WarpCacheKey:()=>ir,WarpClient:()=>ar,WarpConfig:()=>h,WarpConstants:()=>l,WarpExecutor:()=>H,WarpFactory:()=>R,WarpIndex:()=>or,WarpInputTypes:()=>v,WarpInterpolator:()=>S,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>M,WarpLogger:()=>y,WarpProtocolVersions:()=>T,WarpSerializer:()=>b,WarpValidator:()=>L,address:()=>Mr,applyResultsToMessages:()=>Z,biguint:()=>Dr,boolean:()=>Hr,evaluateResultsCommon:()=>mr,extractCollectResults:()=>er,extractIdentifierInfoFromUrl:()=>U,findKnownTokenById:()=>Vr,findWarpExecutableAction:()=>X,getChainExplorerUrl:()=>Er,getLatestProtocolIdentifier:()=>V,getMainChainInfo:()=>$,getNextInfo:()=>tr,getWarpActionByIndex:()=>w,getWarpInfoFromIdentifier:()=>A,hex:()=>Fr,parseResultsOutIndex:()=>hr,replacePlaceholders:()=>z,shiftBigintBy:()=>G,string:()=>qr,toPreviewText:()=>Y,toTypedChainInfo:()=>Tr,u16:()=>Or,u32:()=>kr,u64:()=>jr,u8:()=>Lr});module.exports=br(Gr);var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:e=>e.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:e=>e.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:e=>e.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:e=>e.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},v={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 T={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},h={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${T.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${T.Brand}.schema.json`,DefaultClientUrl:e=>e==="devnet"?"https://devnet.usewarp.to":e==="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:e=>e==="devnet"?"https://devnet-api.multiversx.com":e==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:e=>e==="devnet"?"https://devnet-explorer.multiversx.com":e==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:e=>6e3,AddressHrp:"erd",ChainId:e=>e==="devnet"?"D":e==="testnet"?"T":"1",NativeToken:"EGLD"},Registry:{Contract:e=>e==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":e==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},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 $=e=>({name:h.MainChain.Name,displayName:h.MainChain.DisplayName,chainId:h.MainChain.ChainId(e.env),blockTime:h.MainChain.BlockTime(e.env),addressHrp:h.MainChain.AddressHrp,apiUrl:h.MainChain.ApiUrl(e.env),explorerUrl:h.MainChain.ExplorerUrl(e.env),nativeToken:h.MainChain.NativeToken}),Er=(e,r)=>e.explorerUrl+(r?"/"+r:""),V=e=>{if(e==="warp")return`warp:${T.Warp}`;if(e==="brand")return`brand:${T.Brand}`;if(e==="abi")return`abi:${T.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${e}`)},w=(e,r)=>e?.actions[r-1],X=e=>(e.actions.forEach((r,t)=>{if(r.type!=="link")return[r,t]}),[w(e,1),1]),Tr=e=>({name:e.name.toString(),displayName:e.display_name.toString(),chainId:e.chain_id.toString(),blockTime:e.block_time.toNumber(),addressHrp:e.address_hrp.toString(),apiUrl:e.api_url.toString(),explorerUrl:e.explorer_url.toString(),nativeToken:e.native_token.toString()}),G=(e,r)=>{let t=e.toString(),[n,i=""]=t.split("."),a=Math.abs(r);if(r>0)return BigInt(n+i.padEnd(a,"0"));if(r<0){let o=n+i;if(a>=o.length)return 0n;let s=o.slice(0,-a)||"0";return BigInt(s)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},Y=(e,r=100)=>{if(!e)return"";let t=e.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},z=(e,r)=>e.replace(/\{\{([^}]+)\}\}/g,(t,n)=>r[n]||""),Z=(e,r)=>{let t=Object.entries(e.messages||{}).map(([n,i])=>[n,z(i,r)]);return Object.fromEntries(t)};var A=e=>{let r=decodeURIComponent(e);if(r.includes(l.IdentifierParamSeparator)){let[n,i]=r.split(l.IdentifierParamSeparator),a=i.split("?")[0];return{type:n,identifier:i,identifierBase:a}}let t=r.split("?")[0];return t.length===64?{type:l.IdentifierType.Hash,identifier:r,identifierBase:t}:{type:l.IdentifierType.Alias,identifier:r,identifierBase:t}},U=e=>{let r=new URL(e),t=h.SuperClientUrls.includes(r.origin),n=r.searchParams.get(l.IdentifierParamName),i=t&&!n?r.pathname.split("/")[1]:n;if(!i)return null;let a=decodeURIComponent(i);return A(a)};var cr=_(require("qr-code-styling"));var q=class{constructor(r){this.config=r;this.config=r}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!U(r):!1}build(r,t){let n=this.config.clientUrl||h.DefaultClientUrl(this.config.env),i=r===l.IdentifierType.Alias?encodeURIComponent(t):encodeURIComponent(r+l.IdentifierParamSeparator+t);return h.SuperClientUrls.includes(n)?`${n}/${i}`:`${n}?${l.IdentifierParamName}=${i}`}buildFromPrefixedIdentifier(r){let t=A(r);return t?this.build(t.type,t.identifierBase):""}generateQrCode(r,t,n=512,i="white",a="black",o="#23F7DD"){let s=this.build(r,t);return new cr.default({type:"svg",width:n,height:n,data:String(s),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Rr="https://",tr=(e,r,t,n)=>{let i=r.actions?.[t]?.next||r.next||null;if(!i)return null;if(i.startsWith(Rr))return[{identifier:null,url:i}];let[a,o]=i.split("?");if(!o)return[{identifier:a,url:rr(a,e)}];let s=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(s.length===0){let f=z(o,{...r.vars,...n}),g=f?`${a}?${f}`:a;return[{identifier:g,url:rr(g,e)}]}let c=s[0];if(!c)return[];let p=c.match(/{{([^[]+)\[\]/),u=p?p[1]:null;if(!u||n[u]===void 0)return[];let m=Array.isArray(n[u])?n[u]:[n[u]];if(m.length===0)return[];let W=s.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let g=f.match(/\[\](\.[^}]+)?}}/),d=g&&g[1]||"";return{placeholder:f,field:d?d.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return m.map(f=>{let g=o;for(let{regex:x,field:B}of W){let C=B?Sr(f,B):f;if(C==null)return null;g=g.replace(x,C)}if(g.includes("{{")||g.includes("}}"))return null;let d=g?`${a}?${g}`:a;return{identifier:d,url:rr(d,e)}}).filter(f=>f!==null)},rr=(e,r)=>{let[t,n]=e.split("?"),i=A(t)||{type:"alias",identifier:t,identifierBase:t},o=new q(r).build(i.type,i.identifierBase);if(!n)return o;let s=new URL(o);return new URLSearchParams(n).forEach((c,p)=>s.searchParams.set(p,c)),s.toString().replace(/\/\?/,"?")},Sr=(e,r)=>r.split(".").reduce((t,n)=>t?.[n],e);var N=class N{static info(...r){N.isTestEnv||console.info(...r)}static warn(...r){N.isTestEnv||console.warn(...r)}static error(...r){N.isTestEnv||console.error(...r)}};N.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=N;var b=class{nativeToString(r,t){return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(l.ArgParamsSeparator),n=t[0],i=t.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n==="option"){let[a,o]=i.split(l.ArgParamsSeparator);return[`option:${a}`,o||null]}else if(n==="optional"){let[a,o]=i.split(l.ArgParamsSeparator);return[`optional:${a}`,o||null]}else if(n==="list"){let a=i.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),s=a[a.length-1],p=(s?s.split(","):[]).map(u=>this.stringToNative(`${o}:${u}`)[1]);return[`list:${o}`,p]}else if(n==="variadic"){let a=i.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),s=a[a.length-1],p=(s?s.split(","):[]).map(u=>this.stringToNative(`${o}:${u}`)[1]);return[`variadic:${o}`,p]}else if(n.startsWith("composite")){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),s=i.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[p]}:${c}`)[1]);return[n,s]}else{if(n==="string")return[n,i];if(n==="uint8"||n==="uint16"||n==="uint32")return[n,Number(i)];if(n==="uint64"||n==="biguint")return[n,BigInt(i||0)];if(n==="bool")return[n,i==="true"];if(n==="address")return[n,i];if(n==="token")return[n,i];if(n==="hex")return[n,i];if(n==="codemeta")return[n,i];if(n==="esdt"){let[a,o,s]=i.split(l.ArgCompositeSeparator);return[n,`${a}|${o}|${s}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}};var er=async(e,r,t,n)=>{let i=[],a={};for(let[o,s]of Object.entries(e.results||{})){if(s.startsWith(l.Transform.Prefix))continue;let c=hr(s);if(c!==null&&c!==t){a[o]=null;continue}let[p,...u]=s.split("."),m=(W,P)=>P.reduce((f,g)=>f&&f[g]!==void 0?f[g]:null,W);if(p==="out"||p.startsWith("out[")){let W=u.length===0?r?.data||r:m(r,u);i.push(W),a[o]=W}else a[o]=s}return{values:i,results:await mr(e,a,t,n)}},mr=async(e,r,t,n)=>{if(!e.results)return r;let i={...r};return i=Ur(i,e,t,n),i=await Nr(e,i),i},Ur=(e,r,t,n)=>{let i={...e},a=w(r,t)?.inputs||[],o=new b;for(let[s,c]of Object.entries(i))if(typeof c=="string"&&c.startsWith("input.")){let p=c.split(".")[1],u=a.findIndex(W=>W.as===p||W.name===p),m=u!==-1?n[u]?.value:null;i[s]=m?o.stringToNative(m)[1]:null}return i},Nr=async(e,r)=>{if(!e.results)return r;let t={...r},n=Object.entries(e.results).filter(([,i])=>i.startsWith(l.Transform.Prefix)).map(([i,a])=>({key:i,code:a.substring(l.Transform.Prefix.length)}));for(let{key:i,code:a}of n)try{let o;typeof window>"u"?o=(await Promise.resolve().then(()=>(dr(),ur))).runInVm:o=(await Promise.resolve().then(()=>(gr(),fr))).runInVm,t[i]=await o(a,t)}catch(o){y.error(`Transform error for result '${i}':`,o),t[i]=null}return t},hr=e=>{if(e==="out")return 1;let r=e.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(e.startsWith("out.")||e.startsWith("event."),null)};var Wr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Vr=e=>Wr.find(r=>r.id===e)||null;var qr=e=>`${v.String}:${e}`,Lr=e=>`${v.U8}:${e}`,Or=e=>`${v.U16}:${e}`,kr=e=>`${v.U32}:${e}`,jr=e=>`${v.U64}:${e}`,Dr=e=>`${v.Biguint}:${e}`,Hr=e=>`${v.Boolean}:${e}`,Mr=e=>`${v.Address}:${e}`,Fr=e=>`${v.Hex}:${e}`;var yr=_(require("ajv"));var nr=class{constructor(r){this.pendingBrand={protocol:V("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let n=JSON.parse(r);return t&&await this.ensureValidSchema(n),n}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||h.LatestBrandSchemaUrl,i=await(await fetch(t)).json(),a=new yr.default,o=a.compile(i);if(!o(r))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};var vr=_(require("ajv"));var L=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(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],n=(i,a)=>{i&&Object.keys(i).forEach(o=>{o!==o.toUpperCase()&&t.push(`${a} name '${o}' must be uppercase`)})};return n(r.vars,"Variable"),n(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(o=>o.type==="contract"),n=r.actions.some(o=>o.type==="query");if(!t&&!n)return[];let i=r.actions.some(o=>o.abi),a=Object.values(r.results||{}).some(o=>o.startsWith("out.")||o.startsWith("event."));return r.results&&!i&&a?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||h.LatestWarpSchemaUrl,i=await(await fetch(t)).json(),a=new vr.default({strict:!1}),o=a.compile(i);return o(r)?[]:[`Schema validation failed: ${a.errorsText(o.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var O=class{constructor(r){this.config=r;this.pendingWarp={protocol:V("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,t=!0){let n=JSON.parse(r);return t&&await this.validate(n),n}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 Y(r,t)}ensure(r,t){if(!r)throw new Error(t)}async validate(r){let n=await new L(this.config).validate(r);if(!n.valid)throw new Error(n.errors.join(`
|
|
12
|
-
`))}};var k=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 n=JSON.parse(t);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(r)),null):n.value}catch{return null}}set(r,t,n){let i={value:t,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(i))}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 E=class E{get(r){let t=E.cache.get(r);return t?Date.now()>t.expiresAt?(E.cache.delete(r),null):t.value:null}set(r,t,n){let i=Date.now()+n*1e3;E.cache.set(r,{value:t,expiresAt:i})}forget(r){E.cache.delete(r)}clear(){E.cache.clear()}};E.cache=new Map;var j=E;var K={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},ir={Warp:(e,r)=>`warp:${e}:${r}`,WarpAbi:(e,r)=>`warp-abi:${e}:${r}`,WarpExecutable:(e,r,t)=>`warp-exec:${e}:${r}:${t}`,RegistryInfo:(e,r)=>`registry-info:${e}:${r}`,Brand:(e,r)=>`brand:${e}:${r}`,ChainInfo:(e,r)=>`chain:${e}:${r}`,ChainInfos:e=>`chains:${e}`},D=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new k:r==="memory"?new j:typeof window<"u"&&window.localStorage?new k:new j}set(r,t,n){this.strategy.set(r,t,n)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var R=class{constructor(r){this.config=r;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new b,this.cache=new D(r.cache?.type)}async createExecutable(r,t,n){let i=w(r,t);if(!i)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForAction(i,n),o=await this.getResolvedInputs(a,i,n),s=this.getModifiedInputs(o),c=s.find(I=>I.input.position==="receiver")?.value,p="address"in i?i.address:null,u=c?.split(":")[1]||p;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let m=u,W=this.getPreparedArgs(i,s),P=s.find(I=>I.input.position==="value")?.value||null,f="value"in i?i.value:null,g=BigInt(P?.split(":")[1]||f||0),d=s.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),B=[...("transfers"in i?i.transfers:[])||[],...d||[]],C=s.find(I=>I.input.position==="data")?.value,J="data"in i?i.data||"":null,sr={warp:r,chain:a,action:t,destination:m,args:W,value:g,transfers:B,data:C||J||null,resolvedInputs:s};return this.cache.set(ir.WarpExecutable(this.config.env,r.meta?.hash||"",t),sr.resolvedInputs,K.OneWeek),sr}async getChainInfoForAction(r,t){if(t){let n=await this.tryGetChainFromInputs(r,t);if(n)return n}return this.getDefaultChainInfo(r)}async getResolvedInputs(r,t,n){let i=t.inputs||[],a=await Promise.all(n.map(s=>this.preprocessInput(r,s))),o=(s,c)=>{if(s.source==="query"){let p=this.url.searchParams.get(s.name);return p?this.serializer.nativeToString(s.type,p):null}else return s.source===l.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:a[c]||null};return i.map((s,c)=>{let p=o(s,c);return{input:s,value:p||(s.default!==void 0?this.serializer.nativeToString(s.type,s.default):null)}})}getModifiedInputs(r){return r.map((t,n)=>{if(t.input.modifier?.startsWith("scale:")){let[,i]=t.input.modifier.split(":");if(isNaN(Number(i))){let a=Number(r.find(c=>c.input.name===i)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let o=t.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let s=G(o,+a);return{...t,value:`${t.input.type}:${s}`}}else{let a=t.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=G(a,+i);return{...t,value:`${t.input.type}:${o}`}}}else return t})}async preprocessInput(r,t){try{let[n,i]=t.split(l.ArgParamsSeparator,2),a=this.config.adapters.find(o=>o.chain===r.name)?.executor;return a?a.preprocessInput(r,t,n,i):t}catch{return t}}getPreparedArgs(r,t){let n="args"in r?r.args||[]:[];return t.forEach(({input:i,value:a})=>{if(!a||!i.position?.startsWith("arg:"))return;let o=Number(i.position.split(":")[1])-1;n.splice(o,0,a)}),n}async tryGetChainFromInputs(r,t){let n=r.inputs?.findIndex(c=>c.position==="chain");if(n===-1||n===void 0)return null;let i=t[n];if(!i)throw new Error("WarpUtils: Chain input not found");let o=new b().stringToNative(i)[1],s=await this.config.repository.registry.getChainInfo(o);if(!s)throw new Error(`WarpUtils: Chain info not found for ${o}`);return s}async getDefaultChainInfo(r){if(!r.chain)return $(this.config);let t=await this.config.repository.registry.getChainInfo(r.chain,{ttl:K.OneWeek});if(!t)throw new Error(`WarpUtils: Chain info not found for ${r.chain}`);return t}};var S=class{constructor(r,t){this.config=r;this.repository=t}async apply(r,t){let n=this.applyVars(r,t);return await this.applyGlobals(r,n)}async applyGlobals(r,t){let n={...t};return n.actions=await Promise.all(n.actions.map(async i=>await this.applyActionGlobals(i))),n=await this.applyRootGlobals(n,r),n}applyVars(r,t){if(!t?.vars)return t;let n=JSON.stringify(t),i=(a,o)=>{n=n.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o!="string")i(a,o);else if(o.startsWith(`${l.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let s=o.split(`${l.Vars.Query}:`)[1],c=new URLSearchParams(r.currentUrl.split("?")[1]).get(s);c&&i(a,c)}else if(o.startsWith(`${l.Vars.Env}:`)){let s=o.split(`${l.Vars.Env}:`)[1],c=r.vars?.[s];c&&i(a,c)}else o===l.Source.UserWallet&&r.user?.wallet?i(a,r.user.wallet):i(a,o)}),JSON.parse(n)}async applyRootGlobals(r,t){let n=JSON.stringify(r),i={config:t,chain:$(t)};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(n=n.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}async applyActionGlobals(r){let t=r.chain?await this.repository.registry.getChainInfo(r.chain):$(this.config);if(!t)throw new Error(`Chain info not found for ${r.chain}`);let n=JSON.stringify(r),i={config:this.config,chain:t};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(n=n.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}};var H=class{constructor(r,t){this.config=r;this.handlers=t;this.factory=new R(r),this.interpolator=new S(r,r.repository),this.handlers=t}async execute(r,t){let[n,i]=X(r);if(n.type==="collect"){let p=await this.executeCollect(r,i,t);return this.handlers?.onExecuted?.(p),[null,null]}let a=await this.factory.createExecutable(r,i,t),o=a.chain.name.toLowerCase(),s=this.config.adapters.find(p=>p.chain.toLowerCase()===o);if(!s)throw new Error(`No adapter registered for chain: ${o}`);return[await s.executor.createTransaction(a),a.chain]}async evaluateResults(r,t,n){let i=this.config.adapters.find(o=>o.chain.toLowerCase()===t.name.toLowerCase());if(!i)throw new Error(`No adapter registered for chain: ${t.name}`);let a=await i.results.getTransactionExecutionResults(r,n);this.handlers?.onExecuted?.(a)}async executeCollect(r,t,n,i){let a=w(r,t);if(!a)throw new Error("WarpActionExecutor: Action not found");let o=await this.factory.getChainInfoForAction(a),s=await this.interpolator.apply(this.config,r),c=await this.factory.getResolvedInputs(o,a,n),p=this.factory.getModifiedInputs(c),u=this.factory.serializer,m=d=>{if(!d.value)return null;let x=u.stringToNative(d.value)[1];return d.input.type==="biguint"?x.toString():d.input.type==="esdt"?{}:x},W=new Headers;W.set("Content-Type","application/json"),W.set("Accept","application/json"),Object.entries(a.destination.headers||{}).forEach(([d,x])=>{W.set(d,x)});let P=Object.fromEntries(p.map(d=>[d.input.as||d.input.name,m(d)])),f=a.destination.method||"GET",g=f==="GET"?void 0:JSON.stringify({...P,...i});y.info("Executing collect",{url:a.destination.url,method:f,headers:W,body:g});try{let d=await fetch(a.destination.url,{method:f,headers:W,body:g}),x=await d.json(),{values:B,results:C}=await er(s,x,t,p),J=tr(this.config,s,t,C);return{success:d.ok,warp:s,action:t,user:this.config.user?.wallet||null,txHash:null,next:J,values:B,results:{...C,_DATA:x},messages:Z(s,C)}}catch(d){return y.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:s,action:t,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};var M=class{constructor(r,t){this.config=r;this.repository=t;this.interpolator=new S(r,t)}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!U(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let i=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),o=(await Promise.all(i)).filter(p=>p.match),s=o.length>0,c=o.map(p=>({url:p.url,warp:p.warp}));return{match:s,results:c}}async detect(r,t){let n={match:!1,url:r,warp:null,registryInfo:null,brand:null},i=r.startsWith(l.HttpProtocolPrefix)?U(r):A(r);if(!i)return n;try{let{type:a,identifierBase:o}=i,s=null,c=null,p=null;if(a==="hash"){s=await this.repository.builder.createFromTransactionHash(o,t);let m=await this.repository.registry.getInfoByHash(o,t);c=m.registryInfo,p=m.brand}else if(a==="alias"){let m=await this.repository.registry.getInfoByAlias(o,t);c=m.registryInfo,p=m.brand,m.registryInfo&&(s=await this.repository.builder.createFromTransactionHash(m.registryInfo.hash,t))}let u=s?await this.interpolator.apply(this.config,s):null;return u?{match:!0,url:r,warp:u,registryInfo:c,brand:p}:n}catch(a){return y.error("Error detecting warp link",a),n}}};var ar=class{constructor(r){this.config=r}getConfig(){return this.config}setConfig(r){return this.config=r,this}createBuilder(){return new O(this.config)}createExecutor(r){return new H(this.config,r)}async detectWarp(r,t){return new M(this.config,this.config.repository).detect(r,t)}createInscriptionTransaction(r){return this.config.repository.builder.createInscriptionTransaction(r)}async createFromTransaction(r,t=!1){return this.config.repository.builder.createFromTransaction(r,t)}async createFromTransactionHash(r,t){return this.config.repository.builder.createFromTransactionHash(r,t)}get factory(){return new R(this.config)}get results(){return this.config.repository.results}get registry(){return this.config.repository.registry}};var or=class{constructor(r){this.config=r}async search(r,t,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...t})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}`);return(await i.json()).hits}catch(i){throw y.error("WarpIndex: Error searching for warps: ",i),i}}};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,findWarpExecutableAction,getChainExplorerUrl,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 Jr={};_(Jr,{CacheTtl:()=>Q,KnownTokens:()=>Cr,WarpBrandBuilder:()=>sr,WarpBuilder:()=>D,WarpCache:()=>F,WarpCacheKey:()=>or,WarpClient:()=>pr,WarpConfig:()=>g,WarpConstants:()=>p,WarpExecutor:()=>M,WarpFactory:()=>B,WarpIndex:()=>lr,WarpInputTypes:()=>C,WarpInterpolator:()=>$,WarpLinkBuilder:()=>O,WarpLinkDetecter:()=>G,WarpLogger:()=>x,WarpProtocolVersions:()=>S,WarpSerializer:()=>T,WarpValidator:()=>k,address:()=>zr,applyResultsToMessages:()=>er,biguint:()=>Mr,boolean:()=>Gr,evaluateResultsCommon:()=>vr,extractCollectResults:()=>ir,extractIdentifierInfoFromUrl:()=>N,findKnownTokenById:()=>Or,findWarpAdapterByPrefix:()=>Y,findWarpAdapterForChain:()=>y,findWarpDefaultAdapter:()=>Z,findWarpExecutableAction:()=>rr,getLatestProtocolIdentifier:()=>q,getMainChainInfo:()=>U,getNextInfo:()=>ar,getWarpActionByIndex:()=>b,getWarpInfoFromIdentifier:()=>E,hex:()=>Kr,parseResultsOutIndex:()=>xr,replacePlaceholders:()=>J,shiftBigintBy:()=>K,string:()=>kr,toPreviewText:()=>tr,toTypedChainInfo:()=>Sr,u16:()=>jr,u32:()=>Hr,u64:()=>Fr,u8:()=>Dr});module.exports=Rr(Jr);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?.wallet},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"},Registry:{Contract:n=>n==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":n==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},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 Z=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},y=(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},Y=(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}),q=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}`)},b=(n,r)=>n?.actions[r-1],rr=n=>(n.actions.forEach((r,t)=>{if(r.type!=="link")return[r,t]}),[b(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()}),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},J=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(t,e)=>r[e]||""),er=(n,r)=>{let t=Object.entries(n.messages||{}).map(([e,a])=>[e,J(a,r)]);return Object.fromEntries(t)};var E=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 E(a)};var hr=X(require("qr-code-styling"));var O=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=E(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://",ar=(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:nr(s,n)}];let o=i.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let f=J(i,{...r.vars,...e}),h=f?`${s}?${f}`:s;return[{identifier:h,url:nr(h,n)}]}let c=o[0];if(!c)return[];let l=c.match(/{{([^[]+)\[\]/),u=l?l[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:v}of d){let R=v?$r(f,v):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:nr(w,n)}}).filter(f=>f!==null)},nr=(n,r)=>{let[t,e]=n.split("?"),a=E(t)||{type:"alias",identifier:t,identifierBase:t},i=new O(r).build(a.type,a.identifierBase);if(!e)return i;let o=new URL(i);return new URLSearchParams(e).forEach((c,l)=>o.searchParams.set(l,c)),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],l=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,l]}else if(e==="variadic"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],l=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,l]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=a.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}:${c}`)[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 ir=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 c=xr(o);if(c!==null&&c!==t){s[i]=null;continue}let[l,...u]=o.split("."),W=(d,I)=>I.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d);if(l==="out"||l.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 qr(n,a),a},Lr=(n,r,t,e)=>{let a={...n},s=b(r,t)?.inputs||[],i=new T;for(let[o,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("input.")){let l=c.split(".")[1],u=s.findIndex(d=>d.as===l||d.name===l),W=u!==-1?e[u]?.value:null;a[o]=W?i.stringToNative(W)[1]:null}return a},qr=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}],Or=n=>Cr.find(r=>r.id===n)||null;var kr=n=>`${C.String}:${n}`,Dr=n=>`${C.U8}:${n}`,jr=n=>`${C.U16}:${n}`,Hr=n=>`${C.U32}:${n}`,Fr=n=>`${C.U64}:${n}`,Mr=n=>`${C.Biguint}:${n}`,Gr=n=>`${C.Boolean}:${n}`,zr=n=>`${C.Address}:${n}`,Kr=n=>`${C.Hex}:${n}`;var Ir=X(require("ajv"));var sr=class{constructor(r){this.pendingBrand={protocol:q("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.schema?.brand||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=X(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 D=class{constructor(r){this.config=r;this.pendingWarp={protocol:q("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 j=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 H=P;var Q={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},or={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}`},F=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new j:r==="memory"?new H:typeof window<"u"&&window.localStorage?new j:new H}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 F(r.cache?.type)}async createExecutable(r,t,e){let a=b(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),c=o.find(A=>A.input.position==="receiver")?.value,l="address"in a?a.address:null,u=c?.split(":")[1]||l;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),v=[...("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:v,data:R||L||null,resolvedInputs:o};return this.cache.set(or.WarpExecutable(this.config.env,r.meta?.hash||"",t),ur.resolvedInputs,Q.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,c)=>{if(o.source==="query"){let l=this.url.searchParams.get(o.name);return l?this.serializer.nativeToString(o.type,l):null}else return o.source===p.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:s[c]||null};return a.map((o,c)=>{let l=i(o,c);return{input:o,value:l||(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(c=>c.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(p.ArgParamsSeparator,2);return y(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(l=>l.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],c=await y(i,this.adapters).registry.getChainInfo(i);if(!c)throw new Error(`WarpUtils: Chain info not found for ${i}`);return c}async getDefaultChainInfo(r){if(!r.chain)return U(this.config);let e=await Z(this.adapters).registry.getChainInfo(r.chain,{ttl:Q.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],c=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);c&&a(s,c)}else if(i.startsWith(`${p.Vars.Env}:`)){let o=i.split(`${p.Vars.Env}:`)[1],c=r.vars?.[o];c&&a(s,c)}else i===p.Source.UserWallet&&r.user?.wallet?a(s,r.user.wallet):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 M=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]=rr(r);if(e.type==="collect"){let l=await this.executeCollect(r,a,t);return this.handlers?.onExecuted?.(l),[null,null]}let s=await this.factory.createExecutable(r,a,t),i=s.chain.name.toLowerCase(),o=this.adapters.find(l=>l.chain.toLowerCase()===i);if(!o)throw new Error(`No adapter registered for chain: ${i}`);return[await o.executor.createTransaction(s),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=b(r,t);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=y(i.name,this.adapters),c=await new $(this.config,o).apply(this.config,r),l=await this.factory.getResolvedInputs(i,s,e),u=this.factory.getModifiedInputs(l),W=this.factory.serializer,d=m=>{if(!m.value)return null;let v=W.stringToNative(m.value)[1];return m.input.type==="biguint"?v.toString():m.input.type==="esdt"?{}:v},I=new Headers;I.set("Content-Type","application/json"),I.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([m,v])=>{I.set(m,v)});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}),v=await m.json(),{values:R,results:L}=await ir(c,v,t,u),cr=ar(this.config,c,t,L);return{success:m.ok,warp:c,action:t,user:this.config.user?.wallet||null,txHash:null,next:cr,values:R,results:{...L,_DATA:v},messages:er(c,L)}}catch(m){return x.error("WarpActionExecutor: Error executing collect",m),{success:!1,warp:c,action:t,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:m},messages:{}}}}};var G=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(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),i=(await Promise.all(a)).filter(l=>l.match),o=i.length>0,c=i.map(l=>({url:l.url,warp:l.warp}));return{match:o,results:c}}async detect(r,t){let e={match:!1,url:r,warp:null,registryInfo:null,brand:null},a=r.startsWith(p.HttpProtocolPrefix)?N(r):E(r);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,c=null,l=null,u=Y(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder.createFromTransactionHash(i,t);let d=await u.registry.getInfoByHash(i,t);c=d.registryInfo,l=d.brand}else if(s==="alias"){let d=await u.registry.getInfoByAlias(i,t);c=d.registryInfo,l=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:c,brand:l}:e}catch(s){return x.error("Error detecting warp link",s),e}}};var pr=class{constructor(r,t){this.config=r;this.adapters=t}getConfig(){return this.config}setConfig(r){return this.config=r,this}addAdapter(r){return this.adapters.push(r),this}createBuilder(){return new D(this.config)}createExecutor(r){return new M(this.config,this.adapters,r)}async detectWarp(r,t){return new G(this.config,this.adapters).detect(r,t)}createInscriptionTransaction(r,t){return y(r,this.adapters).builder.createInscriptionTransaction(t)}async createFromTransaction(r,t,e=!1){return y(r,this.adapters).builder.createFromTransaction(t,e)}async createFromTransactionHash(r,t,e){return y(r,this.adapters).builder.createFromTransactionHash(t,e)}getExplorer(r){return y(r.name,this.adapters).explorer(r)}getResults(r){return y(r.name,this.adapters).results}getRegistry(r){return y(r,this.adapters).registry}get factory(){return new B(this.config,this.adapters)}};var lr=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}}};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 l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallet},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 R={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${R.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${R.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],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"},Registry:{Contract:n=>n==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":n==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},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 U=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}),xt=(n,t)=>n.explorerUrl+(t?"/"+t:""),L=n=>{if(n==="warp")return`warp:${R.Warp}`;if(n==="brand")return`brand:${R.Brand}`;if(n==="abi")return`abi:${R.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},A=(n,t)=>n?.actions[t-1],_=n=>(n.actions.forEach((t,r)=>{if(t.type!=="link")return[t,r]}),[A(n,1),1]),It=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()}),G=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),a=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(a,"0"));if(t<0){let o=e+i;if(a>=o.length)return 0n;let s=o.slice(0,-a)||"0";return BigInt(s)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},X=(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},z=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),Y=(n,t)=>{let r=Object.entries(n.messages||{}).map(([e,i])=>[e,z(i,t)]);return Object.fromEntries(r)};var b=n=>{let t=decodeURIComponent(n);if(t.includes(l.IdentifierParamSeparator)){let[e,i]=t.split(l.IdentifierParamSeparator),a=i.split("?")[0];return{type:e,identifier:i,identifierBase:a}}let r=t.split("?")[0];return r.length===64?{type:l.IdentifierType.Hash,identifier:t,identifierBase:r}:{type:l.IdentifierType.Alias,identifier:t,identifierBase:r}},N=n=>{let t=new URL(n),r=m.SuperClientUrls.includes(t.origin),e=t.searchParams.get(l.IdentifierParamName),i=r&&!e?t.pathname.split("/")[1]:e;if(!i)return null;let a=decodeURIComponent(i);return b(a)};import at from"qr-code-styling";var O=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!N(t):!1}build(t,r){let e=this.config.clientUrl||m.DefaultClientUrl(this.config.env),i=t===l.IdentifierType.Alias?encodeURIComponent(r):encodeURIComponent(t+l.IdentifierParamSeparator+r);return m.SuperClientUrls.includes(e)?`${e}/${i}`:`${e}?${l.IdentifierParamName}=${i}`}buildFromPrefixedIdentifier(t){let r=b(t);return r?this.build(r.type,r.identifierBase):""}generateQrCode(t,r,e=512,i="white",a="black",o="#23F7DD"){let s=this.build(t,r);return new at({type:"svg",width:e,height:e,data:String(s),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var ot="https://",Z=(n,t,r,e)=>{let i=t.actions?.[r]?.next||t.next||null;if(!i)return null;if(i.startsWith(ot))return[{identifier:null,url:i}];let[a,o]=i.split("?");if(!o)return[{identifier:a,url:K(a,n)}];let s=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(s.length===0){let f=z(o,{...t.vars,...e}),g=f?`${a}?${f}`:a;return[{identifier:g,url:K(g,n)}]}let c=s[0];if(!c)return[];let p=c.match(/{{([^[]+)\[\]/),u=p?p[1]:null;if(!u||e[u]===void 0)return[];let h=Array.isArray(e[u])?e[u]:[e[u]];if(h.length===0)return[];let W=s.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let g=f.match(/\[\](\.[^}]+)?}}/),d=g&&g[1]||"";return{placeholder:f,field:d?d.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let g=o;for(let{regex:v,field:S}of W){let C=S?st(f,S):f;if(C==null)return null;g=g.replace(v,C)}if(g.includes("{{")||g.includes("}}"))return null;let d=g?`${a}?${g}`:a;return{identifier:d,url:K(d,n)}}).filter(f=>f!==null)},K=(n,t)=>{let[r,e]=n.split("?"),i=b(r)||{type:"alias",identifier:r,identifierBase:r},o=new O(t).build(i.type,i.identifierBase);if(!e)return o;let s=new URL(o);return new URLSearchParams(e).forEach((c,p)=>s.searchParams.set(p,c)),s.toString().replace(/\/\?/,"?")},st=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);var P=class P{static info(...t){P.isTestEnv||console.info(...t)}static warn(...t){P.isTestEnv||console.warn(...t)}static error(...t){P.isTestEnv||console.error(...t)}};P.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=P;var E=class{nativeToString(t,r){return`${t}:${r?.toString()??""}`}stringToNative(t){let r=t.split(l.ArgParamsSeparator),e=r[0],i=r.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[a,o]=i.split(l.ArgParamsSeparator);return[`option:${a}`,o||null]}else if(e==="optional"){let[a,o]=i.split(l.ArgParamsSeparator);return[`optional:${a}`,o||null]}else if(e==="list"){let a=i.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),s=a[a.length-1],p=(s?s.split(","):[]).map(u=>this.stringToNative(`${o}:${u}`)[1]);return[`list:${o}`,p]}else if(e==="variadic"){let a=i.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),s=a[a.length-1],p=(s?s.split(","):[]).map(u=>this.stringToNative(`${o}:${u}`)[1]);return[`variadic:${o}`,p]}else if(e.startsWith("composite")){let a=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),s=i.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[p]}:${c}`)[1]);return[e,s]}else{if(e==="string")return[e,i];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(i)];if(e==="uint64"||e==="biguint")return[e,BigInt(i||0)];if(e==="bool")return[e,i==="true"];if(e==="address")return[e,i];if(e==="token")return[e,i];if(e==="hex")return[e,i];if(e==="codemeta")return[e,i];if(e==="esdt"){let[a,o,s]=i.split(l.ArgCompositeSeparator);return[e,`${a}|${o}|${s}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var tt=async(n,t,r,e)=>{let i=[],a={};for(let[o,s]of Object.entries(n.results||{})){if(s.startsWith(l.Transform.Prefix))continue;let c=ut(s);if(c!==null&&c!==r){a[o]=null;continue}let[p,...u]=s.split("."),h=(W,T)=>T.reduce((f,g)=>f&&f[g]!==void 0?f[g]:null,W);if(p==="out"||p.startsWith("out[")){let W=u.length===0?t?.data||t:h(t,u);i.push(W),a[o]=W}else a[o]=s}return{values:i,results:await pt(n,a,r,e)}},pt=async(n,t,r,e)=>{if(!n.results)return t;let i={...t};return i=lt(i,n,r,e),i=await ct(n,i),i},lt=(n,t,r,e)=>{let i={...n},a=A(t,r)?.inputs||[],o=new E;for(let[s,c]of Object.entries(i))if(typeof c=="string"&&c.startsWith("input.")){let p=c.split(".")[1],u=a.findIndex(W=>W.as===p||W.name===p),h=u!==-1?e[u]?.value:null;i[s]=h?o.stringToNative(h)[1]:null}return i},ct=async(n,t)=>{if(!n.results)return t;let r={...t},e=Object.entries(n.results).filter(([,i])=>i.startsWith(l.Transform.Prefix)).map(([i,a])=>({key:i,code:a.substring(l.Transform.Prefix.length)}));for(let{key:i,code:a}of e)try{let o;typeof window>"u"?o=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:o=(await import("./runInVm-5YQ766M3.mjs")).runInVm,r[i]=await o(a,r)}catch(o){y.error(`Transform error for result '${i}':`,o),r[i]=null}return r},ut=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 dt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Jt=n=>dt.find(t=>t.id===n)||null;var or=n=>`${I.String}:${n}`,sr=n=>`${I.U8}:${n}`,pr=n=>`${I.U16}:${n}`,lr=n=>`${I.U32}:${n}`,cr=n=>`${I.U64}:${n}`,ur=n=>`${I.Biguint}:${n}`,dr=n=>`${I.Boolean}:${n}`,fr=n=>`${I.Address}:${n}`,gr=n=>`${I.Hex}:${n}`;import ft from"ajv";var rt=class{constructor(t){this.pendingBrand={protocol:L("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,i=await(await fetch(r)).json(),a=new ft,o=a.compile(i);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};import gt from"ajv";var k=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(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(i,a)=>{i&&Object.keys(i).forEach(o=>{o!==o.toUpperCase()&&r.push(`${a} name '${o}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.results,"Result"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(o=>o.type==="contract"),e=t.actions.some(o=>o.type==="query");if(!r&&!e)return[];let i=t.actions.some(o=>o.abi),a=Object.values(t.results||{}).some(o=>o.startsWith("out.")||o.startsWith("event."));return t.results&&!i&&a?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||m.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),a=new gt({strict:!1}),o=a.compile(i);return o(t)?[]:[`Schema validation failed: ${a.errorsText(o.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var H=class{constructor(t){this.config=t;this.pendingWarp={protocol:L("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 X(t,r)}ensure(t,r){if(!t)throw new Error(r)}async validate(t){let e=await new k(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
|
|
2
|
-
`))}};var V=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 i={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i))}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 w=class w{get(t){let r=w.cache.get(t);return r?Date.now()>r.expiresAt?(w.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;w.cache.set(t,{value:r,expiresAt:i})}forget(t){w.cache.delete(t)}clear(){w.cache.clear()}};w.cache=new Map;var q=w;var J={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},et={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}`},D=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new V:t==="memory"?new q:typeof window<"u"&&window.localStorage?new V:new q}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var B=class{constructor(t){this.config=t;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new E,this.cache=new D(t.cache?.type)}async createExecutable(t,r,e){let i=A(t,r);if(!i)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForAction(i,e),o=await this.getResolvedInputs(a,i,e),s=this.getModifiedInputs(o),c=s.find(x=>x.input.position==="receiver")?.value,p="address"in i?i.address:null,u=c?.split(":")[1]||p;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let h=u,W=this.getPreparedArgs(i,s),T=s.find(x=>x.input.position==="value")?.value||null,f="value"in i?i.value:null,g=BigInt(T?.split(":")[1]||f||0),d=s.filter(x=>x.input.position==="transfer"&&x.value).map(x=>x.value),S=[...("transfers"in i?i.transfers:[])||[],...d||[]],C=s.find(x=>x.input.position==="data")?.value,M="data"in i?i.data||"":null,Q={warp:t,chain:a,action:r,destination:h,args:W,value:g,transfers:S,data:C||M||null,resolvedInputs:s};return this.cache.set(et.WarpExecutable(this.config.env,t.meta?.hash||"",r),Q.resolvedInputs,J.OneWeek),Q}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 i=r.inputs||[],a=await Promise.all(e.map(s=>this.preprocessInput(t,s))),o=(s,c)=>{if(s.source==="query"){let p=this.url.searchParams.get(s.name);return p?this.serializer.nativeToString(s.type,p):null}else return s.source===l.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:a[c]||null};return i.map((s,c)=>{let p=o(s,c);return{input:s,value:p||(s.default!==void 0?this.serializer.nativeToString(s.type,s.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,i]=r.input.modifier.split(":");if(isNaN(Number(i))){let a=Number(t.find(c=>c.input.name===i)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let o=r.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let s=G(o,+a);return{...r,value:`${r.input.type}:${s}`}}else{let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=G(a,+i);return{...r,value:`${r.input.type}:${o}`}}}else return r})}async preprocessInput(t,r){try{let[e,i]=r.split(l.ArgParamsSeparator,2),a=this.config.adapters.find(o=>o.chain===t.name)?.executor;return a?a.preprocessInput(t,r,e,i):r}catch{return r}}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:i,value:a})=>{if(!a||!i.position?.startsWith("arg:"))return;let o=Number(i.position.split(":")[1])-1;e.splice(o,0,a)}),e}async tryGetChainFromInputs(t,r){let e=t.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let i=r[e];if(!i)throw new Error("WarpUtils: Chain input not found");let o=new E().stringToNative(i)[1],s=await this.config.repository.registry.getChainInfo(o);if(!s)throw new Error(`WarpUtils: Chain info not found for ${o}`);return s}async getDefaultChainInfo(t){if(!t.chain)return U(this.config);let r=await this.config.repository.registry.getChainInfo(t.chain,{ttl:J.OneWeek});if(!r)throw new Error(`WarpUtils: Chain info not found for ${t.chain}`);return r}};var $=class{constructor(t,r){this.config=t;this.repository=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 i=>await this.applyActionGlobals(i))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r){if(!r?.vars)return r;let e=JSON.stringify(r),i=(a,o)=>{e=e.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(r.vars).forEach(([a,o])=>{if(typeof o!="string")i(a,o);else if(o.startsWith(`${l.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let s=o.split(`${l.Vars.Query}:`)[1],c=new URLSearchParams(t.currentUrl.split("?")[1]).get(s);c&&i(a,c)}else if(o.startsWith(`${l.Vars.Env}:`)){let s=o.split(`${l.Vars.Env}:`)[1],c=t.vars?.[s];c&&i(a,c)}else o===l.Source.UserWallet&&t.user?.wallet?i(a,t.user.wallet):i(a,o)}),JSON.parse(e)}async applyRootGlobals(t,r){let e=JSON.stringify(t),i={config:r,chain:U(r)};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(e=e.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=t.chain?await this.repository.registry.getChainInfo(t.chain):U(this.config);if(!r)throw new Error(`Chain info not found for ${t.chain}`);let e=JSON.stringify(t),i={config:this.config,chain:r};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(e=e.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(e)}};var j=class{constructor(t,r){this.config=t;this.handlers=r;this.factory=new B(t),this.interpolator=new $(t,t.repository),this.handlers=r}async execute(t,r){let[e,i]=_(t);if(e.type==="collect"){let p=await this.executeCollect(t,i,r);return this.handlers?.onExecuted?.(p),[null,null]}let a=await this.factory.createExecutable(t,i,r),o=a.chain.name.toLowerCase(),s=this.config.adapters.find(p=>p.chain.toLowerCase()===o);if(!s)throw new Error(`No adapter registered for chain: ${o}`);return[await s.executor.createTransaction(a),a.chain]}async evaluateResults(t,r,e){let i=this.config.adapters.find(o=>o.chain.toLowerCase()===r.name.toLowerCase());if(!i)throw new Error(`No adapter registered for chain: ${r.name}`);let a=await i.results.getTransactionExecutionResults(t,e);this.handlers?.onExecuted?.(a)}async executeCollect(t,r,e,i){let a=A(t,r);if(!a)throw new Error("WarpActionExecutor: Action not found");let o=await this.factory.getChainInfoForAction(a),s=await this.interpolator.apply(this.config,t),c=await this.factory.getResolvedInputs(o,a,e),p=this.factory.getModifiedInputs(c),u=this.factory.serializer,h=d=>{if(!d.value)return null;let v=u.stringToNative(d.value)[1];return d.input.type==="biguint"?v.toString():d.input.type==="esdt"?{}:v},W=new Headers;W.set("Content-Type","application/json"),W.set("Accept","application/json"),Object.entries(a.destination.headers||{}).forEach(([d,v])=>{W.set(d,v)});let T=Object.fromEntries(p.map(d=>[d.input.as||d.input.name,h(d)])),f=a.destination.method||"GET",g=f==="GET"?void 0:JSON.stringify({...T,...i});y.info("Executing collect",{url:a.destination.url,method:f,headers:W,body:g});try{let d=await fetch(a.destination.url,{method:f,headers:W,body:g}),v=await d.json(),{values:S,results:C}=await tt(s,v,r,p),M=Z(this.config,s,r,C);return{success:d.ok,warp:s,action:r,user:this.config.user?.wallet||null,txHash:null,next:M,values:S,results:{...C,_DATA:v},messages:Y(s,C)}}catch(d){return y.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:s,action:r,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};var F=class{constructor(t,r){this.config=t;this.repository=r;this.interpolator=new $(t,r)}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!N(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),o=(await Promise.all(i)).filter(p=>p.match),s=o.length>0,c=o.map(p=>({url:p.url,warp:p.warp}));return{match:s,results:c}}async detect(t,r){let e={match:!1,url:t,warp:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?N(t):b(t);if(!i)return e;try{let{type:a,identifierBase:o}=i,s=null,c=null,p=null;if(a==="hash"){s=await this.repository.builder.createFromTransactionHash(o,r);let h=await this.repository.registry.getInfoByHash(o,r);c=h.registryInfo,p=h.brand}else if(a==="alias"){let h=await this.repository.registry.getInfoByAlias(o,r);c=h.registryInfo,p=h.brand,h.registryInfo&&(s=await this.repository.builder.createFromTransactionHash(h.registryInfo.hash,r))}let u=s?await this.interpolator.apply(this.config,s):null;return u?{match:!0,url:t,warp:u,registryInfo:c,brand:p}:e}catch(a){return y.error("Error detecting warp link",a),e}}};var nt=class{constructor(t){this.config=t}getConfig(){return this.config}setConfig(t){return this.config=t,this}createBuilder(){return new H(this.config)}createExecutor(t){return new j(this.config,t)}async detectWarp(t,r){return new F(this.config,this.config.repository).detect(t,r)}createInscriptionTransaction(t){return this.config.repository.builder.createInscriptionTransaction(t)}async createFromTransaction(t,r=!1){return this.config.repository.builder.createFromTransaction(t,r)}async createFromTransactionHash(t,r){return this.config.repository.builder.createFromTransactionHash(t,r)}get factory(){return new B(this.config)}get results(){return this.config.repository.results}get registry(){return this.config.repository.registry}};var it=class{constructor(t){this.config=t}async search(t,r,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}`);return(await i.json()).hits}catch(i){throw y.error("WarpIndex: Error searching for warps: ",i),i}}};export{J as CacheTtl,dt as KnownTokens,rt as WarpBrandBuilder,H as WarpBuilder,D as WarpCache,et as WarpCacheKey,nt as WarpClient,m as WarpConfig,l as WarpConstants,j as WarpExecutor,B as WarpFactory,it as WarpIndex,I as WarpInputTypes,$ as WarpInterpolator,O as WarpLinkBuilder,F as WarpLinkDetecter,y as WarpLogger,R as WarpProtocolVersions,E as WarpSerializer,k as WarpValidator,fr as address,Y as applyResultsToMessages,ur as biguint,dr as boolean,pt as evaluateResultsCommon,tt as extractCollectResults,N as extractIdentifierInfoFromUrl,Jt as findKnownTokenById,_ as findWarpExecutableAction,xt as getChainExplorerUrl,L as getLatestProtocolIdentifier,U as getMainChainInfo,Z as getNextInfo,A as getWarpActionByIndex,b as getWarpInfoFromIdentifier,gr as hex,ut as parseResultsOutIndex,z as replacePlaceholders,G as shiftBigintBy,or as string,X as toPreviewText,It as toTypedChainInfo,pr as u16,lr as u32,cr as u64,sr as u8};
|
|
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?.wallet},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:"}},w={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"},Registry:{Contract:n=>n==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":n==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},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 Z=n=>{let t=n.find(r=>r.chain.toLowerCase()===m.MainChain.Name.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${m.MainChain.Name}`);return t},v=(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},Y=(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: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}),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}`)},T=(n,t)=>n?.actions[t-1],tt=n=>(n.actions.forEach((t,r)=>{if(t.type!=="link")return[t,r]}),[T(n,1),1]),At=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()}),z=(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)},rt=(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},K=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),et=(n,t)=>{let r=Object.entries(n.messages||{}).map(([e,a])=>[e,K(a,t)]);return Object.fromEntries(r)};var P=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 P(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||m.DefaultClientUrl(this.config.env),a=t===p.IdentifierType.Alias?encodeURIComponent(r):encodeURIComponent(t+p.IdentifierParamSeparator+r);return m.SuperClientUrls.includes(e)?`${e}/${a}`:`${e}?${p.IdentifierParamName}=${a}`}buildFromPrefixedIdentifier(t){let r=P(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://",nt=(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:J(s,n)}];let o=i.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let f=K(i,{...t.vars,...e}),h=f?`${s}?${f}`:s;return[{identifier:h,url:J(h,n)}]}let c=o[0];if(!c)return[];let l=c.match(/{{([^[]+)\[\]/),u=l?l[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:g,field:y}of d){let E=y?ut(f,y):f;if(E==null)return null;h=h.replace(g,E)}if(h.includes("{{")||h.includes("}}"))return null;let I=h?`${s}?${h}`:s;return{identifier:I,url:J(I,n)}}).filter(f=>f!==null)},J=(n,t)=>{let[r,e]=n.split("?"),a=P(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((c,l)=>o.searchParams.set(l,c)),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 x=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],l=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,l]}else if(e==="variadic"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],l=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,l]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=a.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}:${c}`)[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 at=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 c=gt(o);if(c!==null&&c!==r){s[i]=null;continue}let[l,...u]=o.split("."),W=(d,C)=>C.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d);if(l==="out"||l.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=T(t,r)?.inputs||[],i=new R;for(let[o,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("input.")){let l=c.split(".")[1],u=s.findIndex(d=>d.as===l||d.name===l),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){x.error(`Transform error for result '${a}':`,i),r[a]=null}return r},gt=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 mt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Qt=n=>mt.find(t=>t.id===n)||null;var or=n=>`${w.String}:${n}`,pr=n=>`${w.U8}:${n}`,lr=n=>`${w.U16}:${n}`,cr=n=>`${w.U32}:${n}`,ur=n=>`${w.U64}:${n}`,dr=n=>`${w.Biguint}:${n}`,fr=n=>`${w.Boolean}:${n}`,hr=n=>`${w.Address}:${n}`,gr=n=>`${w.Hex}:${n}`;import Wt from"ajv";var it=class{constructor(t){this.pendingBrand={protocol:D("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,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 H=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||m.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 F=class{constructor(t){this.config=t;this.pendingWarp={protocol:D("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 H(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
|
|
2
|
+
`))}};var q=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let e=JSON.parse(r);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 b=class b{get(t){let r=b.cache.get(t);return r?Date.now()>r.expiresAt?(b.cache.delete(t),null):r.value:null}set(t,r,e){let a=Date.now()+e*1e3;b.cache.set(t,{value:r,expiresAt:a})}forget(t){b.cache.delete(t)}clear(){b.cache.clear()}};b.cache=new Map;var O=b;var Q={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},st={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 q:t==="memory"?new O:typeof window<"u"&&window.localStorage?new q:new O}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=T(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),c=o.find(A=>A.input.position==="receiver")?.value,l="address"in a?a.address:null,u=c?.split(":")[1]||l;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let W=u,d=this.getPreparedArgs(a,o),C=o.find(A=>A.input.position==="value")?.value||null,f="value"in a?a.value:null,h=BigInt(C?.split(":")[1]||f||0),I=o.filter(A=>A.input.position==="transfer"&&A.value).map(A=>A.value),y=[...("transfers"in a?a.transfers:[])||[],...I||[]],E=o.find(A=>A.input.position==="data")?.value,U="data"in a?a.data||"":null,X={warp:t,chain:s,action:r,destination:W,args:d,value:h,transfers:y,data:E||U||null,resolvedInputs:o};return this.cache.set(st.WarpExecutable(this.config.env,t.meta?.hash||"",r),X.resolvedInputs,Q.OneWeek),X}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,c)=>{if(o.source==="query"){let l=this.url.searchParams.get(o.name);return l?this.serializer.nativeToString(o.type,l):null}else return o.source===p.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:s[c]||null};return a.map((o,c)=>{let l=i(o,c);return{input:o,value:l||(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(c=>c.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=z(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=z(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 v(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(l=>l.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],c=await v(i,this.adapters).registry.getChainInfo(i);if(!c)throw new Error(`WarpUtils: Chain info not found for ${i}`);return c}async getDefaultChainInfo(t){if(!t.chain)return V(this.config);let e=await Z(this.adapters).registry.getChainInfo(t.chain,{ttl:Q.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],c=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);c&&a(s,c)}else if(i.startsWith(`${p.Vars.Env}:`)){let o=i.split(`${p.Vars.Env}:`)[1],c=t.vars?.[o];c&&a(s,c)}else i===p.Source.UserWallet&&t.user?.wallet?a(s,t.user.wallet):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 M=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]=tt(t);if(e.type==="collect"){let l=await this.executeCollect(t,a,r);return this.handlers?.onExecuted?.(l),[null,null]}let s=await this.factory.createExecutable(t,a,r),i=s.chain.name.toLowerCase(),o=this.adapters.find(l=>l.chain.toLowerCase()===i);if(!o)throw new Error(`No adapter registered for chain: ${i}`);return[await o.executor.createTransaction(s),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=T(t,r);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=v(i.name,this.adapters),c=await new N(this.config,o).apply(this.config,t),l=await this.factory.getResolvedInputs(i,s,e),u=this.factory.getModifiedInputs(l),W=this.factory.serializer,d=g=>{if(!g.value)return null;let y=W.stringToNative(g.value)[1];return g.input.type==="biguint"?y.toString():g.input.type==="esdt"?{}:y},C=new Headers;C.set("Content-Type","application/json"),C.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([g,y])=>{C.set(g,y)});let f=Object.fromEntries(u.map(g=>[g.input.as||g.input.name,d(g)])),h=s.destination.method||"GET",I=h==="GET"?void 0:JSON.stringify({...f,...a});x.info("Executing collect",{url:s.destination.url,method:h,headers:C,body:I});try{let g=await fetch(s.destination.url,{method:h,headers:C,body:I}),y=await g.json(),{values:E,results:U}=await at(c,y,r,u),_=nt(this.config,c,r,U);return{success:g.ok,warp:c,action:r,user:this.config.user?.wallet||null,txHash:null,next:_,values:E,results:{...U,_DATA:y},messages:et(c,U)}}catch(g){return x.error("WarpActionExecutor: Error executing collect",g),{success:!1,warp:c,action:r,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:g},messages:{}}}}};var G=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(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),i=(await Promise.all(a)).filter(l=>l.match),o=i.length>0,c=i.map(l=>({url:l.url,warp:l.warp}));return{match:o,results:c}}async detect(t,r){let e={match:!1,url:t,warp:null,registryInfo:null,brand:null},a=t.startsWith(p.HttpProtocolPrefix)?L(t):P(t);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,c=null,l=null,u=Y(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder.createFromTransactionHash(i,r);let d=await u.registry.getInfoByHash(i,r);c=d.registryInfo,l=d.brand}else if(s==="alias"){let d=await u.registry.getInfoByAlias(i,r);c=d.registryInfo,l=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:c,brand:l}:e}catch(s){return x.error("Error detecting warp link",s),e}}};var ot=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}setConfig(t){return this.config=t,this}addAdapter(t){return this.adapters.push(t),this}createBuilder(){return new F(this.config)}createExecutor(t){return new M(this.config,this.adapters,t)}async detectWarp(t,r){return new G(this.config,this.adapters).detect(t,r)}createInscriptionTransaction(t,r){return v(t,this.adapters).builder.createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return v(t,this.adapters).builder.createFromTransaction(r,e)}async createFromTransactionHash(t,r,e){return v(t,this.adapters).builder.createFromTransactionHash(r,e)}getExplorer(t){return v(t.name,this.adapters).explorer(t)}getResults(t){return v(t.name,this.adapters).results}getRegistry(t){return v(t,this.adapters).registry}get factory(){return new $(this.config,this.adapters)}};var pt=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 x.error("WarpIndex: Error searching for warps: ",a),a}}};export{Q as CacheTtl,mt as KnownTokens,it as WarpBrandBuilder,F as WarpBuilder,j as WarpCache,st as WarpCacheKey,ot as WarpClient,m as WarpConfig,p as WarpConstants,M as WarpExecutor,$ as WarpFactory,pt as WarpIndex,w as WarpInputTypes,N as WarpInterpolator,k as WarpLinkBuilder,G as WarpLinkDetecter,x as WarpLogger,S as WarpProtocolVersions,R as WarpSerializer,H as WarpValidator,hr as address,et as applyResultsToMessages,dr as biguint,fr as boolean,dt as evaluateResultsCommon,at as extractCollectResults,L as extractIdentifierInfoFromUrl,Qt as findKnownTokenById,Y as findWarpAdapterByPrefix,v as findWarpAdapterForChain,Z as findWarpDefaultAdapter,tt as findWarpExecutableAction,D as getLatestProtocolIdentifier,V as getMainChainInfo,nt as getNextInfo,T as getWarpActionByIndex,P as getWarpInfoFromIdentifier,gr as hex,gt as parseResultsOutIndex,K as replacePlaceholders,z as shiftBigintBy,or as string,rt as toPreviewText,At as toTypedChainInfo,lr as u16,cr as u32,ur as u64,pr as u8};
|