@vleap/warps 3.0.0-alpha.38 → 3.0.0-alpha.40
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 +109 -108
- package/dist/index.d.ts +109 -108
- package/dist/index.js +3 -3
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,42 +1,6 @@
|
|
|
1
1
|
import QRCodeStyling from 'qr-code-styling';
|
|
2
2
|
|
|
3
|
-
type WarpCacheType = 'memory' | 'localStorage';
|
|
4
|
-
|
|
5
|
-
type WarpChainEnv = 'mainnet' | 'testnet' | 'devnet';
|
|
6
|
-
type ProtocolName = 'warp' | 'brand' | 'abi';
|
|
7
|
-
|
|
8
3
|
type WarpChain = string;
|
|
9
|
-
type WarpInitConfig = {
|
|
10
|
-
env: WarpChainEnv;
|
|
11
|
-
repository: Adapter;
|
|
12
|
-
adapters: Adapter[];
|
|
13
|
-
preferredChain?: WarpChain;
|
|
14
|
-
clientUrl?: string;
|
|
15
|
-
currentUrl?: string;
|
|
16
|
-
vars?: Record<string, string | number>;
|
|
17
|
-
user?: {
|
|
18
|
-
wallet?: string;
|
|
19
|
-
};
|
|
20
|
-
schema?: {
|
|
21
|
-
warp?: string;
|
|
22
|
-
brand?: string;
|
|
23
|
-
};
|
|
24
|
-
cache?: {
|
|
25
|
-
ttl?: number;
|
|
26
|
-
type?: WarpCacheType;
|
|
27
|
-
};
|
|
28
|
-
registry?: {
|
|
29
|
-
contract?: string;
|
|
30
|
-
};
|
|
31
|
-
index?: {
|
|
32
|
-
url?: string;
|
|
33
|
-
apiKey?: string;
|
|
34
|
-
searchParamName?: string;
|
|
35
|
-
};
|
|
36
|
-
};
|
|
37
|
-
type WarpCacheConfig = {
|
|
38
|
-
ttl?: number;
|
|
39
|
-
};
|
|
40
4
|
type WarpChainInfo = {
|
|
41
5
|
name: WarpChain;
|
|
42
6
|
displayName: string;
|
|
@@ -227,10 +191,10 @@ type WarpBrandMeta = {
|
|
|
227
191
|
createdAt: string;
|
|
228
192
|
};
|
|
229
193
|
|
|
230
|
-
type
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
194
|
+
type WarpCacheType = 'memory' | 'localStorage';
|
|
195
|
+
|
|
196
|
+
type WarpChainEnv = 'mainnet' | 'testnet' | 'devnet';
|
|
197
|
+
type ProtocolName = 'warp' | 'brand' | 'abi';
|
|
234
198
|
|
|
235
199
|
type WarpTrustStatus = 'unverified' | 'verified' | 'blacklisted';
|
|
236
200
|
type WarpRegistryInfo = {
|
|
@@ -266,57 +230,63 @@ type WarpExecutionNextInfo = {
|
|
|
266
230
|
type WarpExecutionResults = Record<WarpResultName, any | null>;
|
|
267
231
|
type WarpExecutionMessages = Record<WarpMessageName, string | null>;
|
|
268
232
|
|
|
269
|
-
type
|
|
270
|
-
|
|
233
|
+
type WarpClientConfig = WarpInitConfig & {
|
|
234
|
+
repository: Adapter;
|
|
235
|
+
adapters: Adapter[];
|
|
271
236
|
};
|
|
272
|
-
type
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
237
|
+
type WarpInitConfig = {
|
|
238
|
+
env: WarpChainEnv;
|
|
239
|
+
preferredChain?: WarpChain;
|
|
240
|
+
clientUrl?: string;
|
|
241
|
+
currentUrl?: string;
|
|
242
|
+
vars?: Record<string, string | number>;
|
|
243
|
+
user?: {
|
|
244
|
+
wallet?: string;
|
|
245
|
+
};
|
|
246
|
+
schema?: {
|
|
247
|
+
warp?: string;
|
|
248
|
+
brand?: string;
|
|
249
|
+
};
|
|
250
|
+
cache?: {
|
|
251
|
+
ttl?: number;
|
|
252
|
+
type?: WarpCacheType;
|
|
253
|
+
};
|
|
254
|
+
registry?: {
|
|
255
|
+
contract?: string;
|
|
256
|
+
};
|
|
257
|
+
index?: {
|
|
258
|
+
url?: string;
|
|
259
|
+
apiKey?: string;
|
|
260
|
+
searchParamName?: string;
|
|
261
|
+
};
|
|
262
|
+
};
|
|
263
|
+
type WarpCacheConfig = {
|
|
264
|
+
ttl?: number;
|
|
282
265
|
};
|
|
283
|
-
|
|
284
266
|
type Adapter = {
|
|
285
267
|
chain: WarpChain;
|
|
286
|
-
builder:
|
|
287
|
-
executor:
|
|
288
|
-
results:
|
|
289
|
-
serializer:
|
|
290
|
-
registry:
|
|
268
|
+
builder: AdapterWarpBuilder;
|
|
269
|
+
executor: AdapterWarpExecutor;
|
|
270
|
+
results: AdapterWarpResults;
|
|
271
|
+
serializer: AdapterWarpSerializer;
|
|
272
|
+
registry: AdapterWarpRegistry;
|
|
291
273
|
};
|
|
292
274
|
type WarpAdapterGenericTransaction = any;
|
|
293
275
|
type WarpAdapterGenericRemoteTransaction = any;
|
|
294
276
|
type WarpAdapterGenericValue = any;
|
|
295
277
|
type WarpAdapterGenericType = any;
|
|
296
|
-
interface AdapterWarpBuilderConstructor {
|
|
297
|
-
new (config: WarpInitConfig): AdapterWarpBuilder;
|
|
298
|
-
}
|
|
299
278
|
interface AdapterWarpBuilder {
|
|
300
279
|
createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
|
|
301
280
|
createFromTransaction(tx: WarpAdapterGenericTransaction, validate?: boolean): Promise<Warp>;
|
|
302
281
|
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
303
282
|
}
|
|
304
|
-
interface AdapterWarpExecutorConstructor {
|
|
305
|
-
new (config: WarpInitConfig): AdapterWarpExecutor;
|
|
306
|
-
}
|
|
307
283
|
interface AdapterWarpExecutor {
|
|
308
284
|
createTransaction(executable: WarpExecutable): Promise<WarpAdapterGenericTransaction>;
|
|
309
285
|
preprocessInput(chain: WarpChainInfo, input: string, type: WarpActionInputType, value: string): Promise<string>;
|
|
310
286
|
}
|
|
311
|
-
interface AdapterWarpResultsConstructor {
|
|
312
|
-
new (config: WarpInitConfig): AdapterWarpResults;
|
|
313
|
-
}
|
|
314
287
|
interface AdapterWarpResults {
|
|
315
288
|
getTransactionExecutionResults(warp: Warp, actionIndex: WarpActionIndex, tx: WarpAdapterGenericRemoteTransaction): Promise<WarpExecution>;
|
|
316
289
|
}
|
|
317
|
-
interface AdapterWarpSerializerConstructor {
|
|
318
|
-
new (): AdapterWarpSerializer;
|
|
319
|
-
}
|
|
320
290
|
interface AdapterWarpSerializer {
|
|
321
291
|
typedToString(value: WarpAdapterGenericValue): string;
|
|
322
292
|
typedToNative(value: WarpAdapterGenericValue): [WarpActionInputType, WarpNativeValue];
|
|
@@ -324,9 +294,6 @@ interface AdapterWarpSerializer {
|
|
|
324
294
|
nativeToType(type: BaseWarpActionInputType): WarpAdapterGenericType;
|
|
325
295
|
stringToTyped(value: string): WarpAdapterGenericValue;
|
|
326
296
|
}
|
|
327
|
-
interface AdapterWarpRegistryConstructor {
|
|
328
|
-
new (config: WarpInitConfig): AdapterWarpRegistry;
|
|
329
|
-
}
|
|
330
297
|
interface AdapterWarpRegistry {
|
|
331
298
|
createWarpRegisterTransaction(txHash: string, alias?: string | null, brand?: string | null): WarpAdapterGenericTransaction;
|
|
332
299
|
createWarpUnregisterTransaction(txHash: string): WarpAdapterGenericTransaction;
|
|
@@ -353,6 +320,26 @@ interface AdapterWarpRegistry {
|
|
|
353
320
|
fetchBrand(hash: string, cache?: WarpCacheConfig): Promise<WarpBrand | null>;
|
|
354
321
|
}
|
|
355
322
|
|
|
323
|
+
type InterpolationBag = {
|
|
324
|
+
config: WarpInitConfig;
|
|
325
|
+
chain: WarpChainInfo;
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
type WarpSearchResult = {
|
|
329
|
+
hits: WarpSearchHit[];
|
|
330
|
+
};
|
|
331
|
+
type WarpSearchHit = {
|
|
332
|
+
hash: string;
|
|
333
|
+
alias: string;
|
|
334
|
+
name: string;
|
|
335
|
+
title: string;
|
|
336
|
+
description: string;
|
|
337
|
+
preview: string;
|
|
338
|
+
status: string;
|
|
339
|
+
category: string;
|
|
340
|
+
featured: boolean;
|
|
341
|
+
};
|
|
342
|
+
|
|
356
343
|
declare const WarpProtocolVersions: {
|
|
357
344
|
Warp: string;
|
|
358
345
|
Brand: string;
|
|
@@ -405,6 +392,10 @@ declare const WarpConstants: {
|
|
|
405
392
|
Placeholder: string;
|
|
406
393
|
Accessor: (bag: InterpolationBag) => string;
|
|
407
394
|
};
|
|
395
|
+
ChainAddressHrp: {
|
|
396
|
+
Placeholder: string;
|
|
397
|
+
Accessor: (bag: InterpolationBag) => string;
|
|
398
|
+
};
|
|
408
399
|
};
|
|
409
400
|
Vars: {
|
|
410
401
|
Query: string;
|
|
@@ -503,12 +494,8 @@ declare class WarpBrandBuilder {
|
|
|
503
494
|
|
|
504
495
|
declare class WarpBuilder {
|
|
505
496
|
private config;
|
|
506
|
-
private adapterBuilder;
|
|
507
497
|
private pendingWarp;
|
|
508
498
|
constructor(config: WarpInitConfig);
|
|
509
|
-
createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
|
|
510
|
-
createFromTransaction(tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
|
|
511
|
-
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
512
499
|
createFromRaw(encoded: string, validate?: boolean): Promise<Warp>;
|
|
513
500
|
setName(name: string): WarpBuilder;
|
|
514
501
|
setTitle(title: string): WarpBuilder;
|
|
@@ -549,14 +536,52 @@ declare class WarpCache {
|
|
|
549
536
|
clear(): void;
|
|
550
537
|
}
|
|
551
538
|
|
|
539
|
+
type DetectionResult = {
|
|
540
|
+
match: boolean;
|
|
541
|
+
url: string;
|
|
542
|
+
warp: Warp | null;
|
|
543
|
+
registryInfo: WarpRegistryInfo | null;
|
|
544
|
+
brand: WarpBrand | null;
|
|
545
|
+
};
|
|
546
|
+
type DetectionResultFromHtml = {
|
|
547
|
+
match: boolean;
|
|
548
|
+
results: {
|
|
549
|
+
url: string;
|
|
550
|
+
warp: Warp;
|
|
551
|
+
}[];
|
|
552
|
+
};
|
|
553
|
+
declare class WarpLinkDetecter {
|
|
554
|
+
private config;
|
|
555
|
+
private repository;
|
|
556
|
+
private interpolator;
|
|
557
|
+
constructor(config: WarpInitConfig, repository: Adapter);
|
|
558
|
+
isValid(url: string): boolean;
|
|
559
|
+
detectFromHtml(content: string): Promise<DetectionResultFromHtml>;
|
|
560
|
+
detect(url: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
declare class WarpClient {
|
|
564
|
+
private config;
|
|
565
|
+
constructor(config: WarpClientConfig);
|
|
566
|
+
createBuilder(): WarpBuilder;
|
|
567
|
+
detectWarp(url: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
|
|
568
|
+
createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
|
|
569
|
+
createFromTransaction(tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
|
|
570
|
+
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
571
|
+
executeWarp(warp: Warp, inputs: string[]): Promise<[WarpAdapterGenericTransaction | null, WarpChainInfo | null]>;
|
|
572
|
+
get registry(): AdapterWarpRegistry;
|
|
573
|
+
private get executor();
|
|
574
|
+
}
|
|
575
|
+
|
|
552
576
|
type ExecutionHandlers = {
|
|
553
577
|
onExecuted?: (result: WarpExecution) => void;
|
|
554
578
|
};
|
|
555
579
|
declare class WarpExecutor {
|
|
556
580
|
private config;
|
|
581
|
+
private handlers?;
|
|
557
582
|
private factory;
|
|
558
|
-
private
|
|
559
|
-
constructor(config:
|
|
583
|
+
private interpolator;
|
|
584
|
+
constructor(config: WarpClientConfig, handlers?: ExecutionHandlers | undefined);
|
|
560
585
|
execute(warp: Warp, inputs: string[]): Promise<[WarpAdapterGenericTransaction | null, WarpChainInfo | null]>;
|
|
561
586
|
evaluateResults(warp: Warp, chain: WarpChainInfo, tx: WarpAdapterGenericRemoteTransaction): Promise<void>;
|
|
562
587
|
private executeCollect;
|
|
@@ -567,7 +592,7 @@ declare class WarpFactory {
|
|
|
567
592
|
private url;
|
|
568
593
|
private serializer;
|
|
569
594
|
private cache;
|
|
570
|
-
constructor(config:
|
|
595
|
+
constructor(config: WarpClientConfig);
|
|
571
596
|
createExecutable(warp: Warp, actionIndex: number, inputs: string[]): Promise<WarpExecutable>;
|
|
572
597
|
determineAction(warp: Warp, inputs: string[]): [WarpAction, WarpActionIndex];
|
|
573
598
|
getResolvedInputs(chain: WarpChainInfo, action: WarpAction, inputArgs: string[]): Promise<ResolvedInput[]>;
|
|
@@ -584,8 +609,8 @@ declare class WarpIndex {
|
|
|
584
609
|
|
|
585
610
|
declare class WarpInterpolator {
|
|
586
611
|
private config;
|
|
587
|
-
private
|
|
588
|
-
constructor(config: WarpInitConfig);
|
|
612
|
+
private repository;
|
|
613
|
+
constructor(config: WarpInitConfig, repository: Adapter);
|
|
589
614
|
apply(config: WarpInitConfig, warp: Warp): Promise<Warp>;
|
|
590
615
|
applyGlobals(config: WarpInitConfig, warp: Warp): Promise<Warp>;
|
|
591
616
|
applyVars(config: WarpInitConfig, warp: Warp): Warp;
|
|
@@ -602,30 +627,6 @@ declare class WarpLinkBuilder {
|
|
|
602
627
|
generateQrCode(type: WarpIdType, id: string, size?: number, background?: string, color?: string, logoColor?: string): QRCodeStyling;
|
|
603
628
|
}
|
|
604
629
|
|
|
605
|
-
type DetectionResult = {
|
|
606
|
-
match: boolean;
|
|
607
|
-
url: string;
|
|
608
|
-
warp: Warp | null;
|
|
609
|
-
registryInfo: WarpRegistryInfo | null;
|
|
610
|
-
brand: WarpBrand | null;
|
|
611
|
-
};
|
|
612
|
-
type DetectionResultFromHtml = {
|
|
613
|
-
match: boolean;
|
|
614
|
-
results: {
|
|
615
|
-
url: string;
|
|
616
|
-
warp: Warp;
|
|
617
|
-
}[];
|
|
618
|
-
};
|
|
619
|
-
declare class WarpLinkDetecter {
|
|
620
|
-
private config;
|
|
621
|
-
private registry;
|
|
622
|
-
private builder;
|
|
623
|
-
constructor(config: WarpInitConfig);
|
|
624
|
-
isValid(url: string): boolean;
|
|
625
|
-
detectFromHtml(content: string): Promise<DetectionResultFromHtml>;
|
|
626
|
-
detect(url: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
|
|
627
|
-
}
|
|
628
|
-
|
|
629
630
|
declare class WarpLogger {
|
|
630
631
|
private static isTestEnv;
|
|
631
632
|
static info(...args: any[]): void;
|
|
@@ -639,7 +640,7 @@ declare class WarpSerializer {
|
|
|
639
640
|
}
|
|
640
641
|
|
|
641
642
|
declare class WarpUtils {
|
|
642
|
-
static getChainInfoForAction(config:
|
|
643
|
+
static getChainInfoForAction(config: WarpClientConfig, action: WarpAction, inputs?: string[]): Promise<WarpChainInfo>;
|
|
643
644
|
private static tryGetChainFromInputs;
|
|
644
645
|
private static getDefaultChainInfo;
|
|
645
646
|
}
|
|
@@ -659,4 +660,4 @@ declare class WarpValidator {
|
|
|
659
660
|
private validateSchema;
|
|
660
661
|
}
|
|
661
662
|
|
|
662
|
-
export { type Adapter, type AdapterWarpBuilder, type
|
|
663
|
+
export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, CacheTtl, type DetectionResult, type DetectionResultFromHtml, 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, type WarpInitConfig, 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, WarpUtils, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, getChainExplorerUrl, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,42 +1,6 @@
|
|
|
1
1
|
import QRCodeStyling from 'qr-code-styling';
|
|
2
2
|
|
|
3
|
-
type WarpCacheType = 'memory' | 'localStorage';
|
|
4
|
-
|
|
5
|
-
type WarpChainEnv = 'mainnet' | 'testnet' | 'devnet';
|
|
6
|
-
type ProtocolName = 'warp' | 'brand' | 'abi';
|
|
7
|
-
|
|
8
3
|
type WarpChain = string;
|
|
9
|
-
type WarpInitConfig = {
|
|
10
|
-
env: WarpChainEnv;
|
|
11
|
-
repository: Adapter;
|
|
12
|
-
adapters: Adapter[];
|
|
13
|
-
preferredChain?: WarpChain;
|
|
14
|
-
clientUrl?: string;
|
|
15
|
-
currentUrl?: string;
|
|
16
|
-
vars?: Record<string, string | number>;
|
|
17
|
-
user?: {
|
|
18
|
-
wallet?: string;
|
|
19
|
-
};
|
|
20
|
-
schema?: {
|
|
21
|
-
warp?: string;
|
|
22
|
-
brand?: string;
|
|
23
|
-
};
|
|
24
|
-
cache?: {
|
|
25
|
-
ttl?: number;
|
|
26
|
-
type?: WarpCacheType;
|
|
27
|
-
};
|
|
28
|
-
registry?: {
|
|
29
|
-
contract?: string;
|
|
30
|
-
};
|
|
31
|
-
index?: {
|
|
32
|
-
url?: string;
|
|
33
|
-
apiKey?: string;
|
|
34
|
-
searchParamName?: string;
|
|
35
|
-
};
|
|
36
|
-
};
|
|
37
|
-
type WarpCacheConfig = {
|
|
38
|
-
ttl?: number;
|
|
39
|
-
};
|
|
40
4
|
type WarpChainInfo = {
|
|
41
5
|
name: WarpChain;
|
|
42
6
|
displayName: string;
|
|
@@ -227,10 +191,10 @@ type WarpBrandMeta = {
|
|
|
227
191
|
createdAt: string;
|
|
228
192
|
};
|
|
229
193
|
|
|
230
|
-
type
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
194
|
+
type WarpCacheType = 'memory' | 'localStorage';
|
|
195
|
+
|
|
196
|
+
type WarpChainEnv = 'mainnet' | 'testnet' | 'devnet';
|
|
197
|
+
type ProtocolName = 'warp' | 'brand' | 'abi';
|
|
234
198
|
|
|
235
199
|
type WarpTrustStatus = 'unverified' | 'verified' | 'blacklisted';
|
|
236
200
|
type WarpRegistryInfo = {
|
|
@@ -266,57 +230,63 @@ type WarpExecutionNextInfo = {
|
|
|
266
230
|
type WarpExecutionResults = Record<WarpResultName, any | null>;
|
|
267
231
|
type WarpExecutionMessages = Record<WarpMessageName, string | null>;
|
|
268
232
|
|
|
269
|
-
type
|
|
270
|
-
|
|
233
|
+
type WarpClientConfig = WarpInitConfig & {
|
|
234
|
+
repository: Adapter;
|
|
235
|
+
adapters: Adapter[];
|
|
271
236
|
};
|
|
272
|
-
type
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
237
|
+
type WarpInitConfig = {
|
|
238
|
+
env: WarpChainEnv;
|
|
239
|
+
preferredChain?: WarpChain;
|
|
240
|
+
clientUrl?: string;
|
|
241
|
+
currentUrl?: string;
|
|
242
|
+
vars?: Record<string, string | number>;
|
|
243
|
+
user?: {
|
|
244
|
+
wallet?: string;
|
|
245
|
+
};
|
|
246
|
+
schema?: {
|
|
247
|
+
warp?: string;
|
|
248
|
+
brand?: string;
|
|
249
|
+
};
|
|
250
|
+
cache?: {
|
|
251
|
+
ttl?: number;
|
|
252
|
+
type?: WarpCacheType;
|
|
253
|
+
};
|
|
254
|
+
registry?: {
|
|
255
|
+
contract?: string;
|
|
256
|
+
};
|
|
257
|
+
index?: {
|
|
258
|
+
url?: string;
|
|
259
|
+
apiKey?: string;
|
|
260
|
+
searchParamName?: string;
|
|
261
|
+
};
|
|
262
|
+
};
|
|
263
|
+
type WarpCacheConfig = {
|
|
264
|
+
ttl?: number;
|
|
282
265
|
};
|
|
283
|
-
|
|
284
266
|
type Adapter = {
|
|
285
267
|
chain: WarpChain;
|
|
286
|
-
builder:
|
|
287
|
-
executor:
|
|
288
|
-
results:
|
|
289
|
-
serializer:
|
|
290
|
-
registry:
|
|
268
|
+
builder: AdapterWarpBuilder;
|
|
269
|
+
executor: AdapterWarpExecutor;
|
|
270
|
+
results: AdapterWarpResults;
|
|
271
|
+
serializer: AdapterWarpSerializer;
|
|
272
|
+
registry: AdapterWarpRegistry;
|
|
291
273
|
};
|
|
292
274
|
type WarpAdapterGenericTransaction = any;
|
|
293
275
|
type WarpAdapterGenericRemoteTransaction = any;
|
|
294
276
|
type WarpAdapterGenericValue = any;
|
|
295
277
|
type WarpAdapterGenericType = any;
|
|
296
|
-
interface AdapterWarpBuilderConstructor {
|
|
297
|
-
new (config: WarpInitConfig): AdapterWarpBuilder;
|
|
298
|
-
}
|
|
299
278
|
interface AdapterWarpBuilder {
|
|
300
279
|
createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
|
|
301
280
|
createFromTransaction(tx: WarpAdapterGenericTransaction, validate?: boolean): Promise<Warp>;
|
|
302
281
|
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
303
282
|
}
|
|
304
|
-
interface AdapterWarpExecutorConstructor {
|
|
305
|
-
new (config: WarpInitConfig): AdapterWarpExecutor;
|
|
306
|
-
}
|
|
307
283
|
interface AdapterWarpExecutor {
|
|
308
284
|
createTransaction(executable: WarpExecutable): Promise<WarpAdapterGenericTransaction>;
|
|
309
285
|
preprocessInput(chain: WarpChainInfo, input: string, type: WarpActionInputType, value: string): Promise<string>;
|
|
310
286
|
}
|
|
311
|
-
interface AdapterWarpResultsConstructor {
|
|
312
|
-
new (config: WarpInitConfig): AdapterWarpResults;
|
|
313
|
-
}
|
|
314
287
|
interface AdapterWarpResults {
|
|
315
288
|
getTransactionExecutionResults(warp: Warp, actionIndex: WarpActionIndex, tx: WarpAdapterGenericRemoteTransaction): Promise<WarpExecution>;
|
|
316
289
|
}
|
|
317
|
-
interface AdapterWarpSerializerConstructor {
|
|
318
|
-
new (): AdapterWarpSerializer;
|
|
319
|
-
}
|
|
320
290
|
interface AdapterWarpSerializer {
|
|
321
291
|
typedToString(value: WarpAdapterGenericValue): string;
|
|
322
292
|
typedToNative(value: WarpAdapterGenericValue): [WarpActionInputType, WarpNativeValue];
|
|
@@ -324,9 +294,6 @@ interface AdapterWarpSerializer {
|
|
|
324
294
|
nativeToType(type: BaseWarpActionInputType): WarpAdapterGenericType;
|
|
325
295
|
stringToTyped(value: string): WarpAdapterGenericValue;
|
|
326
296
|
}
|
|
327
|
-
interface AdapterWarpRegistryConstructor {
|
|
328
|
-
new (config: WarpInitConfig): AdapterWarpRegistry;
|
|
329
|
-
}
|
|
330
297
|
interface AdapterWarpRegistry {
|
|
331
298
|
createWarpRegisterTransaction(txHash: string, alias?: string | null, brand?: string | null): WarpAdapterGenericTransaction;
|
|
332
299
|
createWarpUnregisterTransaction(txHash: string): WarpAdapterGenericTransaction;
|
|
@@ -353,6 +320,26 @@ interface AdapterWarpRegistry {
|
|
|
353
320
|
fetchBrand(hash: string, cache?: WarpCacheConfig): Promise<WarpBrand | null>;
|
|
354
321
|
}
|
|
355
322
|
|
|
323
|
+
type InterpolationBag = {
|
|
324
|
+
config: WarpInitConfig;
|
|
325
|
+
chain: WarpChainInfo;
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
type WarpSearchResult = {
|
|
329
|
+
hits: WarpSearchHit[];
|
|
330
|
+
};
|
|
331
|
+
type WarpSearchHit = {
|
|
332
|
+
hash: string;
|
|
333
|
+
alias: string;
|
|
334
|
+
name: string;
|
|
335
|
+
title: string;
|
|
336
|
+
description: string;
|
|
337
|
+
preview: string;
|
|
338
|
+
status: string;
|
|
339
|
+
category: string;
|
|
340
|
+
featured: boolean;
|
|
341
|
+
};
|
|
342
|
+
|
|
356
343
|
declare const WarpProtocolVersions: {
|
|
357
344
|
Warp: string;
|
|
358
345
|
Brand: string;
|
|
@@ -405,6 +392,10 @@ declare const WarpConstants: {
|
|
|
405
392
|
Placeholder: string;
|
|
406
393
|
Accessor: (bag: InterpolationBag) => string;
|
|
407
394
|
};
|
|
395
|
+
ChainAddressHrp: {
|
|
396
|
+
Placeholder: string;
|
|
397
|
+
Accessor: (bag: InterpolationBag) => string;
|
|
398
|
+
};
|
|
408
399
|
};
|
|
409
400
|
Vars: {
|
|
410
401
|
Query: string;
|
|
@@ -503,12 +494,8 @@ declare class WarpBrandBuilder {
|
|
|
503
494
|
|
|
504
495
|
declare class WarpBuilder {
|
|
505
496
|
private config;
|
|
506
|
-
private adapterBuilder;
|
|
507
497
|
private pendingWarp;
|
|
508
498
|
constructor(config: WarpInitConfig);
|
|
509
|
-
createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
|
|
510
|
-
createFromTransaction(tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
|
|
511
|
-
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
512
499
|
createFromRaw(encoded: string, validate?: boolean): Promise<Warp>;
|
|
513
500
|
setName(name: string): WarpBuilder;
|
|
514
501
|
setTitle(title: string): WarpBuilder;
|
|
@@ -549,14 +536,52 @@ declare class WarpCache {
|
|
|
549
536
|
clear(): void;
|
|
550
537
|
}
|
|
551
538
|
|
|
539
|
+
type DetectionResult = {
|
|
540
|
+
match: boolean;
|
|
541
|
+
url: string;
|
|
542
|
+
warp: Warp | null;
|
|
543
|
+
registryInfo: WarpRegistryInfo | null;
|
|
544
|
+
brand: WarpBrand | null;
|
|
545
|
+
};
|
|
546
|
+
type DetectionResultFromHtml = {
|
|
547
|
+
match: boolean;
|
|
548
|
+
results: {
|
|
549
|
+
url: string;
|
|
550
|
+
warp: Warp;
|
|
551
|
+
}[];
|
|
552
|
+
};
|
|
553
|
+
declare class WarpLinkDetecter {
|
|
554
|
+
private config;
|
|
555
|
+
private repository;
|
|
556
|
+
private interpolator;
|
|
557
|
+
constructor(config: WarpInitConfig, repository: Adapter);
|
|
558
|
+
isValid(url: string): boolean;
|
|
559
|
+
detectFromHtml(content: string): Promise<DetectionResultFromHtml>;
|
|
560
|
+
detect(url: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
declare class WarpClient {
|
|
564
|
+
private config;
|
|
565
|
+
constructor(config: WarpClientConfig);
|
|
566
|
+
createBuilder(): WarpBuilder;
|
|
567
|
+
detectWarp(url: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
|
|
568
|
+
createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
|
|
569
|
+
createFromTransaction(tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
|
|
570
|
+
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
571
|
+
executeWarp(warp: Warp, inputs: string[]): Promise<[WarpAdapterGenericTransaction | null, WarpChainInfo | null]>;
|
|
572
|
+
get registry(): AdapterWarpRegistry;
|
|
573
|
+
private get executor();
|
|
574
|
+
}
|
|
575
|
+
|
|
552
576
|
type ExecutionHandlers = {
|
|
553
577
|
onExecuted?: (result: WarpExecution) => void;
|
|
554
578
|
};
|
|
555
579
|
declare class WarpExecutor {
|
|
556
580
|
private config;
|
|
581
|
+
private handlers?;
|
|
557
582
|
private factory;
|
|
558
|
-
private
|
|
559
|
-
constructor(config:
|
|
583
|
+
private interpolator;
|
|
584
|
+
constructor(config: WarpClientConfig, handlers?: ExecutionHandlers | undefined);
|
|
560
585
|
execute(warp: Warp, inputs: string[]): Promise<[WarpAdapterGenericTransaction | null, WarpChainInfo | null]>;
|
|
561
586
|
evaluateResults(warp: Warp, chain: WarpChainInfo, tx: WarpAdapterGenericRemoteTransaction): Promise<void>;
|
|
562
587
|
private executeCollect;
|
|
@@ -567,7 +592,7 @@ declare class WarpFactory {
|
|
|
567
592
|
private url;
|
|
568
593
|
private serializer;
|
|
569
594
|
private cache;
|
|
570
|
-
constructor(config:
|
|
595
|
+
constructor(config: WarpClientConfig);
|
|
571
596
|
createExecutable(warp: Warp, actionIndex: number, inputs: string[]): Promise<WarpExecutable>;
|
|
572
597
|
determineAction(warp: Warp, inputs: string[]): [WarpAction, WarpActionIndex];
|
|
573
598
|
getResolvedInputs(chain: WarpChainInfo, action: WarpAction, inputArgs: string[]): Promise<ResolvedInput[]>;
|
|
@@ -584,8 +609,8 @@ declare class WarpIndex {
|
|
|
584
609
|
|
|
585
610
|
declare class WarpInterpolator {
|
|
586
611
|
private config;
|
|
587
|
-
private
|
|
588
|
-
constructor(config: WarpInitConfig);
|
|
612
|
+
private repository;
|
|
613
|
+
constructor(config: WarpInitConfig, repository: Adapter);
|
|
589
614
|
apply(config: WarpInitConfig, warp: Warp): Promise<Warp>;
|
|
590
615
|
applyGlobals(config: WarpInitConfig, warp: Warp): Promise<Warp>;
|
|
591
616
|
applyVars(config: WarpInitConfig, warp: Warp): Warp;
|
|
@@ -602,30 +627,6 @@ declare class WarpLinkBuilder {
|
|
|
602
627
|
generateQrCode(type: WarpIdType, id: string, size?: number, background?: string, color?: string, logoColor?: string): QRCodeStyling;
|
|
603
628
|
}
|
|
604
629
|
|
|
605
|
-
type DetectionResult = {
|
|
606
|
-
match: boolean;
|
|
607
|
-
url: string;
|
|
608
|
-
warp: Warp | null;
|
|
609
|
-
registryInfo: WarpRegistryInfo | null;
|
|
610
|
-
brand: WarpBrand | null;
|
|
611
|
-
};
|
|
612
|
-
type DetectionResultFromHtml = {
|
|
613
|
-
match: boolean;
|
|
614
|
-
results: {
|
|
615
|
-
url: string;
|
|
616
|
-
warp: Warp;
|
|
617
|
-
}[];
|
|
618
|
-
};
|
|
619
|
-
declare class WarpLinkDetecter {
|
|
620
|
-
private config;
|
|
621
|
-
private registry;
|
|
622
|
-
private builder;
|
|
623
|
-
constructor(config: WarpInitConfig);
|
|
624
|
-
isValid(url: string): boolean;
|
|
625
|
-
detectFromHtml(content: string): Promise<DetectionResultFromHtml>;
|
|
626
|
-
detect(url: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
|
|
627
|
-
}
|
|
628
|
-
|
|
629
630
|
declare class WarpLogger {
|
|
630
631
|
private static isTestEnv;
|
|
631
632
|
static info(...args: any[]): void;
|
|
@@ -639,7 +640,7 @@ declare class WarpSerializer {
|
|
|
639
640
|
}
|
|
640
641
|
|
|
641
642
|
declare class WarpUtils {
|
|
642
|
-
static getChainInfoForAction(config:
|
|
643
|
+
static getChainInfoForAction(config: WarpClientConfig, action: WarpAction, inputs?: string[]): Promise<WarpChainInfo>;
|
|
643
644
|
private static tryGetChainFromInputs;
|
|
644
645
|
private static getDefaultChainInfo;
|
|
645
646
|
}
|
|
@@ -659,4 +660,4 @@ declare class WarpValidator {
|
|
|
659
660
|
private validateSchema;
|
|
660
661
|
}
|
|
661
662
|
|
|
662
|
-
export { type Adapter, type AdapterWarpBuilder, type
|
|
663
|
+
export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, CacheTtl, type DetectionResult, type DetectionResultFromHtml, 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, type WarpInitConfig, 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, WarpUtils, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, getChainExplorerUrl, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var xr=Object.create;var z=Object.defineProperty;var Ir=Object.getOwnPropertyDescriptor;var Cr=Object.getOwnPropertyNames;var wr=Object.getPrototypeOf,Ar=Object.prototype.hasOwnProperty;var pr=(e,r)=>()=>(e&&(r=e(e=0)),r);var _=(e,r)=>{for(var t in r)z(e,t,{get:r[t],enumerable:!0})},lr=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Cr(r))!Ar.call(e,i)&&i!==t&&z(e,i,{get:()=>r[i],enumerable:!(n=Ir(r,i))||n.enumerable});return e};var X=(e,r,t)=>(t=e!=null?xr(wr(e)):{},lr(r||!e||!e.__esModule?z(t,"default",{value:e,enumerable:!0}):t,e)),br=e=>lr(z({},"__esModule",{value:!0}),e);var ur={};_(ur,{runInVm:()=>Br});var Pr,Br,fr=pr(()=>{"use strict";Pr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Br=async(e,r)=>{let t;try{t=Pr("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 n=new t({timeout:2e3,sandbox:{result:r},eval:!1,wasm:!1});return e.trim().startsWith("(")&&e.includes("=>")?n.run(`(${e})(result)`):null}});var dr={};_(dr,{runInVm:()=>$r});var $r,mr=pr(()=>{"use strict";$r=async(e,r)=>new Promise((t,n)=>{try{let i=new Blob([`
|
|
2
2
|
self.onmessage = function(e) {
|
|
3
3
|
try {
|
|
4
4
|
const result = e.data;
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
self.postMessage({ error: error.toString() });
|
|
9
9
|
}
|
|
10
10
|
};
|
|
11
|
-
`],{type:"application/javascript"}),a=URL.createObjectURL(i),s=new Worker(a);s.onmessage=function(o){o.data.error?n(new Error(o.data.error)):t(o.data.result),s.terminate(),URL.revokeObjectURL(a)},s.onerror=function(o){n(new Error(`Error in transform: ${o.message}`)),s.terminate(),URL.revokeObjectURL(a)},s.postMessage(r)}catch(i){return n(i)}})});var Gr={};K(Gr,{CacheTtl:()=>D,KnownTokens:()=>Wr,WarpBrandBuilder:()=>rr,WarpBuilder:()=>tr,WarpCache:()=>M,WarpCacheKey:()=>er,WarpConfig:()=>h,WarpConstants:()=>l,WarpExecutor:()=>nr,WarpFactory:()=>F,WarpIndex:()=>ir,WarpInputTypes:()=>I,WarpInterpolator:()=>B,WarpLinkBuilder:()=>L,WarpLinkDetecter:()=>ar,WarpLogger:()=>v,WarpProtocolVersions:()=>R,WarpSerializer:()=>b,WarpUtils:()=>P,WarpValidator:()=>O,address:()=>Fr,applyResultsToMessages:()=>_,biguint:()=>Mr,boolean:()=>Dr,evaluateResultsCommon:()=>gr,extractCollectResults:()=>Z,extractIdentifierInfoFromUrl:()=>U,findKnownTokenById:()=>Vr,getChainExplorerUrl:()=>Tr,getLatestProtocolIdentifier:()=>q,getMainChainInfo:()=>$,getNextInfo:()=>Y,getWarpActionByIndex:()=>A,getWarpInfoFromIdentifier:()=>T,hex:()=>Hr,parseResultsOutIndex:()=>hr,replacePlaceholders:()=>z,shiftBigintBy:()=>G,string:()=>qr,toPreviewText:()=>Q,toTypedChainInfo:()=>Er,u16:()=>Or,u32:()=>kr,u64:()=>jr,u8:()=>Lr});module.exports=Ar(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}},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"},h={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: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}),Tr=(e,r)=>e.explorerUrl+(r?"/"+r:""),q=e=>{if(e==="warp")return`warp:${R.Warp}`;if(e==="brand")return`brand:${R.Brand}`;if(e==="abi")return`abi:${R.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${e}`)},A=(e,r)=>e?.actions[r-1],Er=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 s=n+i;if(a>=s.length)return 0n;let o=s.slice(0,-a)||"0";return BigInt(o)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},Q=(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]||""),_=(e,r)=>{let t=Object.entries(e.messages||{}).map(([n,i])=>[n,z(i,r)]);return Object.fromEntries(t)};var T=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 T(a)};var cr=J(require("qr-code-styling"));var L=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=T(r);return t?this.build(t.type,t.identifierBase):""}generateQrCode(r,t,n=512,i="white",a="black",s="#23F7DD"){let o=this.build(r,t);return new cr.default({type:"svg",width:n,height:n,data:String(o),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(s)}" 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 Sr="https://",Y=(e,r,t,n)=>{let i=r.actions?.[t]?.next||r.next||null;if(!i)return null;if(i.startsWith(Sr))return[{identifier:null,url:i}];let[a,s]=i.split("?");if(!s)return[{identifier:a,url:X(a,e)}];let o=s.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let f=z(s,{...r.vars,...n}),m=f?`${a}?${f}`:a;return[{identifier:m,url:X(m,e)}]}let c=o[0];if(!c)return[];let p=c.match(/{{([^[]+)\[\]/),u=p?p[1]:null;if(!u||n[u]===void 0)return[];let W=Array.isArray(n[u])?n[u]:[n[u]];if(W.length===0)return[];let d=o.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let m=f.match(/\[\](\.[^}]+)?}}/),w=m&&m[1]||"";return{placeholder:f,field:w?w.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return W.map(f=>{let m=s;for(let{regex:g,field:y}of d){let S=y?Rr(f,y):f;if(S==null)return null;m=m.replace(g,S)}if(m.includes("{{")||m.includes("}}"))return null;let w=m?`${a}?${m}`:a;return{identifier:w,url:X(w,e)}}).filter(f=>f!==null)},X=(e,r)=>{let[t,n]=e.split("?"),i=T(t)||{type:"alias",identifier:t,identifierBase:t},s=new L(r).build(i.type,i.identifierBase);if(!n)return s;let o=new URL(s);return new URLSearchParams(n).forEach((c,p)=>o.searchParams.set(p,c)),o.toString().replace(/\/\?/,"?")},Rr=(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 v=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,s]=i.split(l.ArgParamsSeparator);return[`option:${a}`,s||null]}else if(n==="optional"){let[a,s]=i.split(l.ArgParamsSeparator);return[`optional:${a}`,s||null]}else if(n==="list"){let a=i.split(l.ArgParamsSeparator),s=a.slice(0,-1).join(l.ArgParamsSeparator),o=a[a.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`list:${s}`,p]}else if(n==="variadic"){let a=i.split(l.ArgParamsSeparator),s=a.slice(0,-1).join(l.ArgParamsSeparator),o=a[a.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`variadic:${s}`,p]}else if(n.startsWith("composite")){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=i.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[p]}:${c}`)[1]);return[n,o]}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,s,o]=i.split(l.ArgCompositeSeparator);return[n,`${a}|${s}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}};var Z=async(e,r,t,n)=>{let i=[],a={};for(let[s,o]of Object.entries(e.results||{})){if(o.startsWith(l.Transform.Prefix))continue;let c=hr(o);if(c!==null&&c!==t){a[s]=null;continue}let[p,...u]=o.split("."),W=(d,x)=>x.reduce((f,m)=>f&&f[m]!==void 0?f[m]:null,d);if(p==="out"||p.startsWith("out[")){let d=u.length===0?r?.data||r:W(r,u);i.push(d),a[s]=d}else a[s]=o}return{values:i,results:await gr(e,a,t,n)}},gr=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=A(r,t)?.inputs||[],s=new b;for(let[o,c]of Object.entries(i))if(typeof c=="string"&&c.startsWith("input.")){let p=c.split(".")[1],u=a.findIndex(d=>d.as===p||d.name===p),W=u!==-1?n[u]?.value:null;i[o]=W?s.stringToNative(W)[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 s;typeof window>"u"?s=(await Promise.resolve().then(()=>(dr(),ur))).runInVm:s=(await Promise.resolve().then(()=>(mr(),fr))).runInVm,t[i]=await s(a,t)}catch(s){v.error(`Transform error for result '${i}':`,s),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=>`${I.String}:${e}`,Lr=e=>`${I.U8}:${e}`,Or=e=>`${I.U16}:${e}`,kr=e=>`${I.U32}:${e}`,jr=e=>`${I.U64}:${e}`,Mr=e=>`${I.Biguint}:${e}`,Dr=e=>`${I.Boolean}:${e}`,Fr=e=>`${I.Address}:${e}`,Hr=e=>`${I.Hex}:${e}`;var yr=J(require("ajv"));var rr=class{constructor(r){this.pendingBrand={protocol:q("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,s=a.compile(i);if(!s(r))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var vr=J(require("ajv"));var O=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(s=>{s!==s.toUpperCase()&&t.push(`${a} name '${s}' must be uppercase`)})};return n(r.vars,"Variable"),n(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(s=>s.type==="contract"),n=r.actions.some(s=>s.type==="query");if(!t&&!n)return[];let i=r.actions.some(s=>s.abi),a=Object.values(r.results||{}).some(s=>s.startsWith("out.")||s.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}),s=a.compile(i);return s(r)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var tr=class{constructor(r){this.pendingWarp={protocol:q("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=r,this.adapterBuilder=new r.repository.builder(r)}createInscriptionTransaction(r){return this.adapterBuilder.createInscriptionTransaction(r)}async createFromTransaction(r,t=!1){return this.adapterBuilder.createFromTransaction(r,t)}async createFromTransactionHash(r,t){return this.adapterBuilder.createFromTransactionHash(r,t)}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 Q(r,t)}ensure(r,t){if(!r)throw new Error(t)}async validate(r){let n=await new O(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 D={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},er={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}`},M=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 P=class{static async getChainInfoForAction(r,t,n){if(n){let i=await this.tryGetChainFromInputs(r,t,n);if(i)return i}return this.getDefaultChainInfo(r,t)}static async tryGetChainFromInputs(r,t,n){let i=t.inputs?.findIndex(u=>u.position==="chain");if(i===-1||i===void 0)return null;let a=n[i];if(!a)throw new Error("WarpUtils: Chain input not found");let o=new b().stringToNative(a)[1],p=await new r.repository.registry(r).getChainInfo(o);if(!p)throw new Error(`WarpUtils: Chain info not found for ${o}`);return p}static async getDefaultChainInfo(r,t){if(!t.chain)return $(r);let i=await new r.repository.registry(r).getChainInfo(t.chain,{ttl:D.OneWeek});if(!i)throw new Error(`WarpUtils: Chain info not found for ${t.chain}`);return i}};var F=class{constructor(r){if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.config=r,this.url=new URL(r.currentUrl),this.serializer=new b,this.cache=new M(r.cache?.type)}async createExecutable(r,t,n){let i=A(r,t);if(!i)throw new Error("WarpFactory: Action not found");let a=await P.getChainInfoForAction(this.config,i,n),s=await this.getResolvedInputs(a,i,n),o=this.getModifiedInputs(s),c=o.find(C=>C.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 W=u,d=this.getPreparedArgs(i,o),x=o.find(C=>C.input.position==="value")?.value||null,f="value"in i?i.value:null,m=BigInt(x?.split(":")[1]||f||0),w=o.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),y=[...("transfers"in i?i.transfers:[])||[],...w||[]],S=o.find(C=>C.input.position==="data")?.value,V="data"in i?i.data||"":null,or={warp:r,chain:a,action:t,destination:W,args:d,value:m,transfers:y,data:S||V||null,resolvedInputs:o};return this.cache.set(er.WarpExecutable(this.config.env,r.meta?.hash||"",t),or.resolvedInputs,D.OneWeek),or}determineAction(r,t){let n=r.actions.filter(s=>s.type!=="link"),i=this.config.preferredChain?.toLowerCase(),a=1;if(i){let s=n.findIndex(o=>o.chain?.toLowerCase()===i);s!==-1&&(a=s)}return[A(r,a),a]}async getResolvedInputs(r,t,n){let i=t.inputs||[],a=await Promise.all(n.map(o=>this.preprocessInput(r,o))),s=(o,c)=>{if(o.source==="query"){let p=this.url.searchParams.get(o.name);return p?this.serializer.nativeToString(o.type,p):null}else return o.source===l.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:a[c]||null};return i.map((o,c)=>{let p=s(o,c);return{input:o,value:p||(o.default!==void 0?this.serializer.nativeToString(o.type,o.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 s=t.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=G(s,+a);return{...t,value:`${t.input.type}:${o}`}}else{let a=t.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let s=G(a,+i);return{...t,value:`${t.input.type}:${s}`}}}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,s=a?new a(this.config):null;return s?s.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 s=Number(i.position.split(":")[1])-1;n.splice(s,0,a)}),n}};var B=class{constructor(r){this.config=r;this.registry=new this.config.repository.registry(this.config)}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,s)=>{n=n.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(t.vars).forEach(([a,s])=>{if(typeof s!="string")i(a,s);else if(s.startsWith(`${l.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${l.Vars.Query}:`)[1],c=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);c&&i(a,c)}else if(s.startsWith(`${l.Vars.Env}:`)){let o=s.split(`${l.Vars.Env}:`)[1],c=r.vars?.[o];c&&i(a,c)}else s===l.Source.UserWallet&&r.user?.wallet?i(a,r.user.wallet):i(a,s)}),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 s=a.Accessor(i);s!=null&&(n=n.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(n)}async applyActionGlobals(r){let t=r.chain?await this.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 s=a.Accessor(i);s!=null&&(n=n.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(n)}};var nr=class{constructor(r,t){this.config=r,this.factory=new F(r),this.handlers=t}async execute(r,t){let[n,i]=this.factory.determineAction(r,t),a=await this.factory.createExecutable(r,i,t);if(n.type==="collect"){let u=await this.executeCollect(r,i,t);return this.handlers?.onExecuted?.(u),[null,null]}let s=a.chain.name.toLowerCase(),o=this.config.adapters.find(u=>u.chain.toLowerCase()===s);if(!o)throw new Error(`No adapter registered for chain: ${s}`);return[await new o.executor(this.config).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 s=await new i.results(this.config).getTransactionExecutionResults(r,1,n);this.handlers?.onExecuted?.(s)}async executeCollect(r,t,n,i){let a=A(r,t);if(!a)throw new Error("WarpActionExecutor: Action not found");let s=await P.getChainInfoForAction(this.config,a),c=await new B(this.config).apply(this.config,r),p=await this.factory.getResolvedInputs(s,a,n),u=this.factory.getModifiedInputs(p),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},x=new Headers;x.set("Content-Type","application/json"),x.set("Accept","application/json"),Object.entries(a.destination.headers||{}).forEach(([g,y])=>{x.set(g,y)});let f=Object.fromEntries(u.map(g=>[g.input.as||g.input.name,d(g)])),m=a.destination.method||"GET",w=m==="GET"?void 0:JSON.stringify({...f,...i});v.info("Executing collect",{url:a.destination.url,method:m,headers:x,body:w});try{let g=await fetch(a.destination.url,{method:m,headers:x,body:w}),y=await g.json(),{values:S,results:V}=await Z(c,y,t,u),sr=Y(this.config,c,t,V);return{success:g.ok,warp:c,action:t,user:this.config.user?.wallet||null,txHash:null,next:sr,values:S,results:{...V,_DATA:y},messages:_(c,V)}}catch(g){return v.error("WarpActionExecutor: Error executing collect",g),{success:!1,warp:c,action:t,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:g},messages:{}}}}};var ir=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 v.error("WarpIndex: Error searching for warps: ",i),i}}};var ar=class{constructor(r){this.config=r;this.registry=new this.config.repository.registry(this.config),this.builder=new this.config.repository.builder(this.config)}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)),s=(await Promise.all(i)).filter(p=>p.match),o=s.length>0,c=s.map(p=>({url:p.url,warp:p.warp}));return{match:o,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):T(r);if(!i)return n;try{let{type:a,identifierBase:s}=i,o=null,c=null,p=null;if(a==="hash"){o=await this.builder.createFromTransactionHash(s,t);let d=await this.registry.getInfoByHash(s,t);c=d.registryInfo,p=d.brand}else if(a==="alias"){let d=await this.registry.getInfoByAlias(s,t);c=d.registryInfo,p=d.brand,d.registryInfo&&(o=await this.builder.createFromTransactionHash(d.registryInfo.hash,t))}let u=new B(this.config),W=o?await u.apply(this.config,o):null;return W?{match:!0,url:r,warp:W,registryInfo:c,brand:p}:n}catch(a){return v.error("Error detecting warp link",a),n}}};0&&(module.exports={CacheTtl,KnownTokens,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpUtils,WarpValidator,address,applyResultsToMessages,biguint,boolean,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,findKnownTokenById,getChainExplorerUrl,getLatestProtocolIdentifier,getMainChainInfo,getNextInfo,getWarpActionByIndex,getWarpInfoFromIdentifier,hex,parseResultsOutIndex,replacePlaceholders,shiftBigintBy,string,toPreviewText,toTypedChainInfo,u16,u32,u64,u8});
|
|
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={};_(Gr,{CacheTtl:()=>M,KnownTokens:()=>Wr,WarpBrandBuilder:()=>nr,WarpBuilder:()=>O,WarpCache:()=>D,WarpCacheKey:()=>ir,WarpClient:()=>ar,WarpConfig:()=>h,WarpConstants:()=>l,WarpExecutor:()=>F,WarpFactory:()=>H,WarpIndex:()=>or,WarpInputTypes:()=>v,WarpInterpolator:()=>R,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>G,WarpLogger:()=>y,WarpProtocolVersions:()=>E,WarpSerializer:()=>w,WarpUtils:()=>S,WarpValidator:()=>L,address:()=>Hr,applyResultsToMessages:()=>Z,biguint:()=>Dr,boolean:()=>Mr,evaluateResultsCommon:()=>gr,extractCollectResults:()=>er,extractIdentifierInfoFromUrl:()=>U,findKnownTokenById:()=>Vr,getChainExplorerUrl:()=>Tr,getLatestProtocolIdentifier:()=>V,getMainChainInfo:()=>$,getNextInfo:()=>tr,getWarpActionByIndex:()=>A,getWarpInfoFromIdentifier:()=>b,hex:()=>Fr,parseResultsOutIndex:()=>hr,replacePlaceholders:()=>J,shiftBigintBy:()=>K,string:()=>qr,toPreviewText:()=>Y,toTypedChainInfo:()=>Er,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 E={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${E.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${E.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}),Tr=(e,r)=>e.explorerUrl+(r?"/"+r:""),V=e=>{if(e==="warp")return`warp:${E.Warp}`;if(e==="brand")return`brand:${E.Brand}`;if(e==="abi")return`abi:${E.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${e}`)},A=(e,r)=>e?.actions[r-1],Er=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()}),K=(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},J=(e,r)=>e.replace(/\{\{([^}]+)\}\}/g,(t,n)=>r[n]||""),Z=(e,r)=>{let t=Object.entries(e.messages||{}).map(([n,i])=>[n,J(i,r)]);return Object.fromEntries(t)};var b=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 b(a)};var cr=X(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=b(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 Sr="https://",tr=(e,r,t,n)=>{let i=r.actions?.[t]?.next||r.next||null;if(!i)return null;if(i.startsWith(Sr))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 d=J(o,{...r.vars,...n}),m=d?`${a}?${d}`:a;return[{identifier:m,url:rr(m,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 g=Array.isArray(n[u])?n[u]:[n[u]];if(g.length===0)return[];let W=s.filter(d=>d.includes(`{{${u}[]`)).map(d=>{let m=d.match(/\[\](\.[^}]+)?}}/),f=m&&m[1]||"";return{placeholder:d,field:f?f.slice(1):"",regex:new RegExp(d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return g.map(d=>{let m=o;for(let{regex:x,field:B}of W){let C=B?Rr(d,B):d;if(C==null)return null;m=m.replace(x,C)}if(m.includes("{{")||m.includes("}}"))return null;let f=m?`${a}?${m}`:a;return{identifier:f,url:rr(f,e)}}).filter(d=>d!==null)},rr=(e,r)=>{let[t,n]=e.split("?"),i=b(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(/\/\?/,"?")},Rr=(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 w=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("."),g=(W,P)=>P.reduce((d,m)=>d&&d[m]!==void 0?d[m]:null,W);if(p==="out"||p.startsWith("out[")){let W=u.length===0?r?.data||r:g(r,u);i.push(W),a[o]=W}else a[o]=s}return{values:i,results:await gr(e,a,t,n)}},gr=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=A(r,t)?.inputs||[],o=new w;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),g=u!==-1?n[u]?.value:null;i[s]=g?o.stringToNative(g)[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(()=>(fr(),ur))).runInVm:o=(await Promise.resolve().then(()=>(mr(),dr))).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}`,Mr=e=>`${v.Boolean}:${e}`,Hr=e=>`${v.Address}:${e}`,Fr=e=>`${v.Hex}:${e}`;var yr=X(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=X(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 T=class T{get(r){let t=T.cache.get(r);return t?Date.now()>t.expiresAt?(T.cache.delete(r),null):t.value:null}set(r,t,n){let i=Date.now()+n*1e3;T.cache.set(r,{value:t,expiresAt:i})}forget(r){T.cache.delete(r)}clear(){T.cache.clear()}};T.cache=new Map;var j=T;var M={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 S=class{static async getChainInfoForAction(r,t,n){if(n){let i=await this.tryGetChainFromInputs(r,t,n);if(i)return i}return this.getDefaultChainInfo(r,t)}static async tryGetChainFromInputs(r,t,n){let i=t.inputs?.findIndex(p=>p.position==="chain");if(i===-1||i===void 0)return null;let a=n[i];if(!a)throw new Error("WarpUtils: Chain input not found");let s=new w().stringToNative(a)[1],c=await r.repository.registry.getChainInfo(s);if(!c)throw new Error(`WarpUtils: Chain info not found for ${s}`);return c}static async getDefaultChainInfo(r,t){if(!t.chain)return $(r);let n=await r.repository.registry.getChainInfo(t.chain,{ttl:M.OneWeek});if(!n)throw new Error(`WarpUtils: Chain info not found for ${t.chain}`);return n}};var H=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 w,this.cache=new D(r.cache?.type)}async createExecutable(r,t,n){let i=A(r,t);if(!i)throw new Error("WarpFactory: Action not found");let a=await S.getChainInfoForAction(this.config,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 g=u,W=this.getPreparedArgs(i,s),P=s.find(I=>I.input.position==="value")?.value||null,d="value"in i?i.value:null,m=BigInt(P?.split(":")[1]||d||0),f=s.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),B=[...("transfers"in i?i.transfers:[])||[],...f||[]],C=s.find(I=>I.input.position==="data")?.value,Q="data"in i?i.data||"":null,sr={warp:r,chain:a,action:t,destination:g,args:W,value:m,transfers:B,data:C||Q||null,resolvedInputs:s};return this.cache.set(ir.WarpExecutable(this.config.env,r.meta?.hash||"",t),sr.resolvedInputs,M.OneWeek),sr}determineAction(r,t){let n=r.actions.filter(o=>o.type!=="link"),i=this.config.preferredChain?.toLowerCase(),a=1;if(i){let o=n.findIndex(s=>s.chain?.toLowerCase()===i);o!==-1&&(a=o)}return[A(r,a),a]}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=K(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=K(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}};var R=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 F=class{constructor(r,t){this.config=r;this.handlers=t;this.factory=new H(r),this.interpolator=new R(r,r.repository),this.handlers=t}async execute(r,t){let[n,i]=this.factory.determineAction(r,t);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,1,n);this.handlers?.onExecuted?.(a)}async executeCollect(r,t,n,i){let a=A(r,t);if(!a)throw new Error("WarpActionExecutor: Action not found");let o=await S.getChainInfoForAction(this.config,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,g=f=>{if(!f.value)return null;let x=u.stringToNative(f.value)[1];return f.input.type==="biguint"?x.toString():f.input.type==="esdt"?{}:x},W=new Headers;W.set("Content-Type","application/json"),W.set("Accept","application/json"),Object.entries(a.destination.headers||{}).forEach(([f,x])=>{W.set(f,x)});let P=Object.fromEntries(p.map(f=>[f.input.as||f.input.name,g(f)])),d=a.destination.method||"GET",m=d==="GET"?void 0:JSON.stringify({...P,...i});y.info("Executing collect",{url:a.destination.url,method:d,headers:W,body:m});try{let f=await fetch(a.destination.url,{method:d,headers:W,body:m}),x=await f.json(),{values:B,results:C}=await er(s,x,t,p),Q=tr(this.config,s,t,C);return{success:f.ok,warp:s,action:t,user:this.config.user?.wallet||null,txHash:null,next:Q,values:B,results:{...C,_DATA:x},messages:Z(s,C)}}catch(f){return y.error("WarpActionExecutor: Error executing collect",f),{success:!1,warp:s,action:t,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:f},messages:{}}}}};var G=class{constructor(r,t){this.config=r;this.repository=t;this.interpolator=new R(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):b(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 g=await this.repository.registry.getInfoByHash(o,t);c=g.registryInfo,p=g.brand}else if(a==="alias"){let g=await this.repository.registry.getInfoByAlias(o,t);c=g.registryInfo,p=g.brand,g.registryInfo&&(s=await this.repository.builder.createFromTransactionHash(g.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}createBuilder(){return new O(this.config)}async detectWarp(r,t){return new G(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)}async executeWarp(r,t){return this.executor.execute(r,t)}get registry(){return this.config.repository.registry}get executor(){return new F(this.config)}};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,WarpUtils,WarpValidator,address,applyResultsToMessages,biguint,boolean,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,findKnownTokenById,getChainExplorerUrl,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 c={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:i=>i.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:i=>i.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:i=>i.chain.explorerUrl}},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 R={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${R.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${R.Brand}.schema.json`,DefaultClientUrl:i=>i==="devnet"?"https://devnet.usewarp.to":i==="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:i=>i==="devnet"?"https://devnet-api.multiversx.com":i==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:i=>i==="devnet"?"https://devnet-explorer.multiversx.com":i==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:i=>6e3,AddressHrp:"erd",ChainId:i=>i==="devnet"?"D":i==="testnet"?"T":"1",NativeToken:"EGLD"},Registry:{Contract:i=>i==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":i==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",c.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 N=i=>({name:h.MainChain.Name,displayName:h.MainChain.DisplayName,chainId:h.MainChain.ChainId(i.env),blockTime:h.MainChain.BlockTime(i.env),addressHrp:h.MainChain.AddressHrp,apiUrl:h.MainChain.ApiUrl(i.env),explorerUrl:h.MainChain.ExplorerUrl(i.env),nativeToken:h.MainChain.NativeToken}),vt=(i,t)=>i.explorerUrl+(t?"/"+t:""),O=i=>{if(i==="warp")return`warp:${R.Warp}`;if(i==="brand")return`brand:${R.Brand}`;if(i==="abi")return`abi:${R.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${i}`)},E=(i,t)=>i?.actions[t-1],It=i=>({name:i.name.toString(),displayName:i.display_name.toString(),chainId:i.chain_id.toString(),blockTime:i.block_time.toNumber(),addressHrp:i.address_hrp.toString(),apiUrl:i.api_url.toString(),explorerUrl:i.explorer_url.toString(),nativeToken:i.native_token.toString()}),M=(i,t)=>{let r=i.toString(),[e,n=""]=r.split("."),a=Math.abs(t);if(t>0)return BigInt(e+n.padEnd(a,"0"));if(t<0){let s=e+n;if(a>=s.length)return 0n;let o=s.slice(0,-a)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},Q=(i,t=100)=>{if(!i)return"";let r=i.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},G=(i,t)=>i.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),_=(i,t)=>{let r=Object.entries(i.messages||{}).map(([e,n])=>[e,G(n,t)]);return Object.fromEntries(r)};var S=i=>{let t=decodeURIComponent(i);if(t.includes(c.IdentifierParamSeparator)){let[e,n]=t.split(c.IdentifierParamSeparator),a=n.split("?")[0];return{type:e,identifier:n,identifierBase:a}}let r=t.split("?")[0];return r.length===64?{type:c.IdentifierType.Hash,identifier:t,identifierBase:r}:{type:c.IdentifierType.Alias,identifier:t,identifierBase:r}},V=i=>{let t=new URL(i),r=h.SuperClientUrls.includes(t.origin),e=t.searchParams.get(c.IdentifierParamName),n=r&&!e?t.pathname.split("/")[1]:e;if(!n)return null;let a=decodeURIComponent(n);return S(a)};import at from"qr-code-styling";var k=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!V(t):!1}build(t,r){let e=this.config.clientUrl||h.DefaultClientUrl(this.config.env),n=t===c.IdentifierType.Alias?encodeURIComponent(r):encodeURIComponent(t+c.IdentifierParamSeparator+r);return h.SuperClientUrls.includes(e)?`${e}/${n}`:`${e}?${c.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let r=S(t);return r?this.build(r.type,r.identifierBase):""}generateQrCode(t,r,e=512,n="white",a="black",s="#23F7DD"){let o=this.build(t,r);return new at({type:"svg",width:e,height:e,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},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(s)}" 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 st="https://",X=(i,t,r,e)=>{let n=t.actions?.[r]?.next||t.next||null;if(!n)return null;if(n.startsWith(st))return[{identifier:null,url:n}];let[a,s]=n.split("?");if(!s)return[{identifier:a,url:z(a,i)}];let o=s.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let f=G(s,{...t.vars,...e}),g=f?`${a}?${f}`:a;return[{identifier:g,url:z(g,i)}]}let l=o[0];if(!l)return[];let p=l.match(/{{([^[]+)\[\]/),u=p?p[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 g=f.match(/\[\](\.[^}]+)?}}/),x=g&&g[1]||"";return{placeholder:f,field:x?x.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return W.map(f=>{let g=s;for(let{regex:m,field:y}of d){let T=y?ot(f,y):f;if(T==null)return null;g=g.replace(m,T)}if(g.includes("{{")||g.includes("}}"))return null;let x=g?`${a}?${g}`:a;return{identifier:x,url:z(x,i)}}).filter(f=>f!==null)},z=(i,t)=>{let[r,e]=i.split("?"),n=S(r)||{type:"alias",identifier:r,identifierBase:r},s=new k(t).build(n.type,n.identifierBase);if(!e)return s;let o=new URL(s);return new URLSearchParams(e).forEach((l,p)=>o.searchParams.set(p,l)),o.toString().replace(/\/\?/,"?")},ot=(i,t)=>t.split(".").reduce((r,e)=>r?.[e],i);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 v=P;var A=class{nativeToString(t,r){return`${t}:${r?.toString()??""}`}stringToNative(t){let r=t.split(c.ArgParamsSeparator),e=r[0],n=r.slice(1).join(c.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[a,s]=n.split(c.ArgParamsSeparator);return[`option:${a}`,s||null]}else if(e==="optional"){let[a,s]=n.split(c.ArgParamsSeparator);return[`optional:${a}`,s||null]}else if(e==="list"){let a=n.split(c.ArgParamsSeparator),s=a.slice(0,-1).join(c.ArgParamsSeparator),o=a[a.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`list:${s}`,p]}else if(e==="variadic"){let a=n.split(c.ArgParamsSeparator),s=a.slice(0,-1).join(c.ArgParamsSeparator),o=a[a.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`variadic:${s}`,p]}else if(e.startsWith("composite")){let a=e.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),o=n.split(c.ArgCompositeSeparator).map((l,p)=>this.stringToNative(`${a[p]}:${l}`)[1]);return[e,o]}else{if(e==="string")return[e,n];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(n)];if(e==="uint64"||e==="biguint")return[e,BigInt(n||0)];if(e==="bool")return[e,n==="true"];if(e==="address")return[e,n];if(e==="token")return[e,n];if(e==="hex")return[e,n];if(e==="codemeta")return[e,n];if(e==="esdt"){let[a,s,o]=n.split(c.ArgCompositeSeparator);return[e,`${a}|${s}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var Y=async(i,t,r,e)=>{let n=[],a={};for(let[s,o]of Object.entries(i.results||{})){if(o.startsWith(c.Transform.Prefix))continue;let l=ut(o);if(l!==null&&l!==r){a[s]=null;continue}let[p,...u]=o.split("."),W=(d,I)=>I.reduce((f,g)=>f&&f[g]!==void 0?f[g]:null,d);if(p==="out"||p.startsWith("out[")){let d=u.length===0?t?.data||t:W(t,u);n.push(d),a[s]=d}else a[s]=o}return{values:n,results:await pt(i,a,r,e)}},pt=async(i,t,r,e)=>{if(!i.results)return t;let n={...t};return n=lt(n,i,r,e),n=await ct(i,n),n},lt=(i,t,r,e)=>{let n={...i},a=E(t,r)?.inputs||[],s=new A;for(let[o,l]of Object.entries(n))if(typeof l=="string"&&l.startsWith("input.")){let p=l.split(".")[1],u=a.findIndex(d=>d.as===p||d.name===p),W=u!==-1?e[u]?.value:null;n[o]=W?s.stringToNative(W)[1]:null}return n},ct=async(i,t)=>{if(!i.results)return t;let r={...t},e=Object.entries(i.results).filter(([,n])=>n.startsWith(c.Transform.Prefix)).map(([n,a])=>({key:n,code:a.substring(c.Transform.Prefix.length)}));for(let{key:n,code:a}of e)try{let s;typeof window>"u"?s=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:s=(await import("./runInVm-5YQ766M3.mjs")).runInVm,r[n]=await s(a,r)}catch(s){v.error(`Transform error for result '${n}':`,s),r[n]=null}return r},ut=i=>{if(i==="out")return 1;let t=i.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(i.startsWith("out.")||i.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}],Kt=i=>dt.find(t=>t.id===i)||null;var ir=i=>`${w.String}:${i}`,ar=i=>`${w.U8}:${i}`,sr=i=>`${w.U16}:${i}`,or=i=>`${w.U32}:${i}`,pr=i=>`${w.U64}:${i}`,lr=i=>`${w.Biguint}:${i}`,cr=i=>`${w.Boolean}:${i}`,ur=i=>`${w.Address}:${i}`,dr=i=>`${w.Hex}:${i}`;import ft from"ajv";var Z=class{constructor(t){this.pendingBrand={protocol:O("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||h.LatestBrandSchemaUrl,n=await(await fetch(r)).json(),a=new ft,s=a.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import gt from"ajv";var j=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(n,a)=>{n&&Object.keys(n).forEach(s=>{s!==s.toUpperCase()&&r.push(`${a} name '${s}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.results,"Result"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(s=>s.type==="contract"),e=t.actions.some(s=>s.type==="query");if(!r&&!e)return[];let n=t.actions.some(s=>s.abi),a=Object.values(t.results||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.results&&!n&&a?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||h.LatestWarpSchemaUrl,n=await(await fetch(r)).json(),a=new gt({strict:!1}),s=a.compile(n);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var tt=class{constructor(t){this.pendingWarp={protocol:O("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.adapterBuilder=new t.repository.builder(t)}createInscriptionTransaction(t){return this.adapterBuilder.createInscriptionTransaction(t)}async createFromTransaction(t,r=!1){return this.adapterBuilder.createFromTransaction(t,r)}async createFromTransactionHash(t,r){return this.adapterBuilder.createFromTransactionHash(t,r)}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 Q(t,r)}ensure(t,r){if(!t)throw new Error(r)}async validate(t){let e=await new j(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
|
|
2
|
-
`))}};var q=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let e=JSON.parse(r);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let n={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r?.startsWith(this.prefix)&&localStorage.removeItem(r)}}};var 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 n=Date.now()+e*1e3;b.cache.set(t,{value:r,expiresAt:n})}forget(t){b.cache.delete(t)}clear(){b.cache.clear()}};b.cache=new Map;var L=b;var F={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},rt={Warp:(i,t)=>`warp:${i}:${t}`,WarpAbi:(i,t)=>`warp-abi:${i}:${t}`,WarpExecutable:(i,t,r)=>`warp-exec:${i}:${t}:${r}`,RegistryInfo:(i,t)=>`registry-info:${i}:${t}`,Brand:(i,t)=>`brand:${i}:${t}`,ChainInfo:(i,t)=>`chain:${i}:${t}`,ChainInfos:i=>`chains:${i}`},D=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new q:t==="memory"?new L:typeof window<"u"&&window.localStorage?new q:new L}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{static async getChainInfoForAction(t,r,e){if(e){let n=await this.tryGetChainFromInputs(t,r,e);if(n)return n}return this.getDefaultChainInfo(t,r)}static async tryGetChainFromInputs(t,r,e){let n=r.inputs?.findIndex(u=>u.position==="chain");if(n===-1||n===void 0)return null;let a=e[n];if(!a)throw new Error("WarpUtils: Chain input not found");let o=new A().stringToNative(a)[1],p=await new t.repository.registry(t).getChainInfo(o);if(!p)throw new Error(`WarpUtils: Chain info not found for ${o}`);return p}static async getDefaultChainInfo(t,r){if(!r.chain)return N(t);let n=await new t.repository.registry(t).getChainInfo(r.chain,{ttl:F.OneWeek});if(!n)throw new Error(`WarpUtils: Chain info not found for ${r.chain}`);return n}};var H=class{constructor(t){if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new A,this.cache=new D(t.cache?.type)}async createExecutable(t,r,e){let n=E(t,r);if(!n)throw new Error("WarpFactory: Action not found");let a=await B.getChainInfoForAction(this.config,n,e),s=await this.getResolvedInputs(a,n,e),o=this.getModifiedInputs(s),l=o.find(C=>C.input.position==="receiver")?.value,p="address"in n?n.address:null,u=l?.split(":")[1]||p;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let W=u,d=this.getPreparedArgs(n,o),I=o.find(C=>C.input.position==="value")?.value||null,f="value"in n?n.value:null,g=BigInt(I?.split(":")[1]||f||0),x=o.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),y=[...("transfers"in n?n.transfers:[])||[],...x||[]],T=o.find(C=>C.input.position==="data")?.value,U="data"in n?n.data||"":null,J={warp:t,chain:a,action:r,destination:W,args:d,value:g,transfers:y,data:T||U||null,resolvedInputs:o};return this.cache.set(rt.WarpExecutable(this.config.env,t.meta?.hash||"",r),J.resolvedInputs,F.OneWeek),J}determineAction(t,r){let e=t.actions.filter(s=>s.type!=="link"),n=this.config.preferredChain?.toLowerCase(),a=1;if(n){let s=e.findIndex(o=>o.chain?.toLowerCase()===n);s!==-1&&(a=s)}return[E(t,a),a]}async getResolvedInputs(t,r,e){let n=r.inputs||[],a=await Promise.all(e.map(o=>this.preprocessInput(t,o))),s=(o,l)=>{if(o.source==="query"){let p=this.url.searchParams.get(o.name);return p?this.serializer.nativeToString(o.type,p):null}else return o.source===c.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:a[l]||null};return n.map((o,l)=>{let p=s(o,l);return{input:o,value:p||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,n]=r.input.modifier.split(":");if(isNaN(Number(n))){let a=Number(t.find(l=>l.input.name===n)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=M(s,+a);return{...r,value:`${r.input.type}:${o}`}}else{let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let s=M(a,+n);return{...r,value:`${r.input.type}:${s}`}}}else return r})}async preprocessInput(t,r){try{let[e,n]=r.split(c.ArgParamsSeparator,2),a=this.config.adapters.find(o=>o.chain===t.name)?.executor,s=a?new a(this.config):null;return s?s.preprocessInput(t,r,e,n):r}catch{return r}}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:n,value:a})=>{if(!a||!n.position?.startsWith("arg:"))return;let s=Number(n.position.split(":")[1])-1;e.splice(s,0,a)}),e}};var $=class{constructor(t){this.config=t;this.registry=new this.config.repository.registry(this.config)}async apply(t,r){let e=this.applyVars(t,r);return await this.applyGlobals(t,e)}async applyGlobals(t,r){let e={...r};return e.actions=await Promise.all(e.actions.map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r){if(!r?.vars)return r;let e=JSON.stringify(r),n=(a,s)=>{e=e.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(r.vars).forEach(([a,s])=>{if(typeof s!="string")n(a,s);else if(s.startsWith(`${c.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${c.Vars.Query}:`)[1],l=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);l&&n(a,l)}else if(s.startsWith(`${c.Vars.Env}:`)){let o=s.split(`${c.Vars.Env}:`)[1],l=t.vars?.[o];l&&n(a,l)}else s===c.Source.UserWallet&&t.user?.wallet?n(a,t.user.wallet):n(a,s)}),JSON.parse(e)}async applyRootGlobals(t,r){let e=JSON.stringify(t),n={config:r,chain:N(r)};return Object.values(c.Globals).forEach(a=>{let s=a.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=t.chain?await this.registry.getChainInfo(t.chain):N(this.config);if(!r)throw new Error(`Chain info not found for ${t.chain}`);let e=JSON.stringify(t),n={config:this.config,chain:r};return Object.values(c.Globals).forEach(a=>{let s=a.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(e)}};var et=class{constructor(t,r){this.config=t,this.factory=new H(t),this.handlers=r}async execute(t,r){let[e,n]=this.factory.determineAction(t,r),a=await this.factory.createExecutable(t,n,r);if(e.type==="collect"){let u=await this.executeCollect(t,n,r);return this.handlers?.onExecuted?.(u),[null,null]}let s=a.chain.name.toLowerCase(),o=this.config.adapters.find(u=>u.chain.toLowerCase()===s);if(!o)throw new Error(`No adapter registered for chain: ${s}`);return[await new o.executor(this.config).createTransaction(a),a.chain]}async evaluateResults(t,r,e){let n=this.config.adapters.find(o=>o.chain.toLowerCase()===r.name.toLowerCase());if(!n)throw new Error(`No adapter registered for chain: ${r.name}`);let s=await new n.results(this.config).getTransactionExecutionResults(t,1,e);this.handlers?.onExecuted?.(s)}async executeCollect(t,r,e,n){let a=E(t,r);if(!a)throw new Error("WarpActionExecutor: Action not found");let s=await B.getChainInfoForAction(this.config,a),l=await new $(this.config).apply(this.config,t),p=await this.factory.getResolvedInputs(s,a,e),u=this.factory.getModifiedInputs(p),W=this.factory.serializer,d=m=>{if(!m.value)return null;let y=W.stringToNative(m.value)[1];return m.input.type==="biguint"?y.toString():m.input.type==="esdt"?{}:y},I=new Headers;I.set("Content-Type","application/json"),I.set("Accept","application/json"),Object.entries(a.destination.headers||{}).forEach(([m,y])=>{I.set(m,y)});let f=Object.fromEntries(u.map(m=>[m.input.as||m.input.name,d(m)])),g=a.destination.method||"GET",x=g==="GET"?void 0:JSON.stringify({...f,...n});v.info("Executing collect",{url:a.destination.url,method:g,headers:I,body:x});try{let m=await fetch(a.destination.url,{method:g,headers:I,body:x}),y=await m.json(),{values:T,results:U}=await Y(l,y,r,u),K=X(this.config,l,r,U);return{success:m.ok,warp:l,action:r,user:this.config.user?.wallet||null,txHash:null,next:K,values:T,results:{...U,_DATA:y},messages:_(l,U)}}catch(m){return v.error("WarpActionExecutor: Error executing collect",m),{success:!1,warp:l,action:r,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:m},messages:{}}}}};var nt=class{constructor(t){this.config=t}async search(t,r,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw v.error("WarpIndex: Error searching for warps: ",n),n}}};var it=class{constructor(t){this.config=t;this.registry=new this.config.repository.registry(this.config),this.builder=new this.config.repository.builder(this.config)}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!V(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),s=(await Promise.all(n)).filter(p=>p.match),o=s.length>0,l=s.map(p=>({url:p.url,warp:p.warp}));return{match:o,results:l}}async detect(t,r){let e={match:!1,url:t,warp:null,registryInfo:null,brand:null},n=t.startsWith(c.HttpProtocolPrefix)?V(t):S(t);if(!n)return e;try{let{type:a,identifierBase:s}=n,o=null,l=null,p=null;if(a==="hash"){o=await this.builder.createFromTransactionHash(s,r);let d=await this.registry.getInfoByHash(s,r);l=d.registryInfo,p=d.brand}else if(a==="alias"){let d=await this.registry.getInfoByAlias(s,r);l=d.registryInfo,p=d.brand,d.registryInfo&&(o=await this.builder.createFromTransactionHash(d.registryInfo.hash,r))}let u=new $(this.config),W=o?await u.apply(this.config,o):null;return W?{match:!0,url:t,warp:W,registryInfo:l,brand:p}:e}catch(a){return v.error("Error detecting warp link",a),e}}};export{F as CacheTtl,dt as KnownTokens,Z as WarpBrandBuilder,tt as WarpBuilder,D as WarpCache,rt as WarpCacheKey,h as WarpConfig,c as WarpConstants,et as WarpExecutor,H as WarpFactory,nt as WarpIndex,w as WarpInputTypes,$ as WarpInterpolator,k as WarpLinkBuilder,it as WarpLinkDetecter,v as WarpLogger,R as WarpProtocolVersions,A as WarpSerializer,B as WarpUtils,j as WarpValidator,ur as address,_ as applyResultsToMessages,lr as biguint,cr as boolean,pt as evaluateResultsCommon,Y as extractCollectResults,V as extractIdentifierInfoFromUrl,Kt as findKnownTokenById,vt as getChainExplorerUrl,O as getLatestProtocolIdentifier,N as getMainChainInfo,X as getNextInfo,E as getWarpActionByIndex,S as getWarpInfoFromIdentifier,dr as hex,ut as parseResultsOutIndex,G as replacePlaceholders,M as shiftBigintBy,ir as string,Q as toPreviewText,It as toTypedChainInfo,sr as u16,or as u32,pr as u64,ar as u8};
|
|
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:i=>i.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:i=>i.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:i=>i.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:i=>i.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 P={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${P.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${P.Brand}.schema.json`,DefaultClientUrl:i=>i==="devnet"?"https://devnet.usewarp.to":i==="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:i=>i==="devnet"?"https://devnet-api.multiversx.com":i==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:i=>i==="devnet"?"https://devnet-explorer.multiversx.com":i==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:i=>6e3,AddressHrp:"erd",ChainId:i=>i==="devnet"?"D":i==="testnet"?"T":"1",NativeToken:"EGLD"},Registry:{Contract:i=>i==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":i==="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=i=>({name:h.MainChain.Name,displayName:h.MainChain.DisplayName,chainId:h.MainChain.ChainId(i.env),blockTime:h.MainChain.BlockTime(i.env),addressHrp:h.MainChain.AddressHrp,apiUrl:h.MainChain.ApiUrl(i.env),explorerUrl:h.MainChain.ExplorerUrl(i.env),nativeToken:h.MainChain.NativeToken}),xt=(i,t)=>i.explorerUrl+(t?"/"+t:""),q=i=>{if(i==="warp")return`warp:${P.Warp}`;if(i==="brand")return`brand:${P.Brand}`;if(i==="abi")return`abi:${P.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${i}`)},b=(i,t)=>i?.actions[t-1],It=i=>({name:i.name.toString(),displayName:i.display_name.toString(),chainId:i.chain_id.toString(),blockTime:i.block_time.toNumber(),addressHrp:i.address_hrp.toString(),apiUrl:i.api_url.toString(),explorerUrl:i.explorer_url.toString(),nativeToken:i.native_token.toString()}),K=(i,t)=>{let r=i.toString(),[e,n=""]=r.split("."),a=Math.abs(t);if(t>0)return BigInt(e+n.padEnd(a,"0"));if(t<0){let o=e+n;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=(i,t=100)=>{if(!i)return"";let r=i.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},J=(i,t)=>i.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),Y=(i,t)=>{let r=Object.entries(i.messages||{}).map(([e,n])=>[e,J(n,t)]);return Object.fromEntries(r)};var T=i=>{let t=decodeURIComponent(i);if(t.includes(l.IdentifierParamSeparator)){let[e,n]=t.split(l.IdentifierParamSeparator),a=n.split("?")[0];return{type:e,identifier:n,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=i=>{let t=new URL(i),r=h.SuperClientUrls.includes(t.origin),e=t.searchParams.get(l.IdentifierParamName),n=r&&!e?t.pathname.split("/")[1]:e;if(!n)return null;let a=decodeURIComponent(n);return T(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||h.DefaultClientUrl(this.config.env),n=t===l.IdentifierType.Alias?encodeURIComponent(r):encodeURIComponent(t+l.IdentifierParamSeparator+r);return h.SuperClientUrls.includes(e)?`${e}/${n}`:`${e}?${l.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let r=T(t);return r?this.build(r.type,r.identifierBase):""}generateQrCode(t,r,e=512,n="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:n},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=(i,t,r,e)=>{let n=t.actions?.[r]?.next||t.next||null;if(!n)return null;if(n.startsWith(ot))return[{identifier:null,url:n}];let[a,o]=n.split("?");if(!o)return[{identifier:a,url:Q(a,i)}];let s=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(s.length===0){let f=J(o,{...t.vars,...e}),m=f?`${a}?${f}`:a;return[{identifier:m,url:Q(m,i)}]}let c=s[0];if(!c)return[];let p=c.match(/{{([^[]+)\[\]/),u=p?p[1]:null;if(!u||e[u]===void 0)return[];let g=Array.isArray(e[u])?e[u]:[e[u]];if(g.length===0)return[];let W=s.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let m=f.match(/\[\](\.[^}]+)?}}/),d=m&&m[1]||"";return{placeholder:f,field:d?d.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return g.map(f=>{let m=o;for(let{regex:v,field:S}of W){let C=S?st(f,S):f;if(C==null)return null;m=m.replace(v,C)}if(m.includes("{{")||m.includes("}}"))return null;let d=m?`${a}?${m}`:a;return{identifier:d,url:Q(d,i)}}).filter(f=>f!==null)},Q=(i,t)=>{let[r,e]=i.split("?"),n=T(r)||{type:"alias",identifier:r,identifierBase:r},o=new O(t).build(n.type,n.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=(i,t)=>t.split(".").reduce((r,e)=>r?.[e],i);var R=class R{static info(...t){R.isTestEnv||console.info(...t)}static warn(...t){R.isTestEnv||console.warn(...t)}static error(...t){R.isTestEnv||console.error(...t)}};R.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=R;var w=class{nativeToString(t,r){return`${t}:${r?.toString()??""}`}stringToNative(t){let r=t.split(l.ArgParamsSeparator),e=r[0],n=r.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[a,o]=n.split(l.ArgParamsSeparator);return[`option:${a}`,o||null]}else if(e==="optional"){let[a,o]=n.split(l.ArgParamsSeparator);return[`optional:${a}`,o||null]}else if(e==="list"){let a=n.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=n.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=n.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[p]}:${c}`)[1]);return[e,s]}else{if(e==="string")return[e,n];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(n)];if(e==="uint64"||e==="biguint")return[e,BigInt(n||0)];if(e==="bool")return[e,n==="true"];if(e==="address")return[e,n];if(e==="token")return[e,n];if(e==="hex")return[e,n];if(e==="codemeta")return[e,n];if(e==="esdt"){let[a,o,s]=n.split(l.ArgCompositeSeparator);return[e,`${a}|${o}|${s}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var tt=async(i,t,r,e)=>{let n=[],a={};for(let[o,s]of Object.entries(i.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("."),g=(W,E)=>E.reduce((f,m)=>f&&f[m]!==void 0?f[m]:null,W);if(p==="out"||p.startsWith("out[")){let W=u.length===0?t?.data||t:g(t,u);n.push(W),a[o]=W}else a[o]=s}return{values:n,results:await pt(i,a,r,e)}},pt=async(i,t,r,e)=>{if(!i.results)return t;let n={...t};return n=lt(n,i,r,e),n=await ct(i,n),n},lt=(i,t,r,e)=>{let n={...i},a=b(t,r)?.inputs||[],o=new w;for(let[s,c]of Object.entries(n))if(typeof c=="string"&&c.startsWith("input.")){let p=c.split(".")[1],u=a.findIndex(W=>W.as===p||W.name===p),g=u!==-1?e[u]?.value:null;n[s]=g?o.stringToNative(g)[1]:null}return n},ct=async(i,t)=>{if(!i.results)return t;let r={...t},e=Object.entries(i.results).filter(([,n])=>n.startsWith(l.Transform.Prefix)).map(([n,a])=>({key:n,code:a.substring(l.Transform.Prefix.length)}));for(let{key:n,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[n]=await o(a,r)}catch(o){y.error(`Transform error for result '${n}':`,o),r[n]=null}return r},ut=i=>{if(i==="out")return 1;let t=i.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(i.startsWith("out.")||i.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=i=>dt.find(t=>t.id===i)||null;var or=i=>`${I.String}:${i}`,sr=i=>`${I.U8}:${i}`,pr=i=>`${I.U16}:${i}`,lr=i=>`${I.U32}:${i}`,cr=i=>`${I.U64}:${i}`,ur=i=>`${I.Biguint}:${i}`,dr=i=>`${I.Boolean}:${i}`,fr=i=>`${I.Address}:${i}`,mr=i=>`${I.Hex}:${i}`;import ft from"ajv";var rt=class{constructor(t){this.pendingBrand={protocol:q("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||h.LatestBrandSchemaUrl,n=await(await fetch(r)).json(),a=new ft,o=a.compile(n);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};import mt 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(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(n,a)=>{n&&Object.keys(n).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 n=t.actions.some(o=>o.abi),a=Object.values(t.results||{}).some(o=>o.startsWith("out.")||o.startsWith("event."));return t.results&&!n&&a?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||h.LatestWarpSchemaUrl,n=await(await fetch(r)).json(),a=new mt({strict:!1}),o=a.compile(n);return o(t)?[]:[`Schema validation failed: ${a.errorsText(o.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var D=class{constructor(t){this.config=t;this.pendingWarp={protocol:q("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 n={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r?.startsWith(this.prefix)&&localStorage.removeItem(r)}}};var A=class A{get(t){let r=A.cache.get(t);return r?Date.now()>r.expiresAt?(A.cache.delete(t),null):r.value:null}set(t,r,e){let n=Date.now()+e*1e3;A.cache.set(t,{value:r,expiresAt:n})}forget(t){A.cache.delete(t)}clear(){A.cache.clear()}};A.cache=new Map;var L=A;var H={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:(i,t)=>`warp:${i}:${t}`,WarpAbi:(i,t)=>`warp-abi:${i}:${t}`,WarpExecutable:(i,t,r)=>`warp-exec:${i}:${t}:${r}`,RegistryInfo:(i,t)=>`registry-info:${i}:${t}`,Brand:(i,t)=>`brand:${i}:${t}`,ChainInfo:(i,t)=>`chain:${i}:${t}`,ChainInfos:i=>`chains:${i}`},j=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new V:t==="memory"?new L:typeof window<"u"&&window.localStorage?new V:new L}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{static async getChainInfoForAction(t,r,e){if(e){let n=await this.tryGetChainFromInputs(t,r,e);if(n)return n}return this.getDefaultChainInfo(t,r)}static async tryGetChainFromInputs(t,r,e){let n=r.inputs?.findIndex(p=>p.position==="chain");if(n===-1||n===void 0)return null;let a=e[n];if(!a)throw new Error("WarpUtils: Chain input not found");let s=new w().stringToNative(a)[1],c=await t.repository.registry.getChainInfo(s);if(!c)throw new Error(`WarpUtils: Chain info not found for ${s}`);return c}static async getDefaultChainInfo(t,r){if(!r.chain)return U(t);let e=await t.repository.registry.getChainInfo(r.chain,{ttl:H.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${r.chain}`);return e}};var F=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 w,this.cache=new j(t.cache?.type)}async createExecutable(t,r,e){let n=b(t,r);if(!n)throw new Error("WarpFactory: Action not found");let a=await B.getChainInfoForAction(this.config,n,e),o=await this.getResolvedInputs(a,n,e),s=this.getModifiedInputs(o),c=s.find(x=>x.input.position==="receiver")?.value,p="address"in n?n.address:null,u=c?.split(":")[1]||p;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let g=u,W=this.getPreparedArgs(n,s),E=s.find(x=>x.input.position==="value")?.value||null,f="value"in n?n.value:null,m=BigInt(E?.split(":")[1]||f||0),d=s.filter(x=>x.input.position==="transfer"&&x.value).map(x=>x.value),S=[...("transfers"in n?n.transfers:[])||[],...d||[]],C=s.find(x=>x.input.position==="data")?.value,z="data"in n?n.data||"":null,_={warp:t,chain:a,action:r,destination:g,args:W,value:m,transfers:S,data:C||z||null,resolvedInputs:s};return this.cache.set(et.WarpExecutable(this.config.env,t.meta?.hash||"",r),_.resolvedInputs,H.OneWeek),_}determineAction(t,r){let e=t.actions.filter(o=>o.type!=="link"),n=this.config.preferredChain?.toLowerCase(),a=1;if(n){let o=e.findIndex(s=>s.chain?.toLowerCase()===n);o!==-1&&(a=o)}return[b(t,a),a]}async getResolvedInputs(t,r,e){let n=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 n.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[,n]=r.input.modifier.split(":");if(isNaN(Number(n))){let a=Number(t.find(c=>c.input.name===n)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let o=r.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let s=K(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=K(a,+n);return{...r,value:`${r.input.type}:${o}`}}}else return r})}async preprocessInput(t,r){try{let[e,n]=r.split(l.ArgParamsSeparator,2),a=this.config.adapters.find(o=>o.chain===t.name)?.executor;return a?a.preprocessInput(t,r,e,n):r}catch{return r}}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:n,value:a})=>{if(!a||!n.position?.startsWith("arg:"))return;let o=Number(n.position.split(":")[1])-1;e.splice(o,0,a)}),e}};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 n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r){if(!r?.vars)return r;let e=JSON.stringify(r),n=(a,o)=>{e=e.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(r.vars).forEach(([a,o])=>{if(typeof o!="string")n(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&&n(a,c)}else if(o.startsWith(`${l.Vars.Env}:`)){let s=o.split(`${l.Vars.Env}:`)[1],c=t.vars?.[s];c&&n(a,c)}else o===l.Source.UserWallet&&t.user?.wallet?n(a,t.user.wallet):n(a,o)}),JSON.parse(e)}async applyRootGlobals(t,r){let e=JSON.stringify(t),n={config:r,chain:U(r)};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(n);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),n={config:this.config,chain:r};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(n);o!=null&&(e=e.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(e)}};var M=class{constructor(t,r){this.config=t;this.handlers=r;this.factory=new F(t),this.interpolator=new $(t,t.repository),this.handlers=r}async execute(t,r){let[e,n]=this.factory.determineAction(t,r);if(e.type==="collect"){let p=await this.executeCollect(t,n,r);return this.handlers?.onExecuted?.(p),[null,null]}let a=await this.factory.createExecutable(t,n,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 n=this.config.adapters.find(o=>o.chain.toLowerCase()===r.name.toLowerCase());if(!n)throw new Error(`No adapter registered for chain: ${r.name}`);let a=await n.results.getTransactionExecutionResults(t,1,e);this.handlers?.onExecuted?.(a)}async executeCollect(t,r,e,n){let a=b(t,r);if(!a)throw new Error("WarpActionExecutor: Action not found");let o=await B.getChainInfoForAction(this.config,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,g=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 E=Object.fromEntries(p.map(d=>[d.input.as||d.input.name,g(d)])),f=a.destination.method||"GET",m=f==="GET"?void 0:JSON.stringify({...E,...n});y.info("Executing collect",{url:a.destination.url,method:f,headers:W,body:m});try{let d=await fetch(a.destination.url,{method:f,headers:W,body:m}),v=await d.json(),{values:S,results:C}=await tt(s,v,r,p),z=Z(this.config,s,r,C);return{success:d.ok,warp:s,action:r,user:this.config.user?.wallet||null,txHash:null,next:z,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 G=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 n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),o=(await Promise.all(n)).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},n=t.startsWith(l.HttpProtocolPrefix)?N(t):T(t);if(!n)return e;try{let{type:a,identifierBase:o}=n,s=null,c=null,p=null;if(a==="hash"){s=await this.repository.builder.createFromTransactionHash(o,r);let g=await this.repository.registry.getInfoByHash(o,r);c=g.registryInfo,p=g.brand}else if(a==="alias"){let g=await this.repository.registry.getInfoByAlias(o,r);c=g.registryInfo,p=g.brand,g.registryInfo&&(s=await this.repository.builder.createFromTransactionHash(g.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}createBuilder(){return new D(this.config)}async detectWarp(t,r){return new G(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)}async executeWarp(t,r){return this.executor.execute(t,r)}get registry(){return this.config.repository.registry}get executor(){return new M(this.config)}};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 n=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw y.error("WarpIndex: Error searching for warps: ",n),n}}};export{H as CacheTtl,dt as KnownTokens,rt as WarpBrandBuilder,D as WarpBuilder,j as WarpCache,et as WarpCacheKey,nt as WarpClient,h as WarpConfig,l as WarpConstants,M as WarpExecutor,F as WarpFactory,it as WarpIndex,I as WarpInputTypes,$ as WarpInterpolator,O as WarpLinkBuilder,G as WarpLinkDetecter,y as WarpLogger,P as WarpProtocolVersions,w as WarpSerializer,B as WarpUtils,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,xt as getChainExplorerUrl,q as getLatestProtocolIdentifier,U as getMainChainInfo,Z as getNextInfo,b as getWarpActionByIndex,T as getWarpInfoFromIdentifier,mr as hex,ut as parseResultsOutIndex,J as replacePlaceholders,K as shiftBigintBy,or as string,X as toPreviewText,It as toTypedChainInfo,pr as u16,lr as u32,cr as u64,sr as u8};
|