@vleap/warps 3.0.0-alpha.85 → 3.0.0-alpha.87

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.
@@ -0,0 +1,877 @@
1
+ import QRCodeStyling from 'qr-code-styling';
2
+
3
+ type WarpChainAccount = {
4
+ chain: WarpChain;
5
+ address: string;
6
+ balance: bigint;
7
+ };
8
+ type WarpChainAssetValue = {
9
+ identifier: string;
10
+ nonce: bigint;
11
+ amount: bigint;
12
+ };
13
+ type WarpChainAsset = {
14
+ chain: WarpChain;
15
+ identifier: string;
16
+ name: string;
17
+ nonce?: bigint;
18
+ amount?: bigint;
19
+ decimals?: number;
20
+ logoUrl?: string;
21
+ };
22
+ type WarpChainAction = {
23
+ chain: WarpChain;
24
+ id: string;
25
+ sender: string;
26
+ receiver: string;
27
+ value: bigint;
28
+ function: string;
29
+ status: WarpChainActionStatus;
30
+ createdAt: string;
31
+ };
32
+ type WarpChainActionStatus = 'pending' | 'success' | 'failed';
33
+
34
+ type WarpChain = string;
35
+ type WarpExplorerName = string;
36
+ type WarpChainInfo = {
37
+ name: string;
38
+ displayName: string;
39
+ chainId: string;
40
+ blockTime: number;
41
+ addressHrp: string;
42
+ defaultApiUrl: string;
43
+ nativeToken: WarpChainAsset;
44
+ };
45
+ type WarpIdType = 'hash' | 'alias';
46
+ type WarpVarPlaceholder = string;
47
+ type WarpResultName = string;
48
+ type WarpResulutionPath = string;
49
+ type WarpMessageName = string;
50
+ type Warp = {
51
+ protocol: string;
52
+ name: string;
53
+ title: string;
54
+ description: string | null;
55
+ bot?: string;
56
+ preview?: string;
57
+ vars?: Record<WarpVarPlaceholder, string>;
58
+ actions: WarpAction[];
59
+ next?: string;
60
+ results?: Record<WarpResultName, WarpResulutionPath>;
61
+ messages?: Record<WarpMessageName, string>;
62
+ meta?: WarpMeta;
63
+ };
64
+ type WarpMeta = {
65
+ chain: WarpChain;
66
+ hash: string;
67
+ creator: string;
68
+ createdAt: string;
69
+ };
70
+ type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpLinkAction;
71
+ type WarpActionIndex = number;
72
+ type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link';
73
+ type WarpTransferAction = {
74
+ type: WarpActionType;
75
+ chain?: WarpChain;
76
+ label: string;
77
+ description?: string | null;
78
+ address?: string;
79
+ data?: string;
80
+ value?: string;
81
+ transfers?: string[];
82
+ inputs?: WarpActionInput[];
83
+ next?: string;
84
+ };
85
+ type WarpContractAction = {
86
+ type: WarpActionType;
87
+ chain?: WarpChain;
88
+ label: string;
89
+ description?: string | null;
90
+ address?: string;
91
+ func?: string | null;
92
+ args?: string[];
93
+ value?: string;
94
+ gasLimit: number;
95
+ transfers?: string[];
96
+ abi?: string;
97
+ inputs?: WarpActionInput[];
98
+ next?: string;
99
+ };
100
+ type WarpQueryAction = {
101
+ type: WarpActionType;
102
+ chain?: WarpChain;
103
+ label: string;
104
+ description?: string | null;
105
+ address?: string;
106
+ func?: string;
107
+ args?: string[];
108
+ abi?: string;
109
+ inputs?: WarpActionInput[];
110
+ next?: string;
111
+ };
112
+ type WarpCollectAction = {
113
+ type: WarpActionType;
114
+ chain?: WarpChain;
115
+ label: string;
116
+ description?: string | null;
117
+ destination: {
118
+ url: string;
119
+ method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
120
+ headers?: Record<string, string>;
121
+ };
122
+ inputs?: WarpActionInput[];
123
+ next?: string;
124
+ };
125
+ type WarpLinkAction = {
126
+ type: WarpActionType;
127
+ chain?: WarpChain;
128
+ label: string;
129
+ description?: string | null;
130
+ url: string;
131
+ inputs?: WarpActionInput[];
132
+ };
133
+ type WarpActionInputSource = 'field' | 'query' | 'user:wallet';
134
+ type BaseWarpActionInputType = 'string' | 'uint8' | 'uint16' | 'uint32' | 'uint64' | 'uint128' | 'uint256' | 'biguint' | 'bool' | 'address' | 'hex' | string;
135
+ type WarpActionInputType = string;
136
+ type WarpNativeValue = string | number | bigint | boolean | WarpChainAssetValue | null | WarpNativeValue[];
137
+ type WarpActionInputPosition = 'receiver' | 'value' | 'transfer' | `arg:${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10}` | 'data' | 'chain';
138
+ type WarpActionInputModifier = 'scale';
139
+ type WarpActionInput = {
140
+ name: string;
141
+ as?: string;
142
+ description?: string | null;
143
+ bot?: string;
144
+ type: WarpActionInputType;
145
+ position?: WarpActionInputPosition;
146
+ source: WarpActionInputSource;
147
+ required?: boolean;
148
+ min?: number | WarpVarPlaceholder;
149
+ max?: number | WarpVarPlaceholder;
150
+ pattern?: string;
151
+ patternDescription?: string;
152
+ options?: string[] | {
153
+ [key: string]: string;
154
+ };
155
+ modifier?: string;
156
+ default?: string | number | boolean;
157
+ };
158
+ type ResolvedInput = {
159
+ input: WarpActionInput;
160
+ value: string | null;
161
+ };
162
+ type WarpContract = {
163
+ address: string;
164
+ owner: string;
165
+ verified: boolean;
166
+ };
167
+ type WarpContractVerification = {
168
+ codeHash: string;
169
+ abi: object;
170
+ };
171
+ type WarpExecutable = {
172
+ chain: WarpChainInfo;
173
+ warp: Warp;
174
+ action: number;
175
+ destination: string;
176
+ args: string[];
177
+ value: bigint;
178
+ transfers: WarpChainAssetValue[];
179
+ data: string | null;
180
+ resolvedInputs: ResolvedInput[];
181
+ };
182
+
183
+ type WarpAbi = {
184
+ protocol: string;
185
+ content: WarpAbiContents;
186
+ meta?: WarpMeta;
187
+ };
188
+ type WarpAbiContents = {
189
+ name?: string;
190
+ constructor?: any;
191
+ upgradeConstructor?: any;
192
+ endpoints?: any[];
193
+ types?: Record<string, any>;
194
+ events?: any[];
195
+ };
196
+
197
+ type WarpBrand = {
198
+ protocol: string;
199
+ name: string;
200
+ description: string;
201
+ logo: string;
202
+ urls?: WarpBrandUrls;
203
+ colors?: WarpBrandColors;
204
+ cta?: WarpBrandCta;
205
+ meta?: WarpBrandMeta;
206
+ };
207
+ type WarpBrandUrls = {
208
+ web?: string;
209
+ };
210
+ type WarpBrandColors = {
211
+ primary?: string;
212
+ secondary?: string;
213
+ };
214
+ type WarpBrandCta = {
215
+ title: string;
216
+ description: string;
217
+ label: string;
218
+ url: string;
219
+ };
220
+ type WarpBrandMeta = {
221
+ hash: string;
222
+ creator: string;
223
+ createdAt: string;
224
+ };
225
+
226
+ type ClientCacheConfig = {
227
+ ttl?: number;
228
+ type?: WarpCacheType;
229
+ };
230
+ type WarpCacheType = 'memory' | 'localStorage';
231
+
232
+ type WarpChainEnv = 'mainnet' | 'testnet' | 'devnet';
233
+ type ProtocolName = 'warp' | 'brand' | 'abi';
234
+
235
+ type WarpTrustStatus = 'unverified' | 'verified' | 'blacklisted';
236
+ type WarpRegistryInfo = {
237
+ hash: string;
238
+ alias: string | null;
239
+ trust: WarpTrustStatus;
240
+ owner: string;
241
+ createdAt: number;
242
+ upgradedAt: number;
243
+ brand: string | null;
244
+ upgrade: string | null;
245
+ };
246
+ type WarpRegistryConfigInfo = {
247
+ unitPrice: bigint;
248
+ admins: string[];
249
+ };
250
+
251
+ type WarpExecution = {
252
+ success: boolean;
253
+ warp: Warp;
254
+ action: number;
255
+ user: string | null;
256
+ txHash: string | null;
257
+ tx: WarpAdapterGenericTransaction | null;
258
+ next: WarpExecutionNextInfo | null;
259
+ values: any[];
260
+ valuesRaw: any[];
261
+ results: WarpExecutionResults;
262
+ messages: WarpExecutionMessages;
263
+ };
264
+ type WarpExecutionNextInfo = {
265
+ identifier: string | null;
266
+ url: string;
267
+ }[];
268
+ type WarpExecutionResults = Record<WarpResultName, any | null>;
269
+ type WarpExecutionMessages = Record<WarpMessageName, string | null>;
270
+
271
+ type ClientIndexConfig = {
272
+ url?: string;
273
+ apiKey?: string;
274
+ searchParamName?: string;
275
+ };
276
+ type WarpSearchResult = {
277
+ hits: WarpSearchHit[];
278
+ };
279
+ type WarpSearchHit = {
280
+ hash: string;
281
+ alias: string;
282
+ name: string;
283
+ title: string;
284
+ description: string;
285
+ preview: string;
286
+ status: string;
287
+ category: string;
288
+ featured: boolean;
289
+ };
290
+
291
+ interface TransformRunner {
292
+ run(code: string, context: any): Promise<any>;
293
+ }
294
+ type ClientTransformConfig = {
295
+ runner?: TransformRunner | null;
296
+ };
297
+
298
+ type WarpUserWallets = Record<WarpChain, string | null>;
299
+ type WarpProviderConfig = Record<WarpChainEnv, string>;
300
+ type WarpClientConfig = {
301
+ env: WarpChainEnv;
302
+ clientUrl?: string;
303
+ currentUrl?: string;
304
+ vars?: Record<string, string | number>;
305
+ user?: {
306
+ wallets?: WarpUserWallets;
307
+ };
308
+ preferences?: {
309
+ explorers?: Record<WarpChain, WarpExplorerName>;
310
+ };
311
+ providers?: Record<WarpChain, WarpProviderConfig>;
312
+ schema?: {
313
+ warp?: string;
314
+ brand?: string;
315
+ };
316
+ cache?: ClientCacheConfig;
317
+ transform?: ClientTransformConfig;
318
+ index?: ClientIndexConfig;
319
+ };
320
+ type WarpCacheConfig = {
321
+ ttl?: number;
322
+ };
323
+ type AdapterFactory = (config: WarpClientConfig, fallback?: Adapter) => Adapter;
324
+ type Adapter = {
325
+ chainInfo: WarpChainInfo;
326
+ prefix: string;
327
+ builder: () => CombinedWarpBuilder;
328
+ executor: AdapterWarpExecutor;
329
+ results: AdapterWarpResults;
330
+ serializer: AdapterWarpSerializer;
331
+ registry: AdapterWarpRegistry;
332
+ explorer: AdapterWarpExplorer;
333
+ abiBuilder: () => AdapterWarpAbiBuilder;
334
+ brandBuilder: () => AdapterWarpBrandBuilder;
335
+ dataLoader: AdapterWarpDataLoader;
336
+ registerTypes?: (typeRegistry: WarpTypeRegistry) => void;
337
+ };
338
+ type WarpAdapterGenericTransaction = any;
339
+ type WarpAdapterGenericRemoteTransaction = any;
340
+ type WarpAdapterGenericValue = any;
341
+ type WarpAdapterGenericType = any;
342
+ interface WarpTypeHandler {
343
+ stringToNative(value: string): any;
344
+ nativeToString(value: any): string;
345
+ }
346
+ interface WarpTypeRegistry {
347
+ registerType(typeName: string, handler: WarpTypeHandler): void;
348
+ hasType(typeName: string): boolean;
349
+ getHandler(typeName: string): WarpTypeHandler | undefined;
350
+ getRegisteredTypes(): string[];
351
+ }
352
+ interface BaseWarpBuilder {
353
+ createFromRaw(encoded: string): Promise<Warp>;
354
+ createFromUrl(url: string): Promise<Warp>;
355
+ setName(name: string): BaseWarpBuilder;
356
+ setTitle(title: string): BaseWarpBuilder;
357
+ setDescription(description: string): BaseWarpBuilder;
358
+ setPreview(preview: string): BaseWarpBuilder;
359
+ setActions(actions: WarpAction[]): BaseWarpBuilder;
360
+ addAction(action: WarpAction): BaseWarpBuilder;
361
+ build(): Promise<Warp>;
362
+ }
363
+ interface AdapterWarpBuilder {
364
+ createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
365
+ createFromTransaction(tx: WarpAdapterGenericTransaction, validate?: boolean): Promise<Warp>;
366
+ createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
367
+ }
368
+ type CombinedWarpBuilder = AdapterWarpBuilder & BaseWarpBuilder;
369
+ interface AdapterWarpAbiBuilder {
370
+ createFromRaw(encoded: string): Promise<any>;
371
+ createFromTransaction(tx: WarpAdapterGenericTransaction): Promise<any>;
372
+ createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<any | null>;
373
+ }
374
+ interface AdapterWarpBrandBuilder {
375
+ createInscriptionTransaction(brand: WarpBrand): WarpAdapterGenericTransaction;
376
+ createFromTransaction(tx: WarpAdapterGenericTransaction, validate?: boolean): Promise<WarpBrand>;
377
+ createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<WarpBrand | null>;
378
+ }
379
+ interface AdapterWarpExecutor {
380
+ createTransaction(executable: WarpExecutable): Promise<WarpAdapterGenericTransaction>;
381
+ executeQuery(executable: WarpExecutable): Promise<WarpExecution>;
382
+ preprocessInput(chain: WarpChainInfo, input: string, type: WarpActionInputType, value: string): Promise<string>;
383
+ signMessage(message: string, privateKey: string): Promise<string>;
384
+ }
385
+ interface AdapterWarpResults {
386
+ getTransactionExecutionResults(warp: Warp, tx: WarpAdapterGenericRemoteTransaction): Promise<WarpExecution>;
387
+ }
388
+ interface AdapterWarpSerializer {
389
+ typedToString(value: WarpAdapterGenericValue): string;
390
+ typedToNative(value: WarpAdapterGenericValue): [WarpActionInputType, WarpNativeValue];
391
+ nativeToTyped(type: WarpActionInputType, value: WarpNativeValue): WarpAdapterGenericValue;
392
+ nativeToType(type: BaseWarpActionInputType): WarpAdapterGenericType;
393
+ stringToTyped(value: string): WarpAdapterGenericValue;
394
+ }
395
+ interface AdapterWarpRegistry {
396
+ init(): Promise<void>;
397
+ getRegistryConfig(): WarpRegistryConfigInfo;
398
+ createWarpRegisterTransaction(txHash: string, alias?: string | null, brand?: string | null): Promise<WarpAdapterGenericTransaction>;
399
+ createWarpUnregisterTransaction(txHash: string): Promise<WarpAdapterGenericTransaction>;
400
+ createWarpUpgradeTransaction(alias: string, txHash: string): Promise<WarpAdapterGenericTransaction>;
401
+ createWarpAliasSetTransaction(txHash: string, alias: string): Promise<WarpAdapterGenericTransaction>;
402
+ createWarpVerifyTransaction(txHash: string): Promise<WarpAdapterGenericTransaction>;
403
+ createWarpTransferOwnershipTransaction(txHash: string, newOwner: string): Promise<WarpAdapterGenericTransaction>;
404
+ createBrandRegisterTransaction(txHash: string): Promise<WarpAdapterGenericTransaction>;
405
+ createWarpBrandingTransaction(warpHash: string, brandHash: string): Promise<WarpAdapterGenericTransaction>;
406
+ getInfoByAlias(alias: string, cache?: WarpCacheConfig): Promise<{
407
+ registryInfo: WarpRegistryInfo | null;
408
+ brand: WarpBrand | null;
409
+ }>;
410
+ getInfoByHash(hash: string, cache?: WarpCacheConfig): Promise<{
411
+ registryInfo: WarpRegistryInfo | null;
412
+ brand: WarpBrand | null;
413
+ }>;
414
+ getUserWarpRegistryInfos(user?: string): Promise<WarpRegistryInfo[]>;
415
+ getUserBrands(user?: string): Promise<WarpBrand[]>;
416
+ fetchBrand(hash: string, cache?: WarpCacheConfig): Promise<WarpBrand | null>;
417
+ }
418
+ interface AdapterWarpExplorer {
419
+ getAccountUrl(address: string): string;
420
+ getTransactionUrl(hash: string): string;
421
+ getAssetUrl(identifier: string): string;
422
+ getContractUrl(address: string): string;
423
+ }
424
+ interface WarpDataLoaderOptions {
425
+ page?: number;
426
+ size?: number;
427
+ }
428
+ interface AdapterWarpDataLoader {
429
+ getAccount(address: string): Promise<WarpChainAccount>;
430
+ getAccountAssets(address: string): Promise<WarpChainAsset[]>;
431
+ getAccountActions(address: string, options?: WarpDataLoaderOptions): Promise<WarpChainAction[]>;
432
+ }
433
+
434
+ declare enum WarpChainName {
435
+ Multiversx = "multiversx",
436
+ Vibechain = "vibechain",
437
+ Sui = "sui",
438
+ Ethereum = "ethereum",
439
+ Base = "base",
440
+ Arbitrum = "arbitrum",
441
+ Fastset = "fastset"
442
+ }
443
+ declare const WarpConstants: {
444
+ HttpProtocolPrefix: string;
445
+ IdentifierParamName: string;
446
+ IdentifierParamSeparator: string[];
447
+ IdentifierParamSeparatorDefault: string;
448
+ IdentifierChainDefault: string;
449
+ IdentifierType: {
450
+ Alias: WarpIdType;
451
+ Hash: WarpIdType;
452
+ };
453
+ Source: {
454
+ UserWallet: string;
455
+ };
456
+ Globals: {
457
+ UserWallet: {
458
+ Placeholder: string;
459
+ Accessor: (bag: InterpolationBag) => string | null | undefined;
460
+ };
461
+ ChainApiUrl: {
462
+ Placeholder: string;
463
+ Accessor: (bag: InterpolationBag) => string;
464
+ };
465
+ ChainAddressHrp: {
466
+ Placeholder: string;
467
+ Accessor: (bag: InterpolationBag) => string;
468
+ };
469
+ };
470
+ Vars: {
471
+ Query: string;
472
+ Env: string;
473
+ };
474
+ ArgParamsSeparator: string;
475
+ ArgCompositeSeparator: string;
476
+ Transform: {
477
+ Prefix: string;
478
+ };
479
+ };
480
+ declare const WarpInputTypes: {
481
+ Option: string;
482
+ Optional: string;
483
+ List: string;
484
+ Variadic: string;
485
+ Composite: string;
486
+ String: string;
487
+ U8: string;
488
+ U16: string;
489
+ U32: string;
490
+ U64: string;
491
+ U128: string;
492
+ U256: string;
493
+ Biguint: string;
494
+ Boolean: string;
495
+ Address: string;
496
+ Asset: string;
497
+ Hex: string;
498
+ };
499
+
500
+ type InterpolationBag = {
501
+ config: WarpClientConfig;
502
+ chain: WarpChainName;
503
+ chainInfo: WarpChainInfo;
504
+ };
505
+
506
+ declare const WarpProtocolVersions: {
507
+ Warp: string;
508
+ Brand: string;
509
+ Abi: string;
510
+ };
511
+ declare const WarpConfig: {
512
+ LatestWarpSchemaUrl: string;
513
+ LatestBrandSchemaUrl: string;
514
+ DefaultClientUrl: (env: WarpChainEnv) => "https://usewarp.to" | "https://testnet.usewarp.to" | "https://devnet.usewarp.to";
515
+ DefaultChainPrefix: string;
516
+ SuperClientUrls: string[];
517
+ AvailableActionInputSources: WarpActionInputSource[];
518
+ AvailableActionInputTypes: WarpActionInputType[];
519
+ AvailableActionInputPositions: WarpActionInputPosition[];
520
+ };
521
+
522
+ interface CryptoProvider {
523
+ getRandomBytes(size: number): Promise<Uint8Array>;
524
+ }
525
+ declare class BrowserCryptoProvider implements CryptoProvider {
526
+ getRandomBytes(size: number): Promise<Uint8Array>;
527
+ }
528
+ declare class NodeCryptoProvider implements CryptoProvider {
529
+ getRandomBytes(size: number): Promise<Uint8Array>;
530
+ }
531
+ declare function getCryptoProvider(): CryptoProvider;
532
+ declare function setCryptoProvider(provider: CryptoProvider): void;
533
+ declare function getRandomBytes(size: number, cryptoProvider?: CryptoProvider): Promise<Uint8Array>;
534
+ declare function bytesToHex(bytes: Uint8Array): string;
535
+ declare function bytesToBase64(bytes: Uint8Array): string;
536
+ declare function getRandomHex(length: number, cryptoProvider?: CryptoProvider): Promise<string>;
537
+ declare function testCryptoAvailability(): Promise<{
538
+ randomBytes: boolean;
539
+ environment: 'browser' | 'nodejs' | 'unknown';
540
+ }>;
541
+ declare function createCryptoProvider(): CryptoProvider;
542
+
543
+ declare const findWarpAdapterForChain: (chain: WarpChain, adapters: Adapter[]) => Adapter;
544
+ declare const findWarpAdapterByPrefix: (prefix: string, adapters: Adapter[]) => Adapter;
545
+ declare const getLatestProtocolIdentifier: (name: ProtocolName) => string;
546
+ declare const getWarpActionByIndex: (warp: Warp, index: number) => WarpAction;
547
+ declare const findWarpExecutableAction: (warp: Warp) => {
548
+ action: WarpAction;
549
+ actionIndex: WarpActionIndex;
550
+ };
551
+ declare const shiftBigintBy: (value: bigint | string | number, decimals: number) => bigint;
552
+ declare const toPreviewText: (text: string, maxChars?: number) => string;
553
+ declare const replacePlaceholders: (message: string, bag: Record<string, any>) => string;
554
+ declare const applyResultsToMessages: (warp: Warp, results: Record<string, any>) => Record<string, string>;
555
+
556
+ declare const getWarpInfoFromIdentifier: (prefixedIdentifier: string) => {
557
+ chainPrefix: string;
558
+ type: WarpIdType;
559
+ identifier: string;
560
+ identifierBase: string;
561
+ } | null;
562
+ declare const extractIdentifierInfoFromUrl: (url: string) => {
563
+ chainPrefix: string;
564
+ type: WarpIdType;
565
+ identifier: string;
566
+ identifierBase: string;
567
+ } | null;
568
+
569
+ declare const getNextInfo: (config: WarpClientConfig, adapters: Adapter[], warp: Warp, actionIndex: number, results: WarpExecutionResults) => WarpExecutionNextInfo | null;
570
+
571
+ declare const getProviderUrl: (config: WarpClientConfig, chain: WarpChain, env: WarpChainEnv, defaultProvider: string) => string;
572
+ declare const getProviderConfig: (config: WarpClientConfig, chain: WarpChain) => WarpProviderConfig | undefined;
573
+
574
+ declare const extractCollectResults: (warp: Warp, response: any, actionIndex: number, inputs: ResolvedInput[], transformRunner?: TransformRunner | null) => Promise<{
575
+ values: any[];
576
+ results: WarpExecutionResults;
577
+ }>;
578
+ declare const evaluateResultsCommon: (warp: Warp, baseResults: WarpExecutionResults, actionIndex: number, inputs: ResolvedInput[], transformRunner?: TransformRunner | null) => Promise<WarpExecutionResults>;
579
+ /**
580
+ * Parses out[N] notation and returns the action index (1-based) or null if invalid.
581
+ * Also handles plain "out" which defaults to action index 1.
582
+ */
583
+ declare const parseResultsOutIndex: (resultPath: string) => number | null;
584
+
585
+ /**
586
+ * Signing utilities for creating and validating signed messages
587
+ * Works with any crypto provider or uses automatic detection
588
+ */
589
+
590
+ interface SignableMessage {
591
+ wallet: string;
592
+ nonce: string;
593
+ expiresAt: string;
594
+ purpose: string;
595
+ }
596
+ type HttpAuthHeaders = Record<string, string> & {
597
+ 'X-Signer-Wallet': string;
598
+ 'X-Signer-Signature': string;
599
+ 'X-Signer-Nonce': string;
600
+ 'X-Signer-ExpiresAt': string;
601
+ };
602
+ /**
603
+ * Creates a signable message with standard security fields
604
+ * This can be used for any type of proof or authentication
605
+ */
606
+ declare function createSignableMessage(walletAddress: string, purpose: string, cryptoProvider?: CryptoProvider, expiresInMinutes?: number): Promise<{
607
+ message: string;
608
+ nonce: string;
609
+ expiresAt: string;
610
+ }>;
611
+ /**
612
+ * Creates a signable message for HTTP authentication
613
+ * This is a convenience function that uses the standard format
614
+ */
615
+ declare function createAuthMessage(walletAddress: string, appName: string, cryptoProvider?: CryptoProvider, purpose?: string): Promise<{
616
+ message: string;
617
+ nonce: string;
618
+ expiresAt: string;
619
+ }>;
620
+ /**
621
+ * Creates HTTP authentication headers from a signature
622
+ */
623
+ declare function createAuthHeaders(walletAddress: string, signature: string, nonce: string, expiresAt: string): HttpAuthHeaders;
624
+ /**
625
+ * Creates HTTP authentication headers for a wallet using the provided signing function
626
+ */
627
+ declare function createHttpAuthHeaders(walletAddress: string, signMessage: (message: string) => Promise<string>, appName: string, cryptoProvider?: CryptoProvider): Promise<HttpAuthHeaders>;
628
+ /**
629
+ * Validates a signed message by checking expiration
630
+ */
631
+ declare function validateSignedMessage(expiresAt: string): boolean;
632
+ /**
633
+ * Parses a signed message to extract its components
634
+ */
635
+ declare function parseSignedMessage(message: string): SignableMessage;
636
+
637
+ type KnownToken = {
638
+ id: string;
639
+ name: string;
640
+ decimals: number;
641
+ };
642
+ declare const KnownTokens: KnownToken[];
643
+ declare const findKnownTokenById: (id: string) => KnownToken | null;
644
+
645
+ declare const string: (value: string) => string;
646
+ declare const u8: (value: number) => string;
647
+ declare const u16: (value: number) => string;
648
+ declare const u32: (value: number) => string;
649
+ declare const u64: (value: bigint | number) => string;
650
+ declare const biguint: (value: bigint | string | number) => string;
651
+ declare const boolean: (value: boolean) => string;
652
+ declare const address: (value: string) => string;
653
+ declare const asset: (value: WarpChainAsset) => string;
654
+ declare const hex: (value: string) => string;
655
+
656
+ declare class WarpBrandBuilder {
657
+ private config;
658
+ private pendingBrand;
659
+ constructor(config: WarpClientConfig);
660
+ createFromRaw(encoded: string, validateSchema?: boolean): Promise<WarpBrand>;
661
+ setName(name: string): WarpBrandBuilder;
662
+ setDescription(description: string): WarpBrandBuilder;
663
+ setLogo(logo: string): WarpBrandBuilder;
664
+ setUrls(urls: WarpBrandUrls): WarpBrandBuilder;
665
+ setColors(colors: WarpBrandColors): WarpBrandBuilder;
666
+ setCta(cta: WarpBrandCta): WarpBrandBuilder;
667
+ build(): Promise<WarpBrand>;
668
+ private ensure;
669
+ private ensureValidSchema;
670
+ }
671
+
672
+ declare class WarpBuilder implements BaseWarpBuilder {
673
+ protected readonly config: WarpClientConfig;
674
+ private pendingWarp;
675
+ constructor(config: WarpClientConfig);
676
+ createFromRaw(encoded: string, validate?: boolean): Promise<Warp>;
677
+ createFromUrl(url: string): Promise<Warp>;
678
+ setName(name: string): WarpBuilder;
679
+ setTitle(title: string): WarpBuilder;
680
+ setDescription(description: string): WarpBuilder;
681
+ setPreview(preview: string): WarpBuilder;
682
+ setActions(actions: WarpAction[]): WarpBuilder;
683
+ addAction(action: WarpAction): WarpBuilder;
684
+ build(): Promise<Warp>;
685
+ getDescriptionPreview(description: string, maxChars?: number): string;
686
+ private ensure;
687
+ private validate;
688
+ }
689
+
690
+ declare const CacheTtl: {
691
+ OneMinute: number;
692
+ OneHour: number;
693
+ OneDay: number;
694
+ OneWeek: number;
695
+ OneMonth: number;
696
+ OneYear: number;
697
+ };
698
+ declare const WarpCacheKey: {
699
+ Warp: (env: WarpChainEnv, id: string) => string;
700
+ WarpAbi: (env: WarpChainEnv, id: string) => string;
701
+ WarpExecutable: (env: WarpChainEnv, id: string, action: number) => string;
702
+ RegistryInfo: (env: WarpChainEnv, id: string) => string;
703
+ Brand: (env: WarpChainEnv, hash: string) => string;
704
+ };
705
+ declare class WarpCache {
706
+ private strategy;
707
+ constructor(type?: WarpCacheType);
708
+ private selectStrategy;
709
+ set<T>(key: string, value: T, ttl: number): void;
710
+ get<T>(key: string): T | null;
711
+ forget(key: string): void;
712
+ clear(): void;
713
+ }
714
+
715
+ type ExecutionHandlers = {
716
+ onExecuted?: (result: WarpExecution) => void;
717
+ onError?: (params: {
718
+ message: string;
719
+ }) => void;
720
+ onSignRequest?: (params: {
721
+ message: string;
722
+ chain: WarpChainInfo;
723
+ }) => Promise<string>;
724
+ };
725
+ declare class WarpExecutor {
726
+ private config;
727
+ private adapters;
728
+ private handlers?;
729
+ private factory;
730
+ private serializer;
731
+ constructor(config: WarpClientConfig, adapters: Adapter[], handlers?: ExecutionHandlers | undefined);
732
+ execute(warp: Warp, inputs: string[]): Promise<{
733
+ tx: WarpAdapterGenericTransaction | null;
734
+ chain: WarpChainInfo | null;
735
+ }>;
736
+ evaluateResults(warp: Warp, chain: WarpChain, tx: WarpAdapterGenericRemoteTransaction): Promise<void>;
737
+ private executeCollect;
738
+ }
739
+
740
+ declare class WarpFactory {
741
+ private config;
742
+ private adapters;
743
+ private url;
744
+ private serializer;
745
+ private cache;
746
+ constructor(config: WarpClientConfig, adapters: Adapter[]);
747
+ createExecutable(warp: Warp, actionIndex: number, inputs: string[]): Promise<WarpExecutable>;
748
+ getChainInfoForAction(action: WarpAction, inputs?: string[]): Promise<WarpChainInfo>;
749
+ getResolvedInputs(chain: WarpChain, action: WarpAction, inputArgs: string[]): Promise<ResolvedInput[]>;
750
+ getModifiedInputs(inputs: ResolvedInput[]): ResolvedInput[];
751
+ preprocessInput(chain: WarpChain, input: string): Promise<string>;
752
+ private getPreparedArgs;
753
+ private tryGetChainFromInputs;
754
+ }
755
+
756
+ declare class WarpIndex {
757
+ private config;
758
+ constructor(config: WarpClientConfig);
759
+ search(query: string, params?: Record<string, any>, headers?: Record<string, string>): Promise<WarpSearchHit[]>;
760
+ }
761
+
762
+ declare class WarpLinkBuilder {
763
+ private readonly config;
764
+ private readonly adapters;
765
+ constructor(config: WarpClientConfig, adapters: Adapter[]);
766
+ isValid(url: string): boolean;
767
+ build(chain: WarpChain, type: WarpIdType, id: string): string;
768
+ buildFromPrefixedIdentifier(identifier: string): string | null;
769
+ generateQrCode(chain: WarpChain, type: WarpIdType, id: string, size?: number, background?: string, color?: string, logoColor?: string): QRCodeStyling;
770
+ }
771
+
772
+ type DetectionResult = {
773
+ match: boolean;
774
+ url: string;
775
+ warp: Warp | null;
776
+ chain: WarpChain | null;
777
+ registryInfo: WarpRegistryInfo | null;
778
+ brand: WarpBrand | null;
779
+ };
780
+ type DetectionResultFromHtml = {
781
+ match: boolean;
782
+ results: {
783
+ url: string;
784
+ warp: Warp;
785
+ }[];
786
+ };
787
+ declare class WarpLinkDetecter {
788
+ private config;
789
+ private adapters;
790
+ constructor(config: WarpClientConfig, adapters: Adapter[]);
791
+ isValid(url: string): boolean;
792
+ detectFromHtml(content: string): Promise<DetectionResultFromHtml>;
793
+ detect(url: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
794
+ }
795
+
796
+ declare class WarpClient {
797
+ private config;
798
+ private adapters;
799
+ constructor(config: WarpClientConfig, adapters: Adapter[]);
800
+ getConfig(): WarpClientConfig;
801
+ setConfig(config: WarpClientConfig): WarpClient;
802
+ getAdapters(): Adapter[];
803
+ addAdapter(adapter: Adapter): WarpClient;
804
+ createExecutor(handlers?: ExecutionHandlers): WarpExecutor;
805
+ detectWarp(urlOrId: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
806
+ executeWarp(identifier: string, inputs: string[], handlers?: ExecutionHandlers, options?: {
807
+ cache?: WarpCacheConfig;
808
+ }): Promise<{
809
+ tx: WarpAdapterGenericTransaction | null;
810
+ chain: WarpChainInfo | null;
811
+ evaluateResults: (remoteTx: WarpAdapterGenericRemoteTransaction) => Promise<void>;
812
+ }>;
813
+ createInscriptionTransaction(chain: WarpChain, warp: Warp): WarpAdapterGenericTransaction;
814
+ createFromTransaction(chain: WarpChain, tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
815
+ createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
816
+ signMessage(chain: WarpChain, message: string, privateKey: string): Promise<string>;
817
+ getExplorer(chain: WarpChain): AdapterWarpExplorer;
818
+ getResults(chain: WarpChain): AdapterWarpResults;
819
+ getRegistry(chain: WarpChain): Promise<AdapterWarpRegistry>;
820
+ getDataLoader(chain: WarpChain): AdapterWarpDataLoader;
821
+ get factory(): WarpFactory;
822
+ get index(): WarpIndex;
823
+ get linkBuilder(): WarpLinkBuilder;
824
+ createBuilder(chain: WarpChain): CombinedWarpBuilder;
825
+ createAbiBuilder(chain: WarpChain): AdapterWarpAbiBuilder;
826
+ createBrandBuilder(chain: WarpChain): AdapterWarpBrandBuilder;
827
+ }
828
+
829
+ declare class WarpInterpolator {
830
+ private config;
831
+ private adapter;
832
+ constructor(config: WarpClientConfig, adapter: Adapter);
833
+ apply(config: WarpClientConfig, warp: Warp): Promise<Warp>;
834
+ applyGlobals(config: WarpClientConfig, warp: Warp): Promise<Warp>;
835
+ applyVars(config: WarpClientConfig, warp: Warp): Warp;
836
+ private applyRootGlobals;
837
+ private applyActionGlobals;
838
+ }
839
+
840
+ declare class WarpLogger {
841
+ private static isTestEnv;
842
+ static info(...args: any[]): void;
843
+ static warn(...args: any[]): void;
844
+ static error(...args: any[]): void;
845
+ }
846
+
847
+ declare class WarpSerializer {
848
+ private typeRegistry;
849
+ setTypeRegistry(typeRegistry: WarpTypeRegistry): void;
850
+ nativeToString(type: WarpActionInputType, value: WarpNativeValue): string;
851
+ stringToNative(value: string): [WarpActionInputType, WarpNativeValue];
852
+ }
853
+
854
+ declare class WarpTypeRegistryImpl implements WarpTypeRegistry {
855
+ private typeHandlers;
856
+ registerType(typeName: string, handler: WarpTypeHandler): void;
857
+ hasType(typeName: string): boolean;
858
+ getHandler(typeName: string): WarpTypeHandler | undefined;
859
+ getRegisteredTypes(): string[];
860
+ }
861
+
862
+ type ValidationResult = {
863
+ valid: boolean;
864
+ errors: ValidationError[];
865
+ };
866
+ type ValidationError = string;
867
+ declare class WarpValidator {
868
+ private config;
869
+ constructor(config: WarpClientConfig);
870
+ validate(warp: Warp): Promise<ValidationResult>;
871
+ private validateMaxOneValuePosition;
872
+ private validateVariableNamesAndResultNamesUppercase;
873
+ private validateAbiIsSetIfApplicable;
874
+ private validateSchema;
875
+ }
876
+
877
+ export { type Adapter, type AdapterFactory, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ClientIndexConfig, type ClientTransformConfig, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, type KnownToken, KnownTokens, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, 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 WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpProviderConfig, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, type WarpTypeRegistry, WarpTypeRegistryImpl, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, asset, biguint, boolean, bytesToBase64, bytesToHex, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpExecutableAction, getCryptoProvider, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getProviderUrl, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, parseSignedMessage, replacePlaceholders, setCryptoProvider, shiftBigintBy, string, testCryptoAvailability, toPreviewText, u16, u32, u64, u8, validateSignedMessage };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import QRCodeStyling from 'qr-code-styling';
2
2
 
3
3
  type WarpChainAccount = {
4
+ chain: WarpChain;
4
5
  address: string;
5
6
  balance: bigint;
6
7
  };
@@ -10,6 +11,7 @@ type WarpChainAssetValue = {
10
11
  amount: bigint;
11
12
  };
12
13
  type WarpChainAsset = {
14
+ chain: WarpChain;
13
15
  identifier: string;
14
16
  name: string;
15
17
  nonce?: bigint;
@@ -17,6 +19,17 @@ type WarpChainAsset = {
17
19
  decimals?: number;
18
20
  logoUrl?: string;
19
21
  };
22
+ type WarpChainAction = {
23
+ chain: WarpChain;
24
+ id: string;
25
+ sender: string;
26
+ receiver: string;
27
+ value: bigint;
28
+ function: string;
29
+ status: WarpChainActionStatus;
30
+ createdAt: string;
31
+ };
32
+ type WarpChainActionStatus = 'pending' | 'success' | 'failed';
20
33
 
21
34
  type WarpChain = string;
22
35
  type WarpExplorerName = string;
@@ -118,7 +131,7 @@ type WarpLinkAction = {
118
131
  inputs?: WarpActionInput[];
119
132
  };
120
133
  type WarpActionInputSource = 'field' | 'query' | 'user:wallet';
121
- type BaseWarpActionInputType = 'string' | 'uint8' | 'uint16' | 'uint32' | 'uint64' | 'biguint' | 'bool' | 'address' | 'hex' | string;
134
+ type BaseWarpActionInputType = 'string' | 'uint8' | 'uint16' | 'uint32' | 'uint64' | 'uint128' | 'uint256' | 'biguint' | 'bool' | 'address' | 'hex' | string;
122
135
  type WarpActionInputType = string;
123
136
  type WarpNativeValue = string | number | bigint | boolean | WarpChainAssetValue | null | WarpNativeValue[];
124
137
  type WarpActionInputPosition = 'receiver' | 'value' | 'transfer' | `arg:${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10}` | 'data' | 'chain';
@@ -244,6 +257,7 @@ type WarpExecution = {
244
257
  tx: WarpAdapterGenericTransaction | null;
245
258
  next: WarpExecutionNextInfo | null;
246
259
  values: any[];
260
+ valuesRaw: any[];
247
261
  results: WarpExecutionResults;
248
262
  messages: WarpExecutionMessages;
249
263
  };
@@ -364,6 +378,7 @@ interface AdapterWarpBrandBuilder {
364
378
  }
365
379
  interface AdapterWarpExecutor {
366
380
  createTransaction(executable: WarpExecutable): Promise<WarpAdapterGenericTransaction>;
381
+ executeQuery(executable: WarpExecutable): Promise<WarpExecution>;
367
382
  preprocessInput(chain: WarpChainInfo, input: string, type: WarpActionInputType, value: string): Promise<string>;
368
383
  signMessage(message: string, privateKey: string): Promise<string>;
369
384
  }
@@ -406,9 +421,14 @@ interface AdapterWarpExplorer {
406
421
  getAssetUrl(identifier: string): string;
407
422
  getContractUrl(address: string): string;
408
423
  }
424
+ interface WarpDataLoaderOptions {
425
+ page?: number;
426
+ size?: number;
427
+ }
409
428
  interface AdapterWarpDataLoader {
410
429
  getAccount(address: string): Promise<WarpChainAccount>;
411
430
  getAccountAssets(address: string): Promise<WarpChainAsset[]>;
431
+ getAccountActions(address: string, options?: WarpDataLoaderOptions): Promise<WarpChainAction[]>;
412
432
  }
413
433
 
414
434
  declare enum WarpChainName {
@@ -417,7 +437,8 @@ declare enum WarpChainName {
417
437
  Sui = "sui",
418
438
  Ethereum = "ethereum",
419
439
  Base = "base",
420
- Arbitrum = "arbitrum"
440
+ Arbitrum = "arbitrum",
441
+ Fastset = "fastset"
421
442
  }
422
443
  declare const WarpConstants: {
423
444
  HttpProtocolPrefix: string;
@@ -467,6 +488,8 @@ declare const WarpInputTypes: {
467
488
  U16: string;
468
489
  U32: string;
469
490
  U64: string;
491
+ U128: string;
492
+ U256: string;
470
493
  Biguint: string;
471
494
  Boolean: string;
472
495
  Address: string;
@@ -851,4 +874,4 @@ declare class WarpValidator {
851
874
  private validateSchema;
852
875
  }
853
876
 
854
- export { type Adapter, type AdapterFactory, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ClientIndexConfig, type ClientTransformConfig, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, type KnownToken, KnownTokens, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, 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 WarpChainAccount, type WarpChainAsset, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpProviderConfig, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, type WarpTypeRegistry, WarpTypeRegistryImpl, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, asset, biguint, boolean, bytesToBase64, bytesToHex, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpExecutableAction, getCryptoProvider, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getProviderUrl, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, parseSignedMessage, replacePlaceholders, setCryptoProvider, shiftBigintBy, string, testCryptoAvailability, toPreviewText, u16, u32, u64, u8, validateSignedMessage };
877
+ export { type Adapter, type AdapterFactory, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ClientIndexConfig, type ClientTransformConfig, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, type KnownToken, KnownTokens, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, 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 WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpProviderConfig, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, type WarpTypeRegistry, WarpTypeRegistryImpl, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, asset, biguint, boolean, bytesToBase64, bytesToHex, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpExecutableAction, getCryptoProvider, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getProviderUrl, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, parseSignedMessage, replacePlaceholders, setCryptoProvider, shiftBigintBy, string, testCryptoAvailability, toPreviewText, u16, u32, u64, u8, validateSignedMessage };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";var Er=Object.create;var X=Object.defineProperty;var Rr=Object.getOwnPropertyDescriptor;var Br=Object.getOwnPropertyNames;var $r=Object.getPrototypeOf,Ur=Object.prototype.hasOwnProperty;var Nr=(n,r)=>{for(var e in r)X(n,e,{get:r[e],enumerable:!0})},yr=(n,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Br(r))!Ur.call(n,a)&&a!==e&&X(n,a,{get:()=>r[a],enumerable:!(t=Rr(r,a))||t.enumerable});return n};var Z=(n,r,e)=>(e=n!=null?Er($r(n)):{},yr(r||!n||!n.__esModule?X(e,"default",{value:n,enumerable:!0}):e,n)),Vr=n=>yr(X({},"__esModule",{value:!0}),n);var oe={};Nr(oe,{BrowserCryptoProvider:()=>Y,CacheTtl:()=>hr,KnownTokens:()=>Pr,NodeCryptoProvider:()=>_,WarpBrandBuilder:()=>fr,WarpBuilder:()=>gr,WarpCache:()=>k,WarpCacheKey:()=>mr,WarpChainName:()=>xr,WarpClient:()=>Wr,WarpConfig:()=>b,WarpConstants:()=>c,WarpExecutor:()=>q,WarpFactory:()=>V,WarpIndex:()=>z,WarpInputTypes:()=>v,WarpInterpolator:()=>H,WarpLinkBuilder:()=>N,WarpLinkDetecter:()=>J,WarpLogger:()=>A,WarpProtocolVersions:()=>$,WarpSerializer:()=>T,WarpTypeRegistryImpl:()=>G,WarpValidator:()=>F,address:()=>ae,applyResultsToMessages:()=>cr,asset:()=>ie,biguint:()=>te,boolean:()=>ne,bytesToBase64:()=>Or,bytesToHex:()=>vr,createAuthHeaders:()=>nr,createAuthMessage:()=>tr,createCryptoProvider:()=>Dr,createHttpAuthHeaders:()=>Jr,createSignableMessage:()=>br,evaluateResultsCommon:()=>Cr,extractCollectResults:()=>dr,extractIdentifierInfoFromUrl:()=>O,findKnownTokenById:()=>Xr,findWarpAdapterByPrefix:()=>S,findWarpAdapterForChain:()=>g,findWarpExecutableAction:()=>or,getCryptoProvider:()=>ar,getLatestProtocolIdentifier:()=>D,getNextInfo:()=>ur,getProviderConfig:()=>Gr,getProviderUrl:()=>kr,getRandomBytes:()=>ir,getRandomHex:()=>sr,getWarpActionByIndex:()=>R,getWarpInfoFromIdentifier:()=>P,hex:()=>se,parseResultsOutIndex:()=>Ir,parseSignedMessage:()=>Kr,replacePlaceholders:()=>er,setCryptoProvider:()=>Hr,shiftBigintBy:()=>rr,string:()=>Zr,testCryptoAvailability:()=>Lr,toPreviewText:()=>pr,u16:()=>_r,u32:()=>re,u64:()=>ee,u8:()=>Yr,validateSignedMessage:()=>Qr});module.exports=Vr(oe);var xr=(o=>(o.Multiversx="multiversx",o.Vibechain="vibechain",o.Sui="sui",o.Ethereum="ethereum",o.Base="base",o.Arbitrum="arbitrum",o.Fastset="fastset",o))(xr||{}),c={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chainInfo.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",U128:"u128",U256:"u256",Biguint:"biguint",Boolean:"boolean",Address:"address",Asset:"asset",Hex:"hex"};var $={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},b={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${$.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${$.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",DefaultChainPrefix:"mvx",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],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 Y=class{async getRandomBytes(r){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(r);return window.crypto.getRandomValues(e),e}},_=class{async getRandomBytes(r){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(r))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},U=null;function ar(){if(U)return U;if(typeof window<"u"&&window.crypto)return U=new Y,U;if(typeof process<"u"&&process.versions?.node)return U=new _,U;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Hr(n){U=n}async function ir(n,r){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(r||ar()).getRandomBytes(n)}function vr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let r=new Array(n.length*2);for(let e=0;e<n.length;e++){let t=n[e];r[e*2]=(t>>>4).toString(16),r[e*2+1]=(t&15).toString(16)}return r.join("")}function Or(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(n).toString("base64");if(typeof btoa<"u"){let r=String.fromCharCode.apply(null,Array.from(n));return btoa(r)}else throw new Error("Base64 encoding not available in this environment")}async function sr(n,r){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let e=await ir(n/2,r);return vr(e)}async function Lr(){let n={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?n.environment="browser":typeof process<"u"&&process.versions?.node&&(n.environment="nodejs"),await ir(16),n.randomBytes=!0}catch{}return n}function Dr(){return ar()}var g=(n,r)=>{let e=r.find(t=>t.chainInfo.name.toLowerCase()===n.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${n}`);return e},S=(n,r)=>{let e=r.find(t=>t.prefix.toLowerCase()===n.toLowerCase());if(!e)throw new Error(`Adapter not found for prefix: ${n}`);return e},D=n=>{if(n==="warp")return`warp:${$.Warp}`;if(n==="brand")return`brand:${$.Brand}`;if(n==="abi")return`abi:${$.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},R=(n,r)=>n?.actions[r-1],or=n=>(n.actions.forEach((r,e)=>{if(r.type!=="link")return{action:r,actionIndex:e}}),{action:R(n,1),actionIndex:1}),rr=(n,r)=>{let e=n.toString(),[t,a=""]=e.split("."),i=Math.abs(r);if(r>0)return BigInt(t+a.padEnd(i,"0"));if(r<0){let s=t+a;if(i>=s.length)return 0n;let o=s.slice(0,-i)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},pr=(n,r=100)=>{if(!n)return"";let e=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>r?e.substring(0,e.lastIndexOf(" ",r))+"...":e,e},er=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(e,t)=>r[t]||""),cr=(n,r)=>{let e=Object.entries(n.messages||{}).map(([t,a])=>[t,er(a,r)]);return Object.fromEntries(e)};var Fr=n=>{let r=c.IdentifierParamSeparator,e=-1,t="";for(let a of r){let i=n.indexOf(a);i!==-1&&(e===-1||i<e)&&(e=i,t=a)}return e!==-1?{separator:t,index:e}:null},Ar=n=>{let r=Fr(n);if(!r)return[n];let{separator:e,index:t}=r,a=n.substring(0,t),i=n.substring(t+e.length),s=Ar(i);return[a,...s]},P=n=>{let r=decodeURIComponent(n).trim(),e=r.split("?")[0],t=Ar(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chainPrefix:c.IdentifierChainDefault,type:c.IdentifierType.Hash,identifier:r,identifierBase:e};if(t.length===2&&/^[a-zA-Z0-9]{62}$/.test(t[0])&&/^[a-zA-Z0-9]{2}$/.test(t[1]))return null;if(t.length===3){let[a,i,s]=t;if(i===c.IdentifierType.Alias||i===c.IdentifierType.Hash){let o=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:a,type:i,identifier:o,identifierBase:s}}}if(t.length===2){let[a,i]=t;if(a===c.IdentifierType.Alias||a===c.IdentifierType.Hash){let s=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:c.IdentifierChainDefault,type:a,identifier:s,identifierBase:i}}}if(t.length===2){let[a,i]=t;if(a!==c.IdentifierType.Alias&&a!==c.IdentifierType.Hash){let s=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:a,type:c.IdentifierType.Alias,identifier:s,identifierBase:i}}}return{chainPrefix:c.IdentifierChainDefault,type:c.IdentifierType.Alias,identifier:r,identifierBase:e}},O=n=>{let r=new URL(n),t=r.searchParams.get(c.IdentifierParamName);if(t||(t=r.pathname.split("/")[1]),!t)return null;let a=decodeURIComponent(t);return P(a)};var wr=Z(require("qr-code-styling"),1);var N=class{constructor(r,e){this.config=r;this.adapters=e}isValid(r){return r.startsWith(c.HttpProtocolPrefix)?!!O(r):!1}build(r,e,t){let a=this.config.clientUrl||b.DefaultClientUrl(this.config.env),i=g(r,this.adapters),s=e===c.IdentifierType.Alias?t:e+c.IdentifierParamSeparatorDefault+t,o=i.prefix+c.IdentifierParamSeparatorDefault+s,p=encodeURIComponent(o);return b.SuperClientUrls.includes(a)?`${a}/${p}`:`${a}?${c.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(r){let e=P(r);if(!e)return null;let t=S(e.chainPrefix,this.adapters);return t?this.build(t.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(r,e,t,a=512,i="white",s="black",o="#23F7DD"){let p=g(r,this.adapters),l=this.build(p.chainInfo.name,e,t);return new wr.default({type:"svg",width:a,height:a,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var jr="https://",ur=(n,r,e,t,a)=>{let i=e.actions?.[t]?.next||e.next||null;if(!i)return null;if(i.startsWith(jr))return[{identifier:null,url:i}];let[s,o]=i.split("?");if(!o)return[{identifier:s,url:lr(r,s,n)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let h=er(o,{...e.vars,...a}),u=h?`${s}?${h}`:s;return[{identifier:u,url:lr(r,u,n)}]}let l=p[0];if(!l)return[];let d=l.match(/{{([^[]+)\[\]/),m=d?d[1]:null;if(!m||a[m]===void 0)return[];let f=Array.isArray(a[m])?a[m]:[a[m]];if(f.length===0)return[];let C=p.filter(h=>h.includes(`{{${m}[]`)).map(h=>{let u=h.match(/\[\](\.[^}]+)?}}/),W=u&&u[1]||"";return{placeholder:h,field:W?W.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(h=>{let u=o;for(let{regex:I,field:x}of C){let w=x?Mr(h,x):h;if(w==null)return null;u=u.replace(I,w)}if(u.includes("{{")||u.includes("}}"))return null;let W=u?`${s}?${u}`:s;return{identifier:W,url:lr(r,W,n)}}).filter(h=>h!==null)},lr=(n,r,e)=>{let[t,a]=r.split("?"),i=P(t)||{chainPrefix:b.DefaultChainPrefix,type:"alias",identifier:t,identifierBase:t},s=S(i.chainPrefix,n);if(!s)throw new Error(`Adapter not found for chain ${i.chainPrefix}`);let o=new N(e,n).build(s.chainInfo.name,i.type,i.identifierBase);if(!a)return o;let p=new URL(o);return new URLSearchParams(a).forEach((l,d)=>p.searchParams.set(d,l)),p.toString().replace(/\/\?/,"?")},Mr=(n,r)=>r.split(".").reduce((e,t)=>e?.[t],n);var kr=(n,r,e,t)=>{let a=n.providers?.[r];return a?.[e]?a[e]:t},Gr=(n,r)=>n.providers?.[r];var L=class L{static info(...r){L.isTestEnv||console.info(...r)}static warn(...r){L.isTestEnv||console.warn(...r)}static error(...r){L.isTestEnv||console.error(...r)}};L.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var A=L;var T=class{setTypeRegistry(r){this.typeRegistry=r}nativeToString(r,e){if(r==="asset"&&typeof e=="object"&&e&&"identifier"in e&&"nonce"in e&&"amount"in e)return`${r}:${e.identifier}|${e.nonce.toString()}|${e.amount.toString()}`;if(this.typeRegistry?.hasType(r)){let t=this.typeRegistry.getHandler(r);if(t)return t.nativeToString(e)}return`${r}:${e?.toString()??""}`}stringToNative(r){let e=r.split(c.ArgParamsSeparator),t=e[0],a=e.slice(1).join(c.ArgParamsSeparator);if(t==="null")return[t,null];if(t==="option"){let[i,s]=a.split(c.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(t==="optional"){let[i,s]=a.split(c.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(t==="list"){let i=a.split(c.ArgParamsSeparator),s=i.slice(0,-1).join(c.ArgParamsSeparator),o=i[i.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`list:${s}`,l]}else if(t==="variadic"){let i=a.split(c.ArgParamsSeparator),s=i.slice(0,-1).join(c.ArgParamsSeparator),o=i[i.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`variadic:${s}`,l]}else if(t.startsWith("composite")){let i=t.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),o=a.split(c.ArgCompositeSeparator).map((p,l)=>this.stringToNative(`${i[l]}:${p}`)[1]);return[t,o]}else{if(t==="string")return[t,a];if(t==="uint8"||t==="uint16"||t==="uint32")return[t,Number(a)];if(t==="uint64"||t==="biguint")return[t,BigInt(a||0)];if(t==="bool")return[t,a==="true"];if(t==="address")return[t,a];if(t==="token")return[t,a];if(t==="hex")return[t,a];if(t==="codemeta")return[t,a];if(t==="asset"){let[i,s,o]=a.split(c.ArgCompositeSeparator),p={identifier:i,nonce:BigInt(s),amount:BigInt(o)};return[t,p]}}if(this.typeRegistry?.hasType(t)){let i=this.typeRegistry.getHandler(t);if(i){let s=i.stringToNative(a);return[t,s]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${t}`)}};var dr=async(n,r,e,t,a)=>{let i=[],s={};for(let[o,p]of Object.entries(n.results||{})){if(p.startsWith(c.Transform.Prefix))continue;let l=Ir(p);if(l!==null&&l!==e){s[o]=null;continue}let[d,...m]=p.split("."),f=(C,E)=>E.reduce((h,u)=>h&&h[u]!==void 0?h[u]:null,C);if(d==="out"||d.startsWith("out[")){let C=m.length===0?r?.data||r:f(r,m);i.push(C),s[o]=C}else s[o]=p}return{values:i,results:await Cr(n,s,e,t,a)}},Cr=async(n,r,e,t,a)=>{if(!n.results)return r;let i={...r};return i=qr(i,n,e,t),i=await zr(n,i,a),i},qr=(n,r,e,t)=>{let a={...n},i=R(r,e)?.inputs||[],s=new T;for(let[o,p]of Object.entries(a))if(typeof p=="string"&&p.startsWith("input.")){let l=p.split(".")[1],d=i.findIndex(f=>f.as===l||f.name===l),m=d!==-1?t[d]?.value:null;a[o]=m?s.stringToNative(m)[1]:null}return a},zr=async(n,r,e)=>{if(!n.results)return r;let t={...r},a=Object.entries(n.results).filter(([,i])=>i.startsWith(c.Transform.Prefix)).map(([i,s])=>({key:i,code:s.substring(c.Transform.Prefix.length)}));if(a.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform results are defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:i,code:s}of a)try{t[i]=await e.run(s,t)}catch(o){A.error(`Transform error for result '${i}':`,o),t[i]=null}return t},Ir=n=>{if(n==="out")return 1;let r=n.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};async function br(n,r,e,t=5){let a=await sr(64,e),i=new Date(Date.now()+t*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:a,expiresAt:i,purpose:r}),nonce:a,expiresAt:i}}async function tr(n,r,e,t){let a=t||`prove-wallet-ownership for app "${r}"`;return br(n,a,e,5)}function nr(n,r,e,t){return{"X-Signer-Wallet":n,"X-Signer-Signature":r,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":t}}async function Jr(n,r,e,t){let{message:a,nonce:i,expiresAt:s}=await tr(n,e,t),o=await r(a);return nr(n,o,i,s)}function Qr(n){let r=new Date(n).getTime();return Date.now()<r}function Kr(n){try{let r=JSON.parse(n);if(!r.wallet||!r.nonce||!r.expiresAt||!r.purpose)throw new Error("Invalid signed message: missing required fields");return r}catch(r){throw new Error(`Failed to parse signed message: ${r instanceof Error?r.message:"Unknown error"}`)}}var Pr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Xr=n=>Pr.find(r=>r.id===n)||null;var Zr=n=>v.String+c.ArgParamsSeparator+n,Yr=n=>v.U8+c.ArgParamsSeparator+n,_r=n=>v.U16+c.ArgParamsSeparator+n,re=n=>v.U32+c.ArgParamsSeparator+n,ee=n=>v.U64+c.ArgParamsSeparator+n,te=n=>v.Biguint+c.ArgParamsSeparator+n,ne=n=>v.Boolean+c.ArgParamsSeparator+n,ae=n=>v.Address+c.ArgParamsSeparator+n,ie=n=>v.Asset+c.ArgParamsSeparator+n.identifier+c.ArgCompositeSeparator+BigInt(n.nonce||0).toString()+c.ArgCompositeSeparator+n.amount,se=n=>v.Hex+c.ArgParamsSeparator+n;var Tr=Z(require("ajv"),1);var fr=class{constructor(r){this.pendingBrand={protocol:D("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,e=!0){let t=JSON.parse(r);return e&&await this.ensureValidSchema(t),t}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,e){if(!r)throw new Error(`Warp: ${e}`)}async ensureValidSchema(r){let e=this.config.schema?.brand||b.LatestBrandSchemaUrl,a=await(await fetch(e)).json(),i=new Tr.default,s=i.compile(a);if(!s(r))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};var Sr=Z(require("ajv"),1);var F=class{constructor(r){this.config=r;this.config=r}async validate(r){let e=[];return e.push(...this.validateMaxOneValuePosition(r)),e.push(...this.validateVariableNamesAndResultNamesUppercase(r)),e.push(...this.validateAbiIsSetIfApplicable(r)),e.push(...await this.validateSchema(r)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(r){return r.actions.filter(t=>t.inputs?t.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let e=[],t=(a,i)=>{a&&Object.keys(a).forEach(s=>{s!==s.toUpperCase()&&e.push(`${i} name '${s}' must be uppercase`)})};return t(r.vars,"Variable"),t(r.results,"Result"),e}validateAbiIsSetIfApplicable(r){let e=r.actions.some(s=>s.type==="contract"),t=r.actions.some(s=>s.type==="query");if(!e&&!t)return[];let a=r.actions.some(s=>s.abi),i=Object.values(r.results||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return r.results&&!a&&i?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let e=this.config.schema?.warp||b.LatestWarpSchemaUrl,a=await(await fetch(e)).json(),i=new Sr.default({strict:!1}),s=i.compile(a);return s(r)?[]:[`Schema validation failed: ${i.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var gr=class{constructor(r){this.config=r;this.pendingWarp={protocol:D("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,e=!0){let t=JSON.parse(r);return e&&await this.validate(t),t}async createFromUrl(r){return await(await fetch(r)).json()}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,e=100){return pr(r,e)}ensure(r,e){if(!r)throw new Error(e)}async validate(r){let t=await new F(this.config).validate(r);if(!t.valid)throw new Error(t.errors.join(`
2
+ `))}};var j=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let e=localStorage.getItem(this.getKey(r));if(!e)return null;let t=JSON.parse(e);return Date.now()>t.expiresAt?(localStorage.removeItem(this.getKey(r)),null):t.value}catch{return null}}set(r,e,t){let a={value:e,expiresAt:Date.now()+t*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(a))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let e=localStorage.key(r);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var B=class B{get(r){let e=B.cache.get(r);return e?Date.now()>e.expiresAt?(B.cache.delete(r),null):e.value:null}set(r,e,t){let a=Date.now()+t*1e3;B.cache.set(r,{value:e,expiresAt:a})}forget(r){B.cache.delete(r)}clear(){B.cache.clear()}};B.cache=new Map;var M=B;var hr={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},mr={Warp:(n,r)=>`warp:${n}:${r}`,WarpAbi:(n,r)=>`warp-abi:${n}:${r}`,WarpExecutable:(n,r,e)=>`warp-exec:${n}:${r}:${e}`,RegistryInfo:(n,r)=>`registry-info:${n}:${r}`,Brand:(n,r)=>`brand:${n}:${r}`},k=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new j:r==="memory"?new M:typeof window<"u"&&window.localStorage?new j:new M}set(r,e,t){this.strategy.set(r,e,t)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var G=class{constructor(){this.typeHandlers=new Map}registerType(r,e){this.typeHandlers.set(r,e)}hasType(r){return this.typeHandlers.has(r)}getHandler(r){return this.typeHandlers.get(r)}getRegisteredTypes(){return Array.from(this.typeHandlers.keys())}};var V=class{constructor(r,e){this.config=r;this.adapters=e;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new T,this.cache=new k(r.cache?.type);let t=new G;this.serializer.setTypeRegistry(t);for(let a of e)a.registerTypes&&a.registerTypes(t)}async createExecutable(r,e,t){let a=R(r,e);if(!a)throw new Error("WarpFactory: Action not found");let i=await this.getChainInfoForAction(a,t),s=await this.getResolvedInputs(i.name,a,t),o=this.getModifiedInputs(s),p=o.find(y=>y.input.position==="receiver")?.value,l="address"in a?a.address:null,d=p?this.serializer.stringToNative(p)[1]:l;if(!d)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let m=this.getPreparedArgs(a,o),f=o.find(y=>y.input.position==="value")?.value||null,C="value"in a?a.value:null,E=BigInt(f?.split(":")[1]||C||0),h=o.filter(y=>y.input.position==="transfer"&&y.value).map(y=>y.value),I=[...("transfers"in a?a.transfers:[])||[],...h||[]].map(y=>this.serializer.stringToNative(y)[1]),x=o.find(y=>y.input.position==="data")?.value,w="data"in a?a.data||"":null,K={warp:r,chain:i,action:e,destination:d,args:m,value:E,transfers:I,data:x||w||null,resolvedInputs:o};return this.cache.set(mr.WarpExecutable(this.config.env,r.meta?.hash||"",e),K.resolvedInputs,hr.OneWeek),K}async getChainInfoForAction(r,e){if(r.chain)return g(r.chain,this.adapters).chainInfo;if(e){let a=await this.tryGetChainFromInputs(r,e);if(a)return a}return this.adapters[0].chainInfo}async getResolvedInputs(r,e,t){let a=e.inputs||[],i=await Promise.all(t.map(o=>this.preprocessInput(r,o))),s=(o,p)=>{if(o.source==="query"){let l=this.url.searchParams.get(o.name);return l?this.serializer.nativeToString(o.type,l):null}else return o.source===c.Source.UserWallet?this.config.user?.wallets?.[r]?this.serializer.nativeToString("address",this.config.user.wallets[r]):null:i[p]||null};return a.map((o,p)=>{let l=s(o,p);return{input:o,value:l||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((e,t)=>{if(e.input.modifier?.startsWith("scale:")){let[,a]=e.input.modifier.split(":");if(isNaN(Number(a))){let i=Number(r.find(p=>p.input.name===a)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=rr(s,+i);return{...e,value:`${e.input.type}:${o}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=rr(i,+a);return{...e,value:`${e.input.type}:${s}`}}}else return e})}async preprocessInput(r,e){try{let[t,a]=e.split(c.ArgParamsSeparator,2),i=g(r,this.adapters);return i.executor.preprocessInput(i.chainInfo,e,t,a)}catch{return e}}getPreparedArgs(r,e){let t="args"in r?r.args||[]:[];return e.forEach(({input:a,value:i})=>{if(!i||!a.position?.startsWith("arg:"))return;let s=Number(a.position.split(":")[1])-1;t.splice(s,0,i)}),t}async tryGetChainFromInputs(r,e){let t=r.inputs?.findIndex(p=>p.position==="chain");if(t===-1||t===void 0)return null;let a=e[t];if(!a)throw new Error("Chain input not found");let s=new T().stringToNative(a)[1];return g(s,this.adapters).chainInfo}};var H=class{constructor(r,e){this.config=r;this.adapter=e}async apply(r,e){let t=this.applyVars(r,e);return await this.applyGlobals(r,t)}async applyGlobals(r,e){let t={...e};return t.actions=await Promise.all(t.actions.map(async a=>await this.applyActionGlobals(a))),t=await this.applyRootGlobals(t,r),t}applyVars(r,e){if(!e?.vars)return e;let t=JSON.stringify(e),a=(i,s)=>{t=t.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(e.vars).forEach(([i,s])=>{if(typeof s!="string")a(i,s);else if(s.startsWith(`${c.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${c.Vars.Query}:`)[1],p=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);p&&a(i,p)}else if(s.startsWith(`${c.Vars.Env}:`)){let o=s.split(`${c.Vars.Env}:`)[1],p=r.vars?.[o];p&&a(i,p)}else if(s===c.Source.UserWallet&&r.user?.wallets?.[this.adapter.chainInfo.name]){let o=r.user.wallets[this.adapter.chainInfo.name];o&&a(i,o)}else a(i,s)}),JSON.parse(t)}async applyRootGlobals(r,e){let t=JSON.stringify(r),a={config:e,chain:this.adapter.chainInfo.name,chainInfo:this.adapter.chainInfo};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(a);s!=null&&(t=t.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(t)}async applyActionGlobals(r){let e=r.chain?this.adapter.chainInfo:this.adapter.chainInfo;if(!e)throw new Error(`Chain info not found for ${r.chain}`);let t=JSON.stringify(r),a={config:this.config,chain:this.adapter.chainInfo.name,chainInfo:e};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(a);s!=null&&(t=t.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(t)}};var q=class{constructor(r,e,t){this.config=r;this.adapters=e;this.handlers=t;this.handlers=t,this.factory=new V(r,e),this.serializer=new T}async execute(r,e){let{action:t,actionIndex:a}=or(r);if(t.type==="collect"){let p=await this.executeCollect(r,a,e);return p.success?this.handlers?.onExecuted?.(p):this.handlers?.onError?.({message:JSON.stringify(p.values)}),{tx:null,chain:null}}let i=await this.factory.createExecutable(r,a,e),s=g(i.chain.name,this.adapters);if(t.type==="query"){let p=await s.executor.executeQuery(i);return p.success?this.handlers?.onExecuted?.(p):this.handlers?.onError?.({message:JSON.stringify(p.values)}),{tx:null,chain:i.chain}}return{tx:await s.executor.createTransaction(i),chain:i.chain}}async evaluateResults(r,e,t){let a=await g(e,this.adapters).results.getTransactionExecutionResults(r,t);this.handlers?.onExecuted?.(a)}async executeCollect(r,e,t,a){let i=R(r,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let s=await this.factory.getChainInfoForAction(i),o=g(s.name,this.adapters),p=await new H(this.config,o).apply(this.config,r),l=await this.factory.getResolvedInputs(s.name,i,t),d=this.factory.getModifiedInputs(l),m=u=>{if(!u.value)return null;let W=this.serializer.stringToNative(u.value)[1];if(u.input.type==="biguint")return W.toString();if(u.input.type==="asset"){let{identifier:I,nonce:x,amount:w}=W;return{identifier:I,nonce:x.toString(),amount:w.toString()}}else return W},f=new Headers;if(f.set("Content-Type","application/json"),f.set("Accept","application/json"),this.handlers?.onSignRequest){let u=this.config.user?.wallets?.[s.name];if(!u)throw new Error(`No wallet configured for chain ${s.name}`);let{message:W,nonce:I,expiresAt:x}=await tr(u,`${s.name}-adapter`),w=await this.handlers.onSignRequest({message:W,chain:s}),Q=nr(u,w,I,x);Object.entries(Q).forEach(([K,y])=>f.set(K,y))}Object.entries(i.destination.headers||{}).forEach(([u,W])=>{f.set(u,W)});let C=Object.fromEntries(d.map(u=>[u.input.as||u.input.name,m(u)])),E=i.destination.method||"GET",h=E==="GET"?void 0:JSON.stringify({...C,...a});A.info("Executing collect",{url:i.destination.url,method:E,headers:f,body:h});try{let u=await fetch(i.destination.url,{method:E,headers:f,body:h}),W=await u.json(),{values:I,results:x}=await dr(p,W,e,d,this.config.transform?.runner),w=ur(this.config,this.adapters,p,e,x);return{success:u.ok,warp:p,action:e,user:this.config.user?.wallets?.[s.name]||null,txHash:null,tx:null,next:w,values:I,valuesRaw:I.map(Q=>this.serializer.stringToNative(Q)[1]),results:{...x,_DATA:W},messages:cr(p,x)}}catch(u){return A.error("WarpActionExecutor: Error executing collect",u),{success:!1,warp:p,action:e,user:this.config.user?.wallets?.[s.name]||null,txHash:null,tx:null,next:null,values:[],valuesRaw:[],results:{_DATA:u},messages:{}}}}};var z=class{constructor(r){this.config=r}async search(r,e,t){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let a=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...t},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...e})});if(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw A.error("WarpIndex: Error searching for warps: ",a),a}}};var J=class{constructor(r,e){this.config=r;this.adapters=e}isValid(r){return r.startsWith(c.HttpProtocolPrefix)?!!O(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let a=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),s=(await Promise.all(a)).filter(l=>l.match),o=s.length>0,p=s.map(l=>({url:l.url,warp:l.warp}));return{match:o,results:p}}async detect(r,e){let t={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},a=r.startsWith(c.HttpProtocolPrefix)?O(r):P(r);if(!a)return t;try{let{type:i,identifierBase:s}=a,o=null,p=null,l=null,d=S(a.chainPrefix,this.adapters);if(i==="hash"){o=await d.builder().createFromTransactionHash(s,e);let f=await d.registry.getInfoByHash(s,e);p=f.registryInfo,l=f.brand}else if(i==="alias"){let f=await d.registry.getInfoByAlias(s,e);p=f.registryInfo,l=f.brand,f.registryInfo&&(o=await d.builder().createFromTransactionHash(f.registryInfo.hash,e))}let m=o?await new H(this.config,d).apply(this.config,o):null;return m?{match:!0,url:r,warp:m,chain:d.chainInfo.name,registryInfo:p,brand:l}:t}catch(i){return A.error("Error detecting warp link",i),t}}};var Wr=class{constructor(r,e){this.config=r;this.adapters=e}getConfig(){return this.config}setConfig(r){return this.config=r,this}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new q(this.config,this.adapters,r)}async detectWarp(r,e){return new J(this.config,this.adapters).detect(r,e)}async executeWarp(r,e,t,a={}){let i=r.startsWith("http")&&r.endsWith(".json")?await(await fetch(r)).json():(await this.detectWarp(r,a.cache)).warp;if(!i)throw new Error("Warp not found");let s=this.createExecutor(t),{tx:o,chain:p}=await s.execute(i,e);return{tx:o,chain:p,evaluateResults:async d=>{if(!p||!o||!i)throw new Error("Warp not found");await s.evaluateResults(i,p.name,d)}}}createInscriptionTransaction(r,e){return g(r,this.adapters).builder().createInscriptionTransaction(e)}async createFromTransaction(r,e,t=!1){return g(r,this.adapters).builder().createFromTransaction(e,t)}async createFromTransactionHash(r,e){let t=P(r);if(!t)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return S(t.chainPrefix,this.adapters).builder().createFromTransactionHash(r,e)}async signMessage(r,e,t){if(!this.config.user?.wallets?.[r])throw new Error(`No wallet configured for chain ${r}`);return g(r,this.adapters).executor.signMessage(e,t)}getExplorer(r){return g(r,this.adapters).explorer}getResults(r){return g(r,this.adapters).results}async getRegistry(r){let e=g(r,this.adapters).registry;return await e.init(),e}getDataLoader(r){return g(r,this.adapters).dataLoader}get factory(){return new V(this.config,this.adapters)}get index(){return new z(this.config)}get linkBuilder(){return new N(this.config,this.adapters)}createBuilder(r){return g(r,this.adapters).builder()}createAbiBuilder(r){return g(r,this.adapters).abiBuilder()}createBrandBuilder(r){return g(r,this.adapters).brandBuilder()}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,KnownTokens,NodeCryptoProvider,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistryImpl,WarpValidator,address,applyResultsToMessages,asset,biguint,boolean,bytesToBase64,bytesToHex,createAuthHeaders,createAuthMessage,createCryptoProvider,createHttpAuthHeaders,createSignableMessage,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,findKnownTokenById,findWarpAdapterByPrefix,findWarpAdapterForChain,findWarpExecutableAction,getCryptoProvider,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getProviderUrl,getRandomBytes,getRandomHex,getWarpActionByIndex,getWarpInfoFromIdentifier,hex,parseResultsOutIndex,parseSignedMessage,replacePlaceholders,setCryptoProvider,shiftBigintBy,string,testCryptoAvailability,toPreviewText,u16,u32,u64,u8,validateSignedMessage});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var yr=(s=>(s.Multiversx="multiversx",s.Vibechain="vibechain",s.Sui="sui",s.Ethereum="ethereum",s.Base="base",s.Arbitrum="arbitrum",s))(yr||{}),p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},A={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Asset:"asset",Hex:"hex"};var U={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},I={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${U.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${U.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",DefaultChainPrefix:"mvx",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",p.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var X=class{async getRandomBytes(r){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(r);return window.crypto.getRandomValues(e),e}},Z=class{async getRandomBytes(r){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(r))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},B=null;function ar(){if(B)return B;if(typeof window<"u"&&window.crypto)return B=new X,B;if(typeof process<"u"&&process.versions?.node)return B=new Z,B;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Vr(n){B=n}async function ir(n,r){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(r||ar()).getRandomBytes(n)}function xr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let r=new Array(n.length*2);for(let e=0;e<n.length;e++){let t=n[e];r[e*2]=(t>>>4).toString(16),r[e*2+1]=(t&15).toString(16)}return r.join("")}function Hr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(n).toString("base64");if(typeof btoa<"u"){let r=String.fromCharCode.apply(null,Array.from(n));return btoa(r)}else throw new Error("Base64 encoding not available in this environment")}async function sr(n,r){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let e=await ir(n/2,r);return xr(e)}async function Or(){let n={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?n.environment="browser":typeof process<"u"&&process.versions?.node&&(n.environment="nodejs"),await ir(16),n.randomBytes=!0}catch{}return n}function Lr(){return ar()}var h=(n,r)=>{let e=r.find(t=>t.chainInfo.name.toLowerCase()===n.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${n}`);return e},E=(n,r)=>{let e=r.find(t=>t.prefix.toLowerCase()===n.toLowerCase());if(!e)throw new Error(`Adapter not found for prefix: ${n}`);return e},M=n=>{if(n==="warp")return`warp:${U.Warp}`;if(n==="brand")return`brand:${U.Brand}`;if(n==="abi")return`abi:${U.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},$=(n,r)=>n?.actions[r-1],or=n=>(n.actions.forEach((r,e)=>{if(r.type!=="link")return{action:r,actionIndex:e}}),{action:$(n,1),actionIndex:1}),Y=(n,r)=>{let e=n.toString(),[t,a=""]=e.split("."),i=Math.abs(r);if(r>0)return BigInt(t+a.padEnd(i,"0"));if(r<0){let s=t+a;if(i>=s.length)return 0n;let o=s.slice(0,-i)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},pr=(n,r=100)=>{if(!n)return"";let e=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>r?e.substring(0,e.lastIndexOf(" ",r))+"...":e,e},_=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(e,t)=>r[t]||""),cr=(n,r)=>{let e=Object.entries(n.messages||{}).map(([t,a])=>[t,_(a,r)]);return Object.fromEntries(e)};var vr=n=>{let r=p.IdentifierParamSeparator,e=-1,t="";for(let a of r){let i=n.indexOf(a);i!==-1&&(e===-1||i<e)&&(e=i,t=a)}return e!==-1?{separator:t,index:e}:null},lr=n=>{let r=vr(n);if(!r)return[n];let{separator:e,index:t}=r,a=n.substring(0,t),i=n.substring(t+e.length),s=lr(i);return[a,...s]},b=n=>{let r=decodeURIComponent(n).trim(),e=r.split("?")[0],t=lr(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:r,identifierBase:e};if(t.length===2&&/^[a-zA-Z0-9]{62}$/.test(t[0])&&/^[a-zA-Z0-9]{2}$/.test(t[1]))return null;if(t.length===3){let[a,i,s]=t;if(i===p.IdentifierType.Alias||i===p.IdentifierType.Hash){let o=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:a,type:i,identifier:o,identifierBase:s}}}if(t.length===2){let[a,i]=t;if(a===p.IdentifierType.Alias||a===p.IdentifierType.Hash){let s=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:p.IdentifierChainDefault,type:a,identifier:s,identifierBase:i}}}if(t.length===2){let[a,i]=t;if(a!==p.IdentifierType.Alias&&a!==p.IdentifierType.Hash){let s=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:a,type:p.IdentifierType.Alias,identifier:s,identifierBase:i}}}return{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:e}},L=n=>{let r=new URL(n),t=r.searchParams.get(p.IdentifierParamName);if(t||(t=r.pathname.split("/")[1]),!t)return null;let a=decodeURIComponent(t);return b(a)};import Ar from"qr-code-styling";var N=class{constructor(r,e){this.config=r;this.adapters=e}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!L(r):!1}build(r,e,t){let a=this.config.clientUrl||I.DefaultClientUrl(this.config.env),i=h(r,this.adapters),s=e===p.IdentifierType.Alias?t:e+p.IdentifierParamSeparatorDefault+t,o=i.prefix+p.IdentifierParamSeparatorDefault+s,c=encodeURIComponent(o);return I.SuperClientUrls.includes(a)?`${a}/${c}`:`${a}?${p.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(r){let e=b(r);if(!e)return null;let t=E(e.chainPrefix,this.adapters);return t?this.build(t.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(r,e,t,a=512,i="white",s="black",o="#23F7DD"){let c=h(r,this.adapters),l=this.build(c.chainInfo.name,e,t);return new Ar({type:"svg",width:a,height:a,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var wr="https://",ur=(n,r,e,t,a)=>{let i=e.actions?.[t]?.next||e.next||null;if(!i)return null;if(i.startsWith(wr))return[{identifier:null,url:i}];let[s,o]=i.split("?");if(!o)return[{identifier:s,url:rr(r,s,n)}];let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let g=_(o,{...e.vars,...a}),u=g?`${s}?${g}`:s;return[{identifier:u,url:rr(r,u,n)}]}let l=c[0];if(!l)return[];let d=l.match(/{{([^[]+)\[\]/),m=d?d[1]:null;if(!m||a[m]===void 0)return[];let f=Array.isArray(a[m])?a[m]:[a[m]];if(f.length===0)return[];let C=c.filter(g=>g.includes(`{{${m}[]`)).map(g=>{let u=g.match(/\[\](\.[^}]+)?}}/),W=u&&u[1]||"";return{placeholder:g,field:W?W.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(g=>{let u=o;for(let{regex:S,field:y}of C){let v=y?Cr(g,y):g;if(v==null)return null;u=u.replace(S,v)}if(u.includes("{{")||u.includes("}}"))return null;let W=u?`${s}?${u}`:s;return{identifier:W,url:rr(r,W,n)}}).filter(g=>g!==null)},rr=(n,r,e)=>{let[t,a]=r.split("?"),i=b(t)||{chainPrefix:I.DefaultChainPrefix,type:"alias",identifier:t,identifierBase:t},s=E(i.chainPrefix,n);if(!s)throw new Error(`Adapter not found for chain ${i.chainPrefix}`);let o=new N(e,n).build(s.chainInfo.name,i.type,i.identifierBase);if(!a)return o;let c=new URL(o);return new URLSearchParams(a).forEach((l,d)=>c.searchParams.set(d,l)),c.toString().replace(/\/\?/,"?")},Cr=(n,r)=>r.split(".").reduce((e,t)=>e?.[t],n);var ee=(n,r,e,t)=>{let a=n.providers?.[r];return a?.[e]?a[e]:t},te=(n,r)=>n.providers?.[r];var V=class V{static info(...r){V.isTestEnv||console.info(...r)}static warn(...r){V.isTestEnv||console.warn(...r)}static error(...r){V.isTestEnv||console.error(...r)}};V.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var w=V;var P=class{setTypeRegistry(r){this.typeRegistry=r}nativeToString(r,e){if(r==="asset"&&typeof e=="object"&&e&&"identifier"in e&&"nonce"in e&&"amount"in e)return`${r}:${e.identifier}|${e.nonce.toString()}|${e.amount.toString()}`;if(this.typeRegistry?.hasType(r)){let t=this.typeRegistry.getHandler(r);if(t)return t.nativeToString(e)}return`${r}:${e?.toString()??""}`}stringToNative(r){let e=r.split(p.ArgParamsSeparator),t=e[0],a=e.slice(1).join(p.ArgParamsSeparator);if(t==="null")return[t,null];if(t==="option"){let[i,s]=a.split(p.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(t==="optional"){let[i,s]=a.split(p.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(t==="list"){let i=a.split(p.ArgParamsSeparator),s=i.slice(0,-1).join(p.ArgParamsSeparator),o=i[i.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`list:${s}`,l]}else if(t==="variadic"){let i=a.split(p.ArgParamsSeparator),s=i.slice(0,-1).join(p.ArgParamsSeparator),o=i[i.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`variadic:${s}`,l]}else if(t.startsWith("composite")){let i=t.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=a.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${i[l]}:${c}`)[1]);return[t,o]}else{if(t==="string")return[t,a];if(t==="uint8"||t==="uint16"||t==="uint32")return[t,Number(a)];if(t==="uint64"||t==="biguint")return[t,BigInt(a||0)];if(t==="bool")return[t,a==="true"];if(t==="address")return[t,a];if(t==="hex")return[t,a];if(t==="codemeta")return[t,a];if(t==="asset"){let[i,s,o]=a.split(p.ArgCompositeSeparator),c={identifier:i,nonce:BigInt(s),amount:BigInt(o)};return[t,c]}}if(this.typeRegistry?.hasType(t)){let i=this.typeRegistry.getHandler(t);if(i){let s=i.stringToNative(a);return[t,s]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${t}`)}};var dr=async(n,r,e,t,a)=>{let i=[],s={};for(let[o,c]of Object.entries(n.results||{})){if(c.startsWith(p.Transform.Prefix))continue;let l=Tr(c);if(l!==null&&l!==e){s[o]=null;continue}let[d,...m]=c.split("."),f=(C,T)=>T.reduce((g,u)=>g&&g[u]!==void 0?g[u]:null,C);if(d==="out"||d.startsWith("out[")){let C=m.length===0?r?.data||r:f(r,m);i.push(C),s[o]=C}else s[o]=c}return{values:i,results:await Ir(n,s,e,t,a)}},Ir=async(n,r,e,t,a)=>{if(!n.results)return r;let i={...r};return i=br(i,n,e,t),i=await Pr(n,i,a),i},br=(n,r,e,t)=>{let a={...n},i=$(r,e)?.inputs||[],s=new P;for(let[o,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("input.")){let l=c.split(".")[1],d=i.findIndex(f=>f.as===l||f.name===l),m=d!==-1?t[d]?.value:null;a[o]=m?s.stringToNative(m)[1]:null}return a},Pr=async(n,r,e)=>{if(!n.results)return r;let t={...r},a=Object.entries(n.results).filter(([,i])=>i.startsWith(p.Transform.Prefix)).map(([i,s])=>({key:i,code:s.substring(p.Transform.Prefix.length)}));if(a.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform results are defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:i,code:s}of a)try{t[i]=await e.run(s,t)}catch(o){w.error(`Transform error for result '${i}':`,o),t[i]=null}return t},Tr=n=>{if(n==="out")return 1;let r=n.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};async function Sr(n,r,e,t=5){let a=await sr(64,e),i=new Date(Date.now()+t*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:a,expiresAt:i,purpose:r}),nonce:a,expiresAt:i}}async function er(n,r,e,t){let a=t||`prove-wallet-ownership for app "${r}"`;return Sr(n,a,e,5)}function tr(n,r,e,t){return{"X-Signer-Wallet":n,"X-Signer-Signature":r,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":t}}async function ge(n,r,e,t){let{message:a,nonce:i,expiresAt:s}=await er(n,e,t),o=await r(a);return tr(n,o,i,s)}function he(n){let r=new Date(n).getTime();return Date.now()<r}function me(n){try{let r=JSON.parse(n);if(!r.wallet||!r.nonce||!r.expiresAt||!r.purpose)throw new Error("Invalid signed message: missing required fields");return r}catch(r){throw new Error(`Failed to parse signed message: ${r instanceof Error?r.message:"Unknown error"}`)}}var Er=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],ye=n=>Er.find(r=>r.id===n)||null;var Ae=n=>A.String+p.ArgParamsSeparator+n,we=n=>A.U8+p.ArgParamsSeparator+n,Ce=n=>A.U16+p.ArgParamsSeparator+n,Ie=n=>A.U32+p.ArgParamsSeparator+n,be=n=>A.U64+p.ArgParamsSeparator+n,Pe=n=>A.Biguint+p.ArgParamsSeparator+n,Te=n=>A.Boolean+p.ArgParamsSeparator+n,Se=n=>A.Address+p.ArgParamsSeparator+n,Ee=n=>A.Asset+p.ArgParamsSeparator+n.identifier+p.ArgCompositeSeparator+BigInt(n.nonce||0).toString()+p.ArgCompositeSeparator+n.amount,Re=n=>A.Hex+p.ArgParamsSeparator+n;import Rr from"ajv";var fr=class{constructor(r){this.pendingBrand={protocol:M("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,e=!0){let t=JSON.parse(r);return e&&await this.ensureValidSchema(t),t}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,e){if(!r)throw new Error(`Warp: ${e}`)}async ensureValidSchema(r){let e=this.config.schema?.brand||I.LatestBrandSchemaUrl,a=await(await fetch(e)).json(),i=new Rr,s=i.compile(a);if(!s(r))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import Br from"ajv";var k=class{constructor(r){this.config=r;this.config=r}async validate(r){let e=[];return e.push(...this.validateMaxOneValuePosition(r)),e.push(...this.validateVariableNamesAndResultNamesUppercase(r)),e.push(...this.validateAbiIsSetIfApplicable(r)),e.push(...await this.validateSchema(r)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(r){return r.actions.filter(t=>t.inputs?t.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let e=[],t=(a,i)=>{a&&Object.keys(a).forEach(s=>{s!==s.toUpperCase()&&e.push(`${i} name '${s}' must be uppercase`)})};return t(r.vars,"Variable"),t(r.results,"Result"),e}validateAbiIsSetIfApplicable(r){let e=r.actions.some(s=>s.type==="contract"),t=r.actions.some(s=>s.type==="query");if(!e&&!t)return[];let a=r.actions.some(s=>s.abi),i=Object.values(r.results||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return r.results&&!a&&i?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let e=this.config.schema?.warp||I.LatestWarpSchemaUrl,a=await(await fetch(e)).json(),i=new Br({strict:!1}),s=i.compile(a);return s(r)?[]:[`Schema validation failed: ${i.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var gr=class{constructor(r){this.config=r;this.pendingWarp={protocol:M("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,e=!0){let t=JSON.parse(r);return e&&await this.validate(t),t}async createFromUrl(r){return await(await fetch(r)).json()}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,e=100){return pr(r,e)}ensure(r,e){if(!r)throw new Error(e)}async validate(r){let t=await new k(this.config).validate(r);if(!t.valid)throw new Error(t.errors.join(`
2
- `))}};var D=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let e=localStorage.getItem(this.getKey(r));if(!e)return null;let t=JSON.parse(e);return Date.now()>t.expiresAt?(localStorage.removeItem(this.getKey(r)),null):t.value}catch{return null}}set(r,e,t){let a={value:e,expiresAt:Date.now()+t*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(a))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let e=localStorage.key(r);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var R=class R{get(r){let e=R.cache.get(r);return e?Date.now()>e.expiresAt?(R.cache.delete(r),null):e.value:null}set(r,e,t){let a=Date.now()+t*1e3;R.cache.set(r,{value:e,expiresAt:a})}forget(r){R.cache.delete(r)}clear(){R.cache.clear()}};R.cache=new Map;var F=R;var hr={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},mr={Warp:(n,r)=>`warp:${n}:${r}`,WarpAbi:(n,r)=>`warp-abi:${n}:${r}`,WarpExecutable:(n,r,e)=>`warp-exec:${n}:${r}:${e}`,RegistryInfo:(n,r)=>`registry-info:${n}:${r}`,Brand:(n,r)=>`brand:${n}:${r}`},G=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new D:r==="memory"?new F:typeof window<"u"&&window.localStorage?new D:new F}set(r,e,t){this.strategy.set(r,e,t)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var q=class{constructor(){this.typeHandlers=new Map}registerType(r,e){this.typeHandlers.set(r,e)}hasType(r){return this.typeHandlers.has(r)}getHandler(r){return this.typeHandlers.get(r)}getRegisteredTypes(){return Array.from(this.typeHandlers.keys())}};var H=class{constructor(r,e){this.config=r;this.adapters=e;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new P,this.cache=new G(r.cache?.type);let t=new q;this.serializer.setTypeRegistry(t);for(let a of e)a.registerTypes&&a.registerTypes(t)}async createExecutable(r,e,t){let a=$(r,e);if(!a)throw new Error("WarpFactory: Action not found");let i=await this.getChainInfoForAction(a,t),s=await this.getResolvedInputs(i.name,a,t),o=this.getModifiedInputs(s),c=o.find(x=>x.input.position==="receiver")?.value,l="address"in a?a.address:null,d=c?.split(":")[1]||l;if(!d)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let m=d,f=this.getPreparedArgs(a,o),C=o.find(x=>x.input.position==="value")?.value||null,T="value"in a?a.value:null,g=BigInt(C?.split(":")[1]||T||0),u=o.filter(x=>x.input.position==="transfer"&&x.value).map(x=>x.value),y=[...("transfers"in a?a.transfers:[])||[],...u||[]].map(x=>this.serializer.stringToNative(x)[1]),v=o.find(x=>x.input.position==="data")?.value,Q="data"in a?a.data||"":null,j={warp:r,chain:i,action:e,destination:m,args:f,value:g,transfers:y,data:v||Q||null,resolvedInputs:o};return this.cache.set(mr.WarpExecutable(this.config.env,r.meta?.hash||"",e),j.resolvedInputs,hr.OneWeek),j}async getChainInfoForAction(r,e){if(r.chain)return h(r.chain,this.adapters).chainInfo;if(e){let a=await this.tryGetChainFromInputs(r,e);if(a)return a}return this.adapters[0].chainInfo}async getResolvedInputs(r,e,t){let a=e.inputs||[],i=await Promise.all(t.map(o=>this.preprocessInput(r,o))),s=(o,c)=>{if(o.source==="query"){let l=this.url.searchParams.get(o.name);return l?this.serializer.nativeToString(o.type,l):null}else return o.source===p.Source.UserWallet?this.config.user?.wallets?.[r]?this.serializer.nativeToString("address",this.config.user.wallets[r]):null:i[c]||null};return a.map((o,c)=>{let l=s(o,c);return{input:o,value:l||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((e,t)=>{if(e.input.modifier?.startsWith("scale:")){let[,a]=e.input.modifier.split(":");if(isNaN(Number(a))){let i=Number(r.find(c=>c.input.name===a)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=Y(s,+i);return{...e,value:`${e.input.type}:${o}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=Y(i,+a);return{...e,value:`${e.input.type}:${s}`}}}else return e})}async preprocessInput(r,e){try{let[t,a]=e.split(p.ArgParamsSeparator,2),i=h(r,this.adapters);return i.executor.preprocessInput(i.chainInfo,e,t,a)}catch{return e}}getPreparedArgs(r,e){let t="args"in r?r.args||[]:[];return e.forEach(({input:a,value:i})=>{if(!i||!a.position?.startsWith("arg:"))return;let s=Number(a.position.split(":")[1])-1;t.splice(s,0,i)}),t}async tryGetChainFromInputs(r,e){let t=r.inputs?.findIndex(c=>c.position==="chain");if(t===-1||t===void 0)return null;let a=e[t];if(!a)throw new Error("Chain input not found");let s=new P().stringToNative(a)[1];return h(s,this.adapters).chainInfo}};var O=class{constructor(r,e){this.config=r;this.adapter=e}async apply(r,e){let t=this.applyVars(r,e);return await this.applyGlobals(r,t)}async applyGlobals(r,e){let t={...e};return t.actions=await Promise.all(t.actions.map(async a=>await this.applyActionGlobals(a))),t=await this.applyRootGlobals(t,r),t}applyVars(r,e){if(!e?.vars)return e;let t=JSON.stringify(e),a=(i,s)=>{t=t.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(e.vars).forEach(([i,s])=>{if(typeof s!="string")a(i,s);else if(s.startsWith(`${p.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${p.Vars.Query}:`)[1],c=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);c&&a(i,c)}else if(s.startsWith(`${p.Vars.Env}:`)){let o=s.split(`${p.Vars.Env}:`)[1],c=r.vars?.[o];c&&a(i,c)}else if(s===p.Source.UserWallet&&r.user?.wallets?.[this.adapter.chainInfo.name]){let o=r.user.wallets[this.adapter.chainInfo.name];o&&a(i,o)}else a(i,s)}),JSON.parse(t)}async applyRootGlobals(r,e){let t=JSON.stringify(r),a={config:e,chain:this.adapter.chainInfo.name,chainInfo:this.adapter.chainInfo};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(a);s!=null&&(t=t.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(t)}async applyActionGlobals(r){let e=r.chain?this.adapter.chainInfo:this.adapter.chainInfo;if(!e)throw new Error(`Chain info not found for ${r.chain}`);let t=JSON.stringify(r),a={config:this.config,chain:this.adapter.chainInfo.name,chainInfo:e};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(a);s!=null&&(t=t.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(t)}};var z=class{constructor(r,e,t){this.config=r;this.adapters=e;this.handlers=t;this.handlers=t,this.factory=new H(r,e),this.serializer=new P}async execute(r,e){let{action:t,actionIndex:a}=or(r);if(t.type==="collect"){let o=await this.executeCollect(r,a,e);return o.success?this.handlers?.onExecuted?.(o):this.handlers?.onError?.({message:JSON.stringify(o.values)}),{tx:null,chain:null}}let i=await this.factory.createExecutable(r,a,e);return{tx:await h(i.chain.name,this.adapters).executor.createTransaction(i),chain:i.chain}}async evaluateResults(r,e,t){let a=await h(e,this.adapters).results.getTransactionExecutionResults(r,t);this.handlers?.onExecuted?.(a)}async executeCollect(r,e,t,a){let i=$(r,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let s=await this.factory.getChainInfoForAction(i),o=h(s.name,this.adapters),c=await new O(this.config,o).apply(this.config,r),l=await this.factory.getResolvedInputs(s.name,i,t),d=this.factory.getModifiedInputs(l),m=u=>{if(!u.value)return null;let W=this.serializer.stringToNative(u.value)[1];if(u.input.type==="biguint")return W.toString();if(u.input.type==="asset"){let{identifier:S,nonce:y,amount:v}=W;return{identifier:S,nonce:y.toString(),amount:v.toString()}}else return W},f=new Headers;if(f.set("Content-Type","application/json"),f.set("Accept","application/json"),this.handlers?.onSignRequest){let u=this.config.user?.wallets?.[s.name];if(!u)throw new Error(`No wallet configured for chain ${s.name}`);let{message:W,nonce:S,expiresAt:y}=await er(u,`${s.name}-adapter`),v=await this.handlers.onSignRequest({message:W,chain:s}),Q=tr(u,v,S,y);Object.entries(Q).forEach(([nr,j])=>f.set(nr,j))}Object.entries(i.destination.headers||{}).forEach(([u,W])=>{f.set(u,W)});let C=Object.fromEntries(d.map(u=>[u.input.as||u.input.name,m(u)])),T=i.destination.method||"GET",g=T==="GET"?void 0:JSON.stringify({...C,...a});w.info("Executing collect",{url:i.destination.url,method:T,headers:f,body:g});try{let u=await fetch(i.destination.url,{method:T,headers:f,body:g}),W=await u.json(),{values:S,results:y}=await dr(c,W,e,d,this.config.transform?.runner),v=ur(this.config,this.adapters,c,e,y);return{success:u.ok,warp:c,action:e,user:this.config.user?.wallets?.[s.name]||null,txHash:null,tx:null,next:v,values:S,results:{...y,_DATA:W},messages:cr(c,y)}}catch(u){return w.error("WarpActionExecutor: Error executing collect",u),{success:!1,warp:c,action:e,user:this.config.user?.wallets?.[s.name]||null,txHash:null,tx:null,next:null,values:[],results:{_DATA:u},messages:{}}}}};var J=class{constructor(r){this.config=r}async search(r,e,t){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let a=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...t},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...e})});if(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw w.error("WarpIndex: Error searching for warps: ",a),a}}};var K=class{constructor(r,e){this.config=r;this.adapters=e}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!L(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let a=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),s=(await Promise.all(a)).filter(l=>l.match),o=s.length>0,c=s.map(l=>({url:l.url,warp:l.warp}));return{match:o,results:c}}async detect(r,e){let t={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},a=r.startsWith(p.HttpProtocolPrefix)?L(r):b(r);if(!a)return t;try{let{type:i,identifierBase:s}=a,o=null,c=null,l=null,d=E(a.chainPrefix,this.adapters);if(i==="hash"){o=await d.builder().createFromTransactionHash(s,e);let f=await d.registry.getInfoByHash(s,e);c=f.registryInfo,l=f.brand}else if(i==="alias"){let f=await d.registry.getInfoByAlias(s,e);c=f.registryInfo,l=f.brand,f.registryInfo&&(o=await d.builder().createFromTransactionHash(f.registryInfo.hash,e))}let m=o?await new O(this.config,d).apply(this.config,o):null;return m?{match:!0,url:r,warp:m,chain:d.chainInfo.name,registryInfo:c,brand:l}:t}catch(i){return w.error("Error detecting warp link",i),t}}};var Wr=class{constructor(r,e){this.config=r;this.adapters=e}getConfig(){return this.config}setConfig(r){return this.config=r,this}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new z(this.config,this.adapters,r)}async detectWarp(r,e){return new K(this.config,this.adapters).detect(r,e)}async executeWarp(r,e,t,a={}){let i=r.startsWith("http")&&r.endsWith(".json")?await(await fetch(r)).json():(await this.detectWarp(r,a.cache)).warp;if(!i)throw new Error("Warp not found");let s=this.createExecutor(t),{tx:o,chain:c}=await s.execute(i,e);return{tx:o,chain:c,evaluateResults:async d=>{if(!c||!o||!i)throw new Error("Warp not found");await s.evaluateResults(i,c.name,d)}}}createInscriptionTransaction(r,e){return h(r,this.adapters).builder().createInscriptionTransaction(e)}async createFromTransaction(r,e,t=!1){return h(r,this.adapters).builder().createFromTransaction(e,t)}async createFromTransactionHash(r,e){let t=b(r);if(!t)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return E(t.chainPrefix,this.adapters).builder().createFromTransactionHash(r,e)}async signMessage(r,e,t){if(!this.config.user?.wallets?.[r])throw new Error(`No wallet configured for chain ${r}`);return h(r,this.adapters).executor.signMessage(e,t)}getExplorer(r){return h(r,this.adapters).explorer}getResults(r){return h(r,this.adapters).results}async getRegistry(r){let e=h(r,this.adapters).registry;return await e.init(),e}getDataLoader(r){return h(r,this.adapters).dataLoader}get factory(){return new H(this.config,this.adapters)}get index(){return new J(this.config)}get linkBuilder(){return new N(this.config,this.adapters)}createBuilder(r){return h(r,this.adapters).builder()}createAbiBuilder(r){return h(r,this.adapters).abiBuilder()}createBrandBuilder(r){return h(r,this.adapters).brandBuilder()}};export{X as BrowserCryptoProvider,hr as CacheTtl,Er as KnownTokens,Z as NodeCryptoProvider,fr as WarpBrandBuilder,gr as WarpBuilder,G as WarpCache,mr as WarpCacheKey,yr as WarpChainName,Wr as WarpClient,I as WarpConfig,p as WarpConstants,z as WarpExecutor,H as WarpFactory,J as WarpIndex,A as WarpInputTypes,O as WarpInterpolator,N as WarpLinkBuilder,K as WarpLinkDetecter,w as WarpLogger,U as WarpProtocolVersions,P as WarpSerializer,q as WarpTypeRegistryImpl,k as WarpValidator,Se as address,cr as applyResultsToMessages,Ee as asset,Pe as biguint,Te as boolean,Hr as bytesToBase64,xr as bytesToHex,tr as createAuthHeaders,er as createAuthMessage,Lr as createCryptoProvider,ge as createHttpAuthHeaders,Sr as createSignableMessage,Ir as evaluateResultsCommon,dr as extractCollectResults,L as extractIdentifierInfoFromUrl,ye as findKnownTokenById,E as findWarpAdapterByPrefix,h as findWarpAdapterForChain,or as findWarpExecutableAction,ar as getCryptoProvider,M as getLatestProtocolIdentifier,ur as getNextInfo,te as getProviderConfig,ee as getProviderUrl,ir as getRandomBytes,sr as getRandomHex,$ as getWarpActionByIndex,b as getWarpInfoFromIdentifier,Re as hex,Tr as parseResultsOutIndex,me as parseSignedMessage,_ as replacePlaceholders,Vr as setCryptoProvider,Y as shiftBigintBy,Ae as string,Or as testCryptoAvailability,pr as toPreviewText,Ce as u16,Ie as u32,be as u64,we as u8,he as validateSignedMessage};
1
+ var Wr=(o=>(o.Multiversx="multiversx",o.Vibechain="vibechain",o.Sui="sui",o.Ethereum="ethereum",o.Base="base",o.Arbitrum="arbitrum",o.Fastset="fastset",o))(Wr||{}),c={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},A={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",U128:"u128",U256:"u256",Biguint:"biguint",Boolean:"boolean",Address:"address",Asset:"asset",Hex:"hex"};var U={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},b={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${U.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${U.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",DefaultChainPrefix:"mvx",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],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 X=class{async getRandomBytes(r){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(r);return window.crypto.getRandomValues(e),e}},Z=class{async getRandomBytes(r){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(r))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},B=null;function nr(){if(B)return B;if(typeof window<"u"&&window.crypto)return B=new X,B;if(typeof process<"u"&&process.versions?.node)return B=new Z,B;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Nr(n){B=n}async function ar(n,r){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(r||nr()).getRandomBytes(n)}function yr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let r=new Array(n.length*2);for(let e=0;e<n.length;e++){let t=n[e];r[e*2]=(t>>>4).toString(16),r[e*2+1]=(t&15).toString(16)}return r.join("")}function Vr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(n).toString("base64");if(typeof btoa<"u"){let r=String.fromCharCode.apply(null,Array.from(n));return btoa(r)}else throw new Error("Base64 encoding not available in this environment")}async function ir(n,r){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let e=await ar(n/2,r);return yr(e)}async function Hr(){let n={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?n.environment="browser":typeof process<"u"&&process.versions?.node&&(n.environment="nodejs"),await ar(16),n.randomBytes=!0}catch{}return n}function Or(){return nr()}var h=(n,r)=>{let e=r.find(t=>t.chainInfo.name.toLowerCase()===n.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${n}`);return e},E=(n,r)=>{let e=r.find(t=>t.prefix.toLowerCase()===n.toLowerCase());if(!e)throw new Error(`Adapter not found for prefix: ${n}`);return e},k=n=>{if(n==="warp")return`warp:${U.Warp}`;if(n==="brand")return`brand:${U.Brand}`;if(n==="abi")return`abi:${U.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},$=(n,r)=>n?.actions[r-1],sr=n=>(n.actions.forEach((r,e)=>{if(r.type!=="link")return{action:r,actionIndex:e}}),{action:$(n,1),actionIndex:1}),Y=(n,r)=>{let e=n.toString(),[t,a=""]=e.split("."),i=Math.abs(r);if(r>0)return BigInt(t+a.padEnd(i,"0"));if(r<0){let s=t+a;if(i>=s.length)return 0n;let o=s.slice(0,-i)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},or=(n,r=100)=>{if(!n)return"";let e=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>r?e.substring(0,e.lastIndexOf(" ",r))+"...":e,e},_=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(e,t)=>r[t]||""),pr=(n,r)=>{let e=Object.entries(n.messages||{}).map(([t,a])=>[t,_(a,r)]);return Object.fromEntries(e)};var xr=n=>{let r=c.IdentifierParamSeparator,e=-1,t="";for(let a of r){let i=n.indexOf(a);i!==-1&&(e===-1||i<e)&&(e=i,t=a)}return e!==-1?{separator:t,index:e}:null},cr=n=>{let r=xr(n);if(!r)return[n];let{separator:e,index:t}=r,a=n.substring(0,t),i=n.substring(t+e.length),s=cr(i);return[a,...s]},P=n=>{let r=decodeURIComponent(n).trim(),e=r.split("?")[0],t=cr(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chainPrefix:c.IdentifierChainDefault,type:c.IdentifierType.Hash,identifier:r,identifierBase:e};if(t.length===2&&/^[a-zA-Z0-9]{62}$/.test(t[0])&&/^[a-zA-Z0-9]{2}$/.test(t[1]))return null;if(t.length===3){let[a,i,s]=t;if(i===c.IdentifierType.Alias||i===c.IdentifierType.Hash){let o=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:a,type:i,identifier:o,identifierBase:s}}}if(t.length===2){let[a,i]=t;if(a===c.IdentifierType.Alias||a===c.IdentifierType.Hash){let s=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:c.IdentifierChainDefault,type:a,identifier:s,identifierBase:i}}}if(t.length===2){let[a,i]=t;if(a!==c.IdentifierType.Alias&&a!==c.IdentifierType.Hash){let s=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:a,type:c.IdentifierType.Alias,identifier:s,identifierBase:i}}}return{chainPrefix:c.IdentifierChainDefault,type:c.IdentifierType.Alias,identifier:r,identifierBase:e}},L=n=>{let r=new URL(n),t=r.searchParams.get(c.IdentifierParamName);if(t||(t=r.pathname.split("/")[1]),!t)return null;let a=decodeURIComponent(t);return P(a)};import vr from"qr-code-styling";var N=class{constructor(r,e){this.config=r;this.adapters=e}isValid(r){return r.startsWith(c.HttpProtocolPrefix)?!!L(r):!1}build(r,e,t){let a=this.config.clientUrl||b.DefaultClientUrl(this.config.env),i=h(r,this.adapters),s=e===c.IdentifierType.Alias?t:e+c.IdentifierParamSeparatorDefault+t,o=i.prefix+c.IdentifierParamSeparatorDefault+s,p=encodeURIComponent(o);return b.SuperClientUrls.includes(a)?`${a}/${p}`:`${a}?${c.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(r){let e=P(r);if(!e)return null;let t=E(e.chainPrefix,this.adapters);return t?this.build(t.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(r,e,t,a=512,i="white",s="black",o="#23F7DD"){let p=h(r,this.adapters),l=this.build(p.chainInfo.name,e,t);return new vr({type:"svg",width:a,height:a,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Ar="https://",lr=(n,r,e,t,a)=>{let i=e.actions?.[t]?.next||e.next||null;if(!i)return null;if(i.startsWith(Ar))return[{identifier:null,url:i}];let[s,o]=i.split("?");if(!o)return[{identifier:s,url:rr(r,s,n)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let g=_(o,{...e.vars,...a}),u=g?`${s}?${g}`:s;return[{identifier:u,url:rr(r,u,n)}]}let l=p[0];if(!l)return[];let d=l.match(/{{([^[]+)\[\]/),m=d?d[1]:null;if(!m||a[m]===void 0)return[];let f=Array.isArray(a[m])?a[m]:[a[m]];if(f.length===0)return[];let C=p.filter(g=>g.includes(`{{${m}[]`)).map(g=>{let u=g.match(/\[\](\.[^}]+)?}}/),W=u&&u[1]||"";return{placeholder:g,field:W?W.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(g=>{let u=o;for(let{regex:I,field:x}of C){let v=x?wr(g,x):g;if(v==null)return null;u=u.replace(I,v)}if(u.includes("{{")||u.includes("}}"))return null;let W=u?`${s}?${u}`:s;return{identifier:W,url:rr(r,W,n)}}).filter(g=>g!==null)},rr=(n,r,e)=>{let[t,a]=r.split("?"),i=P(t)||{chainPrefix:b.DefaultChainPrefix,type:"alias",identifier:t,identifierBase:t},s=E(i.chainPrefix,n);if(!s)throw new Error(`Adapter not found for chain ${i.chainPrefix}`);let o=new N(e,n).build(s.chainInfo.name,i.type,i.identifierBase);if(!a)return o;let p=new URL(o);return new URLSearchParams(a).forEach((l,d)=>p.searchParams.set(d,l)),p.toString().replace(/\/\?/,"?")},wr=(n,r)=>r.split(".").reduce((e,t)=>e?.[t],n);var re=(n,r,e,t)=>{let a=n.providers?.[r];return a?.[e]?a[e]:t},ee=(n,r)=>n.providers?.[r];var V=class V{static info(...r){V.isTestEnv||console.info(...r)}static warn(...r){V.isTestEnv||console.warn(...r)}static error(...r){V.isTestEnv||console.error(...r)}};V.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var w=V;var T=class{setTypeRegistry(r){this.typeRegistry=r}nativeToString(r,e){if(r==="asset"&&typeof e=="object"&&e&&"identifier"in e&&"nonce"in e&&"amount"in e)return`${r}:${e.identifier}|${e.nonce.toString()}|${e.amount.toString()}`;if(this.typeRegistry?.hasType(r)){let t=this.typeRegistry.getHandler(r);if(t)return t.nativeToString(e)}return`${r}:${e?.toString()??""}`}stringToNative(r){let e=r.split(c.ArgParamsSeparator),t=e[0],a=e.slice(1).join(c.ArgParamsSeparator);if(t==="null")return[t,null];if(t==="option"){let[i,s]=a.split(c.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(t==="optional"){let[i,s]=a.split(c.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(t==="list"){let i=a.split(c.ArgParamsSeparator),s=i.slice(0,-1).join(c.ArgParamsSeparator),o=i[i.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`list:${s}`,l]}else if(t==="variadic"){let i=a.split(c.ArgParamsSeparator),s=i.slice(0,-1).join(c.ArgParamsSeparator),o=i[i.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`variadic:${s}`,l]}else if(t.startsWith("composite")){let i=t.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),o=a.split(c.ArgCompositeSeparator).map((p,l)=>this.stringToNative(`${i[l]}:${p}`)[1]);return[t,o]}else{if(t==="string")return[t,a];if(t==="uint8"||t==="uint16"||t==="uint32")return[t,Number(a)];if(t==="uint64"||t==="biguint")return[t,BigInt(a||0)];if(t==="bool")return[t,a==="true"];if(t==="address")return[t,a];if(t==="token")return[t,a];if(t==="hex")return[t,a];if(t==="codemeta")return[t,a];if(t==="asset"){let[i,s,o]=a.split(c.ArgCompositeSeparator),p={identifier:i,nonce:BigInt(s),amount:BigInt(o)};return[t,p]}}if(this.typeRegistry?.hasType(t)){let i=this.typeRegistry.getHandler(t);if(i){let s=i.stringToNative(a);return[t,s]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${t}`)}};var ur=async(n,r,e,t,a)=>{let i=[],s={};for(let[o,p]of Object.entries(n.results||{})){if(p.startsWith(c.Transform.Prefix))continue;let l=Pr(p);if(l!==null&&l!==e){s[o]=null;continue}let[d,...m]=p.split("."),f=(C,S)=>S.reduce((g,u)=>g&&g[u]!==void 0?g[u]:null,C);if(d==="out"||d.startsWith("out[")){let C=m.length===0?r?.data||r:f(r,m);i.push(C),s[o]=C}else s[o]=p}return{values:i,results:await Cr(n,s,e,t,a)}},Cr=async(n,r,e,t,a)=>{if(!n.results)return r;let i={...r};return i=Ir(i,n,e,t),i=await br(n,i,a),i},Ir=(n,r,e,t)=>{let a={...n},i=$(r,e)?.inputs||[],s=new T;for(let[o,p]of Object.entries(a))if(typeof p=="string"&&p.startsWith("input.")){let l=p.split(".")[1],d=i.findIndex(f=>f.as===l||f.name===l),m=d!==-1?t[d]?.value:null;a[o]=m?s.stringToNative(m)[1]:null}return a},br=async(n,r,e)=>{if(!n.results)return r;let t={...r},a=Object.entries(n.results).filter(([,i])=>i.startsWith(c.Transform.Prefix)).map(([i,s])=>({key:i,code:s.substring(c.Transform.Prefix.length)}));if(a.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform results are defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:i,code:s}of a)try{t[i]=await e.run(s,t)}catch(o){w.error(`Transform error for result '${i}':`,o),t[i]=null}return t},Pr=n=>{if(n==="out")return 1;let r=n.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};async function Tr(n,r,e,t=5){let a=await ir(64,e),i=new Date(Date.now()+t*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:a,expiresAt:i,purpose:r}),nonce:a,expiresAt:i}}async function er(n,r,e,t){let a=t||`prove-wallet-ownership for app "${r}"`;return Tr(n,a,e,5)}function tr(n,r,e,t){return{"X-Signer-Wallet":n,"X-Signer-Signature":r,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":t}}async function fe(n,r,e,t){let{message:a,nonce:i,expiresAt:s}=await er(n,e,t),o=await r(a);return tr(n,o,i,s)}function ge(n){let r=new Date(n).getTime();return Date.now()<r}function he(n){try{let r=JSON.parse(n);if(!r.wallet||!r.nonce||!r.expiresAt||!r.purpose)throw new Error("Invalid signed message: missing required fields");return r}catch(r){throw new Error(`Failed to parse signed message: ${r instanceof Error?r.message:"Unknown error"}`)}}var Sr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],We=n=>Sr.find(r=>r.id===n)||null;var ve=n=>A.String+c.ArgParamsSeparator+n,Ae=n=>A.U8+c.ArgParamsSeparator+n,we=n=>A.U16+c.ArgParamsSeparator+n,Ce=n=>A.U32+c.ArgParamsSeparator+n,Ie=n=>A.U64+c.ArgParamsSeparator+n,be=n=>A.Biguint+c.ArgParamsSeparator+n,Pe=n=>A.Boolean+c.ArgParamsSeparator+n,Te=n=>A.Address+c.ArgParamsSeparator+n,Se=n=>A.Asset+c.ArgParamsSeparator+n.identifier+c.ArgCompositeSeparator+BigInt(n.nonce||0).toString()+c.ArgCompositeSeparator+n.amount,Ee=n=>A.Hex+c.ArgParamsSeparator+n;import Er from"ajv";var dr=class{constructor(r){this.pendingBrand={protocol:k("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,e=!0){let t=JSON.parse(r);return e&&await this.ensureValidSchema(t),t}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,e){if(!r)throw new Error(`Warp: ${e}`)}async ensureValidSchema(r){let e=this.config.schema?.brand||b.LatestBrandSchemaUrl,a=await(await fetch(e)).json(),i=new Er,s=i.compile(a);if(!s(r))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import Rr from"ajv";var G=class{constructor(r){this.config=r;this.config=r}async validate(r){let e=[];return e.push(...this.validateMaxOneValuePosition(r)),e.push(...this.validateVariableNamesAndResultNamesUppercase(r)),e.push(...this.validateAbiIsSetIfApplicable(r)),e.push(...await this.validateSchema(r)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(r){return r.actions.filter(t=>t.inputs?t.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let e=[],t=(a,i)=>{a&&Object.keys(a).forEach(s=>{s!==s.toUpperCase()&&e.push(`${i} name '${s}' must be uppercase`)})};return t(r.vars,"Variable"),t(r.results,"Result"),e}validateAbiIsSetIfApplicable(r){let e=r.actions.some(s=>s.type==="contract"),t=r.actions.some(s=>s.type==="query");if(!e&&!t)return[];let a=r.actions.some(s=>s.abi),i=Object.values(r.results||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return r.results&&!a&&i?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let e=this.config.schema?.warp||b.LatestWarpSchemaUrl,a=await(await fetch(e)).json(),i=new Rr({strict:!1}),s=i.compile(a);return s(r)?[]:[`Schema validation failed: ${i.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var fr=class{constructor(r){this.config=r;this.pendingWarp={protocol:k("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,e=!0){let t=JSON.parse(r);return e&&await this.validate(t),t}async createFromUrl(r){return await(await fetch(r)).json()}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,e=100){return or(r,e)}ensure(r,e){if(!r)throw new Error(e)}async validate(r){let t=await new G(this.config).validate(r);if(!t.valid)throw new Error(t.errors.join(`
2
+ `))}};var D=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let e=localStorage.getItem(this.getKey(r));if(!e)return null;let t=JSON.parse(e);return Date.now()>t.expiresAt?(localStorage.removeItem(this.getKey(r)),null):t.value}catch{return null}}set(r,e,t){let a={value:e,expiresAt:Date.now()+t*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(a))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let e=localStorage.key(r);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var R=class R{get(r){let e=R.cache.get(r);return e?Date.now()>e.expiresAt?(R.cache.delete(r),null):e.value:null}set(r,e,t){let a=Date.now()+t*1e3;R.cache.set(r,{value:e,expiresAt:a})}forget(r){R.cache.delete(r)}clear(){R.cache.clear()}};R.cache=new Map;var F=R;var gr={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},hr={Warp:(n,r)=>`warp:${n}:${r}`,WarpAbi:(n,r)=>`warp-abi:${n}:${r}`,WarpExecutable:(n,r,e)=>`warp-exec:${n}:${r}:${e}`,RegistryInfo:(n,r)=>`registry-info:${n}:${r}`,Brand:(n,r)=>`brand:${n}:${r}`},q=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new D:r==="memory"?new F:typeof window<"u"&&window.localStorage?new D:new F}set(r,e,t){this.strategy.set(r,e,t)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var z=class{constructor(){this.typeHandlers=new Map}registerType(r,e){this.typeHandlers.set(r,e)}hasType(r){return this.typeHandlers.has(r)}getHandler(r){return this.typeHandlers.get(r)}getRegisteredTypes(){return Array.from(this.typeHandlers.keys())}};var H=class{constructor(r,e){this.config=r;this.adapters=e;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new T,this.cache=new q(r.cache?.type);let t=new z;this.serializer.setTypeRegistry(t);for(let a of e)a.registerTypes&&a.registerTypes(t)}async createExecutable(r,e,t){let a=$(r,e);if(!a)throw new Error("WarpFactory: Action not found");let i=await this.getChainInfoForAction(a,t),s=await this.getResolvedInputs(i.name,a,t),o=this.getModifiedInputs(s),p=o.find(y=>y.input.position==="receiver")?.value,l="address"in a?a.address:null,d=p?this.serializer.stringToNative(p)[1]:l;if(!d)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let m=this.getPreparedArgs(a,o),f=o.find(y=>y.input.position==="value")?.value||null,C="value"in a?a.value:null,S=BigInt(f?.split(":")[1]||C||0),g=o.filter(y=>y.input.position==="transfer"&&y.value).map(y=>y.value),I=[...("transfers"in a?a.transfers:[])||[],...g||[]].map(y=>this.serializer.stringToNative(y)[1]),x=o.find(y=>y.input.position==="data")?.value,v="data"in a?a.data||"":null,M={warp:r,chain:i,action:e,destination:d,args:m,value:S,transfers:I,data:x||v||null,resolvedInputs:o};return this.cache.set(hr.WarpExecutable(this.config.env,r.meta?.hash||"",e),M.resolvedInputs,gr.OneWeek),M}async getChainInfoForAction(r,e){if(r.chain)return h(r.chain,this.adapters).chainInfo;if(e){let a=await this.tryGetChainFromInputs(r,e);if(a)return a}return this.adapters[0].chainInfo}async getResolvedInputs(r,e,t){let a=e.inputs||[],i=await Promise.all(t.map(o=>this.preprocessInput(r,o))),s=(o,p)=>{if(o.source==="query"){let l=this.url.searchParams.get(o.name);return l?this.serializer.nativeToString(o.type,l):null}else return o.source===c.Source.UserWallet?this.config.user?.wallets?.[r]?this.serializer.nativeToString("address",this.config.user.wallets[r]):null:i[p]||null};return a.map((o,p)=>{let l=s(o,p);return{input:o,value:l||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((e,t)=>{if(e.input.modifier?.startsWith("scale:")){let[,a]=e.input.modifier.split(":");if(isNaN(Number(a))){let i=Number(r.find(p=>p.input.name===a)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=Y(s,+i);return{...e,value:`${e.input.type}:${o}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=Y(i,+a);return{...e,value:`${e.input.type}:${s}`}}}else return e})}async preprocessInput(r,e){try{let[t,a]=e.split(c.ArgParamsSeparator,2),i=h(r,this.adapters);return i.executor.preprocessInput(i.chainInfo,e,t,a)}catch{return e}}getPreparedArgs(r,e){let t="args"in r?r.args||[]:[];return e.forEach(({input:a,value:i})=>{if(!i||!a.position?.startsWith("arg:"))return;let s=Number(a.position.split(":")[1])-1;t.splice(s,0,i)}),t}async tryGetChainFromInputs(r,e){let t=r.inputs?.findIndex(p=>p.position==="chain");if(t===-1||t===void 0)return null;let a=e[t];if(!a)throw new Error("Chain input not found");let s=new T().stringToNative(a)[1];return h(s,this.adapters).chainInfo}};var O=class{constructor(r,e){this.config=r;this.adapter=e}async apply(r,e){let t=this.applyVars(r,e);return await this.applyGlobals(r,t)}async applyGlobals(r,e){let t={...e};return t.actions=await Promise.all(t.actions.map(async a=>await this.applyActionGlobals(a))),t=await this.applyRootGlobals(t,r),t}applyVars(r,e){if(!e?.vars)return e;let t=JSON.stringify(e),a=(i,s)=>{t=t.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(e.vars).forEach(([i,s])=>{if(typeof s!="string")a(i,s);else if(s.startsWith(`${c.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${c.Vars.Query}:`)[1],p=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);p&&a(i,p)}else if(s.startsWith(`${c.Vars.Env}:`)){let o=s.split(`${c.Vars.Env}:`)[1],p=r.vars?.[o];p&&a(i,p)}else if(s===c.Source.UserWallet&&r.user?.wallets?.[this.adapter.chainInfo.name]){let o=r.user.wallets[this.adapter.chainInfo.name];o&&a(i,o)}else a(i,s)}),JSON.parse(t)}async applyRootGlobals(r,e){let t=JSON.stringify(r),a={config:e,chain:this.adapter.chainInfo.name,chainInfo:this.adapter.chainInfo};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(a);s!=null&&(t=t.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(t)}async applyActionGlobals(r){let e=r.chain?this.adapter.chainInfo:this.adapter.chainInfo;if(!e)throw new Error(`Chain info not found for ${r.chain}`);let t=JSON.stringify(r),a={config:this.config,chain:this.adapter.chainInfo.name,chainInfo:e};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(a);s!=null&&(t=t.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(t)}};var J=class{constructor(r,e,t){this.config=r;this.adapters=e;this.handlers=t;this.handlers=t,this.factory=new H(r,e),this.serializer=new T}async execute(r,e){let{action:t,actionIndex:a}=sr(r);if(t.type==="collect"){let p=await this.executeCollect(r,a,e);return p.success?this.handlers?.onExecuted?.(p):this.handlers?.onError?.({message:JSON.stringify(p.values)}),{tx:null,chain:null}}let i=await this.factory.createExecutable(r,a,e),s=h(i.chain.name,this.adapters);if(t.type==="query"){let p=await s.executor.executeQuery(i);return p.success?this.handlers?.onExecuted?.(p):this.handlers?.onError?.({message:JSON.stringify(p.values)}),{tx:null,chain:i.chain}}return{tx:await s.executor.createTransaction(i),chain:i.chain}}async evaluateResults(r,e,t){let a=await h(e,this.adapters).results.getTransactionExecutionResults(r,t);this.handlers?.onExecuted?.(a)}async executeCollect(r,e,t,a){let i=$(r,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let s=await this.factory.getChainInfoForAction(i),o=h(s.name,this.adapters),p=await new O(this.config,o).apply(this.config,r),l=await this.factory.getResolvedInputs(s.name,i,t),d=this.factory.getModifiedInputs(l),m=u=>{if(!u.value)return null;let W=this.serializer.stringToNative(u.value)[1];if(u.input.type==="biguint")return W.toString();if(u.input.type==="asset"){let{identifier:I,nonce:x,amount:v}=W;return{identifier:I,nonce:x.toString(),amount:v.toString()}}else return W},f=new Headers;if(f.set("Content-Type","application/json"),f.set("Accept","application/json"),this.handlers?.onSignRequest){let u=this.config.user?.wallets?.[s.name];if(!u)throw new Error(`No wallet configured for chain ${s.name}`);let{message:W,nonce:I,expiresAt:x}=await er(u,`${s.name}-adapter`),v=await this.handlers.onSignRequest({message:W,chain:s}),j=tr(u,v,I,x);Object.entries(j).forEach(([M,y])=>f.set(M,y))}Object.entries(i.destination.headers||{}).forEach(([u,W])=>{f.set(u,W)});let C=Object.fromEntries(d.map(u=>[u.input.as||u.input.name,m(u)])),S=i.destination.method||"GET",g=S==="GET"?void 0:JSON.stringify({...C,...a});w.info("Executing collect",{url:i.destination.url,method:S,headers:f,body:g});try{let u=await fetch(i.destination.url,{method:S,headers:f,body:g}),W=await u.json(),{values:I,results:x}=await ur(p,W,e,d,this.config.transform?.runner),v=lr(this.config,this.adapters,p,e,x);return{success:u.ok,warp:p,action:e,user:this.config.user?.wallets?.[s.name]||null,txHash:null,tx:null,next:v,values:I,valuesRaw:I.map(j=>this.serializer.stringToNative(j)[1]),results:{...x,_DATA:W},messages:pr(p,x)}}catch(u){return w.error("WarpActionExecutor: Error executing collect",u),{success:!1,warp:p,action:e,user:this.config.user?.wallets?.[s.name]||null,txHash:null,tx:null,next:null,values:[],valuesRaw:[],results:{_DATA:u},messages:{}}}}};var Q=class{constructor(r){this.config=r}async search(r,e,t){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let a=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...t},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...e})});if(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw w.error("WarpIndex: Error searching for warps: ",a),a}}};var K=class{constructor(r,e){this.config=r;this.adapters=e}isValid(r){return r.startsWith(c.HttpProtocolPrefix)?!!L(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let a=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),s=(await Promise.all(a)).filter(l=>l.match),o=s.length>0,p=s.map(l=>({url:l.url,warp:l.warp}));return{match:o,results:p}}async detect(r,e){let t={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},a=r.startsWith(c.HttpProtocolPrefix)?L(r):P(r);if(!a)return t;try{let{type:i,identifierBase:s}=a,o=null,p=null,l=null,d=E(a.chainPrefix,this.adapters);if(i==="hash"){o=await d.builder().createFromTransactionHash(s,e);let f=await d.registry.getInfoByHash(s,e);p=f.registryInfo,l=f.brand}else if(i==="alias"){let f=await d.registry.getInfoByAlias(s,e);p=f.registryInfo,l=f.brand,f.registryInfo&&(o=await d.builder().createFromTransactionHash(f.registryInfo.hash,e))}let m=o?await new O(this.config,d).apply(this.config,o):null;return m?{match:!0,url:r,warp:m,chain:d.chainInfo.name,registryInfo:p,brand:l}:t}catch(i){return w.error("Error detecting warp link",i),t}}};var mr=class{constructor(r,e){this.config=r;this.adapters=e}getConfig(){return this.config}setConfig(r){return this.config=r,this}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new J(this.config,this.adapters,r)}async detectWarp(r,e){return new K(this.config,this.adapters).detect(r,e)}async executeWarp(r,e,t,a={}){let i=r.startsWith("http")&&r.endsWith(".json")?await(await fetch(r)).json():(await this.detectWarp(r,a.cache)).warp;if(!i)throw new Error("Warp not found");let s=this.createExecutor(t),{tx:o,chain:p}=await s.execute(i,e);return{tx:o,chain:p,evaluateResults:async d=>{if(!p||!o||!i)throw new Error("Warp not found");await s.evaluateResults(i,p.name,d)}}}createInscriptionTransaction(r,e){return h(r,this.adapters).builder().createInscriptionTransaction(e)}async createFromTransaction(r,e,t=!1){return h(r,this.adapters).builder().createFromTransaction(e,t)}async createFromTransactionHash(r,e){let t=P(r);if(!t)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return E(t.chainPrefix,this.adapters).builder().createFromTransactionHash(r,e)}async signMessage(r,e,t){if(!this.config.user?.wallets?.[r])throw new Error(`No wallet configured for chain ${r}`);return h(r,this.adapters).executor.signMessage(e,t)}getExplorer(r){return h(r,this.adapters).explorer}getResults(r){return h(r,this.adapters).results}async getRegistry(r){let e=h(r,this.adapters).registry;return await e.init(),e}getDataLoader(r){return h(r,this.adapters).dataLoader}get factory(){return new H(this.config,this.adapters)}get index(){return new Q(this.config)}get linkBuilder(){return new N(this.config,this.adapters)}createBuilder(r){return h(r,this.adapters).builder()}createAbiBuilder(r){return h(r,this.adapters).abiBuilder()}createBrandBuilder(r){return h(r,this.adapters).brandBuilder()}};export{X as BrowserCryptoProvider,gr as CacheTtl,Sr as KnownTokens,Z as NodeCryptoProvider,dr as WarpBrandBuilder,fr as WarpBuilder,q as WarpCache,hr as WarpCacheKey,Wr as WarpChainName,mr as WarpClient,b as WarpConfig,c as WarpConstants,J as WarpExecutor,H as WarpFactory,Q as WarpIndex,A as WarpInputTypes,O as WarpInterpolator,N as WarpLinkBuilder,K as WarpLinkDetecter,w as WarpLogger,U as WarpProtocolVersions,T as WarpSerializer,z as WarpTypeRegistryImpl,G as WarpValidator,Te as address,pr as applyResultsToMessages,Se as asset,be as biguint,Pe as boolean,Vr as bytesToBase64,yr as bytesToHex,tr as createAuthHeaders,er as createAuthMessage,Or as createCryptoProvider,fe as createHttpAuthHeaders,Tr as createSignableMessage,Cr as evaluateResultsCommon,ur as extractCollectResults,L as extractIdentifierInfoFromUrl,We as findKnownTokenById,E as findWarpAdapterByPrefix,h as findWarpAdapterForChain,sr as findWarpExecutableAction,nr as getCryptoProvider,k as getLatestProtocolIdentifier,lr as getNextInfo,ee as getProviderConfig,re as getProviderUrl,ar as getRandomBytes,ir as getRandomHex,$ as getWarpActionByIndex,P as getWarpInfoFromIdentifier,Ee as hex,Pr as parseResultsOutIndex,he as parseSignedMessage,_ as replacePlaceholders,Nr as setCryptoProvider,Y as shiftBigintBy,ve as string,Hr as testCryptoAvailability,or as toPreviewText,we as u16,Ce as u32,Ie as u64,Ae as u8,ge as validateSignedMessage};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "3.0.0-alpha.85",
3
+ "version": "3.0.0-alpha.87",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",
@@ -8,6 +8,7 @@
8
8
  ".": {
9
9
  "types": "./dist/index.d.ts",
10
10
  "import": "./dist/index.mjs",
11
+ "require": "./dist/index.js",
11
12
  "default": "./dist/index.mjs"
12
13
  }
13
14
  },