@opendatalabs/vana-sdk 0.1.0-alpha.606fa2d → 0.1.0-alpha.61efc06

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.
Files changed (44) hide show
  1. package/README.md +4 -13
  2. package/dist/{browser-Bb8gLWHp.d.ts → browser-DY8XDblx.d.ts} +14 -61
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +106 -723
  5. package/dist/browser.js.map +1 -1
  6. package/dist/chains.browser.cjs +2 -2
  7. package/dist/chains.browser.cjs.map +1 -1
  8. package/dist/chains.browser.js +2 -2
  9. package/dist/chains.browser.js.map +1 -1
  10. package/dist/chains.cjs +2 -2
  11. package/dist/chains.cjs.map +1 -1
  12. package/dist/chains.js +2 -2
  13. package/dist/chains.js.map +1 -1
  14. package/dist/chains.node.cjs +2 -2
  15. package/dist/chains.node.cjs.map +1 -1
  16. package/dist/chains.node.js +2 -2
  17. package/dist/chains.node.js.map +1 -1
  18. package/dist/index.browser.d.ts +201 -342
  19. package/dist/index.browser.js +628 -861
  20. package/dist/index.browser.js.map +1 -1
  21. package/dist/index.node.cjs +666 -1010
  22. package/dist/index.node.cjs.map +1 -1
  23. package/dist/index.node.d.cts +205 -101
  24. package/dist/index.node.d.ts +205 -101
  25. package/dist/index.node.js +668 -1024
  26. package/dist/index.node.js.map +1 -1
  27. package/dist/node.cjs +53 -692
  28. package/dist/node.cjs.map +1 -1
  29. package/dist/node.js +52 -704
  30. package/dist/node.js.map +1 -1
  31. package/dist/platform.browser.d.ts +2 -2
  32. package/dist/platform.browser.js +116 -780
  33. package/dist/platform.browser.js.map +1 -1
  34. package/dist/platform.cjs +156 -933
  35. package/dist/platform.cjs.map +1 -1
  36. package/dist/platform.js +156 -945
  37. package/dist/platform.js.map +1 -1
  38. package/dist/platform.node.cjs +156 -933
  39. package/dist/platform.node.cjs.map +1 -1
  40. package/dist/platform.node.d.cts +14 -61
  41. package/dist/platform.node.d.ts +14 -61
  42. package/dist/platform.node.js +156 -945
  43. package/dist/platform.node.js.map +1 -1
  44. package/package.json +15 -31
@@ -10,6 +10,53 @@ var __export = (target, all) => {
10
10
  };
11
11
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
12
12
 
13
+ // src/platform/shared/crypto-utils.ts
14
+ function processWalletPublicKey(publicKey) {
15
+ const publicKeyHex = publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey;
16
+ const publicKeyBytes = Buffer.from(publicKeyHex, "hex");
17
+ return publicKeyBytes.length === 64 ? Buffer.concat([Buffer.from([4]), publicKeyBytes]) : publicKeyBytes;
18
+ }
19
+ function processWalletPrivateKey(privateKey) {
20
+ const privateKeyHex = privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey;
21
+ return Buffer.from(privateKeyHex, "hex");
22
+ }
23
+ function parseEncryptedDataBuffer(encryptedBuffer) {
24
+ return {
25
+ iv: encryptedBuffer.slice(0, 16),
26
+ ephemPublicKey: encryptedBuffer.slice(16, 81),
27
+ // 65 bytes for uncompressed public key
28
+ ciphertext: encryptedBuffer.slice(81, -32),
29
+ mac: encryptedBuffer.slice(-32)
30
+ };
31
+ }
32
+ function toBase64(str) {
33
+ if (typeof Buffer !== "undefined") {
34
+ return Buffer.from(str, "utf8").toString("base64");
35
+ } else if (typeof btoa !== "undefined") {
36
+ return btoa(str);
37
+ } else {
38
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
39
+ let result = "";
40
+ let i = 0;
41
+ while (i < str.length) {
42
+ const a = str.charCodeAt(i++);
43
+ const b = i < str.length ? str.charCodeAt(i++) : 0;
44
+ const c = i < str.length ? str.charCodeAt(i++) : 0;
45
+ const bitmap = a << 16 | b << 8 | c;
46
+ result += chars.charAt(bitmap >> 18 & 63);
47
+ result += chars.charAt(bitmap >> 12 & 63);
48
+ result += i - 2 < str.length ? chars.charAt(bitmap >> 6 & 63) : "=";
49
+ result += i - 1 < str.length ? chars.charAt(bitmap & 63) : "=";
50
+ }
51
+ return result;
52
+ }
53
+ }
54
+ var init_crypto_utils = __esm({
55
+ "src/platform/shared/crypto-utils.ts"() {
56
+ "use strict";
57
+ }
58
+ });
59
+
13
60
  // src/platform/shared/pgp-utils.ts
14
61
  function processPGPKeyOptions(options) {
15
62
  return {
@@ -71,823 +118,118 @@ var init_lazy_import = __esm({
71
118
  }
72
119
  });
73
120
 
74
- // src/utils/encoding.ts
75
- function toBase64(data) {
76
- if (typeof Buffer !== "undefined" && Buffer.from) {
77
- return Buffer.from(data).toString("base64");
78
- }
79
- if (typeof btoa !== "undefined") {
80
- const binary = Array.from(data, (byte) => String.fromCharCode(byte)).join(
81
- ""
82
- );
83
- return btoa(binary);
84
- }
85
- throw new Error("No base64 encoding method available in this environment");
86
- }
87
- function toHex(data) {
88
- if (typeof Buffer !== "undefined" && Buffer.from) {
89
- return Buffer.from(data).toString("hex");
90
- }
91
- return Array.from(data, (byte) => byte.toString(16).padStart(2, "0")).join(
92
- ""
93
- );
94
- }
95
- function fromHex(hex) {
96
- const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
97
- if (cleanHex.length % 2 !== 0) {
98
- throw new Error("Invalid hex string: odd length");
99
- }
100
- if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {
101
- throw new Error("Invalid hex string: contains non-hex characters");
102
- }
103
- if (typeof Buffer !== "undefined" && Buffer.from) {
104
- return new Uint8Array(Buffer.from(cleanHex, "hex"));
105
- }
106
- const bytes = new Uint8Array(cleanHex.length / 2);
107
- for (let i = 0; i < cleanHex.length; i += 2) {
108
- bytes[i / 2] = parseInt(cleanHex.substr(i, 2), 16);
109
- }
110
- return bytes;
111
- }
112
- function stringToBytes(str) {
113
- if (typeof Buffer !== "undefined" && Buffer.from) {
114
- return new Uint8Array(Buffer.from(str, "utf8"));
115
- }
116
- if (typeof TextEncoder !== "undefined") {
117
- return new TextEncoder().encode(str);
118
- }
119
- const bytes = [];
120
- for (let i = 0; i < str.length; i++) {
121
- const char = str.charCodeAt(i);
122
- if (char < 128) {
123
- bytes.push(char);
124
- } else if (char < 2048) {
125
- bytes.push(192 | char >> 6, 128 | char & 63);
126
- } else if (char < 55296 || char >= 57344) {
127
- bytes.push(
128
- 224 | char >> 12,
129
- 128 | char >> 6 & 63,
130
- 128 | char & 63
131
- );
132
- } else {
133
- i++;
134
- const char2 = str.charCodeAt(i);
135
- const codePoint = 65536 + ((char & 1023) << 10 | char2 & 1023);
136
- bytes.push(
137
- 240 | codePoint >> 18,
138
- 128 | codePoint >> 12 & 63,
139
- 128 | codePoint >> 6 & 63,
140
- 128 | codePoint & 63
141
- );
142
- }
143
- }
144
- return new Uint8Array(bytes);
145
- }
146
- function bytesToString(bytes) {
147
- if (typeof Buffer !== "undefined" && Buffer.from) {
148
- return Buffer.from(bytes).toString("utf8");
149
- }
150
- if (typeof TextDecoder !== "undefined") {
151
- return new TextDecoder().decode(bytes);
152
- }
153
- let str = "";
154
- let i = 0;
155
- while (i < bytes.length) {
156
- const byte = bytes[i];
157
- if (byte < 128) {
158
- str += String.fromCharCode(byte);
159
- i++;
160
- } else if ((byte & 224) === 192) {
161
- str += String.fromCharCode((byte & 31) << 6 | bytes[i + 1] & 63);
162
- i += 2;
163
- } else if ((byte & 240) === 224) {
164
- str += String.fromCharCode(
165
- (byte & 15) << 12 | (bytes[i + 1] & 63) << 6 | bytes[i + 2] & 63
166
- );
167
- i += 3;
168
- } else {
169
- const codePoint = ((byte & 7) << 18 | (bytes[i + 1] & 63) << 12 | (bytes[i + 2] & 63) << 6 | bytes[i + 3] & 63) - 65536;
170
- str += String.fromCharCode(
171
- 55296 + (codePoint >> 10),
172
- 56320 + (codePoint & 1023)
173
- );
174
- i += 4;
175
- }
176
- }
177
- return str;
178
- }
179
- var init_encoding = __esm({
180
- "src/utils/encoding.ts"() {
181
- "use strict";
182
- }
183
- });
184
-
185
- // src/utils/crypto-utils.ts
186
- function concatBytes(...arrays) {
187
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
188
- const result = new Uint8Array(totalLength);
189
- let offset = 0;
190
- for (const arr of arrays) {
191
- result.set(arr, offset);
192
- offset += arr.length;
193
- }
194
- return result;
195
- }
196
- function hexToBytes(hex) {
197
- return fromHex(hex);
198
- }
199
- function bytesToHex(bytes) {
200
- return toHex(bytes);
201
- }
202
- function processWalletPublicKey(publicKey) {
203
- const publicKeyHex = typeof publicKey === "string" ? publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey : bytesToHex(publicKey);
204
- const publicKeyBytes = hexToBytes(publicKeyHex);
205
- return publicKeyBytes.length === 64 ? concatBytes(new Uint8Array([4]), publicKeyBytes) : publicKeyBytes;
206
- }
207
- function processWalletPrivateKey(privateKey) {
208
- const privateKeyHex = typeof privateKey === "string" ? privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey : bytesToHex(privateKey);
209
- return hexToBytes(privateKeyHex);
210
- }
211
- function parseEncryptedDataBuffer(encryptedBuffer) {
212
- return {
213
- iv: encryptedBuffer.slice(0, 16),
214
- ephemPublicKey: encryptedBuffer.slice(16, 81),
215
- // 65 bytes for uncompressed public key
216
- ciphertext: encryptedBuffer.slice(81, -32),
217
- mac: encryptedBuffer.slice(-32)
218
- };
219
- }
220
- var init_crypto_utils = __esm({
221
- "src/utils/crypto-utils.ts"() {
222
- "use strict";
223
- init_encoding();
224
- }
225
- });
226
-
227
- // src/crypto/services/WalletKeyEncryptionService.ts
228
- var WalletKeyEncryptionService;
229
- var init_WalletKeyEncryptionService = __esm({
230
- "src/crypto/services/WalletKeyEncryptionService.ts"() {
231
- "use strict";
232
- init_crypto_utils();
233
- init_encoding();
234
- WalletKeyEncryptionService = class {
235
- constructor(config) {
236
- __publicField(this, "eciesProvider");
237
- this.eciesProvider = config.eciesProvider;
238
- }
239
- /**
240
- * Encrypts data using a wallet's public key.
241
- *
242
- * @param data - The plaintext message to encrypt for the wallet owner.
243
- * @param publicKey - The recipient wallet's public key for encryption.
244
- * @returns A promise that resolves to the encrypted data as a hex string.
245
- * @throws {Error} When encryption fails due to invalid key format.
246
- *
247
- * @example
248
- * ```typescript
249
- * const encrypted = await processor.encryptWithWalletPublicKey(
250
- * "Secret message",
251
- * "0x04..." // 65-byte uncompressed public key
252
- * );
253
- * console.log(`Encrypted: ${encrypted}`);
254
- * ```
255
- */
256
- async encryptWithWalletPublicKey(data, publicKey) {
257
- const publicKeyBytes = processWalletPublicKey(publicKey);
258
- const dataBytes = stringToBytes(data);
259
- const encrypted = await this.eciesProvider.encrypt(
260
- publicKeyBytes,
261
- dataBytes
262
- );
263
- const result = concatBytes(
264
- encrypted.iv,
265
- encrypted.ephemPublicKey,
266
- encrypted.ciphertext,
267
- encrypted.mac
268
- );
269
- return bytesToHex(result);
270
- }
271
- /**
272
- * Decrypts data using a wallet's private key.
273
- *
274
- * @param encryptedData - The hex-encoded encrypted data to decrypt.
275
- * @param privateKey - The wallet's private key for decryption.
276
- * @returns A promise that resolves to the decrypted plaintext message.
277
- * @throws {Error} When decryption fails due to invalid data or key format.
278
- *
279
- * @example
280
- * ```typescript
281
- * const decrypted = await processor.decryptWithWalletPrivateKey(
282
- * encryptedHexString,
283
- * "0x..." // 32-byte private key
284
- * );
285
- * console.log(`Decrypted: ${decrypted}`);
286
- * ```
287
- */
288
- async decryptWithWalletPrivateKey(encryptedData, privateKey) {
289
- const privateKeyBytes = processWalletPrivateKey(privateKey);
290
- const encryptedBytes = hexToBytes(encryptedData);
291
- const encrypted = parseEncryptedDataBuffer(encryptedBytes);
292
- const decrypted = await this.eciesProvider.decrypt(
293
- privateKeyBytes,
294
- encrypted
295
- );
296
- return bytesToString(decrypted);
297
- }
298
- /**
299
- * Encrypts a Uint8Array with a wallet public key
300
- *
301
- * @param data - Binary data to encrypt
302
- * @param publicKey - Public key as hex string or Uint8Array
303
- * @returns Encrypted data structure
304
- */
305
- async encryptBinary(data, publicKey) {
306
- const publicKeyBytes = processWalletPublicKey(publicKey);
307
- return this.eciesProvider.encrypt(publicKeyBytes, data);
308
- }
309
- /**
310
- * Decrypts to a Uint8Array with a wallet private key
311
- *
312
- * @param encrypted - Encrypted data structure
313
- * @param privateKey - Private key as hex string or Uint8Array
314
- * @returns Decrypted binary data
315
- */
316
- async decryptBinary(encrypted, privateKey) {
317
- const privateKeyBytes = processWalletPrivateKey(privateKey);
318
- return this.eciesProvider.decrypt(privateKeyBytes, encrypted);
319
- }
320
- /**
321
- * Gets the underlying ECIES provider
322
- *
323
- * @returns The ECIES provider instance
324
- */
325
- getECIESProvider() {
326
- return this.eciesProvider;
327
- }
328
- };
329
- }
330
- });
331
-
332
- // src/crypto/ecies/utils.ts
333
- function hexToBytes2(hex) {
334
- if (hex.length % 2 !== 0) {
335
- throw new Error("Hex string must have even length");
336
- }
337
- const bytes = new Uint8Array(hex.length / 2);
338
- for (let i = 0; i < hex.length; i += 2) {
339
- bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
340
- }
341
- return bytes;
342
- }
343
- function bytesToHex2(bytes) {
344
- return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
345
- }
346
- function stringToBytes2(str) {
347
- return new TextEncoder().encode(str);
348
- }
349
- function bytesToString2(bytes) {
350
- return new TextDecoder().decode(bytes);
351
- }
352
- function concatBytes2(...arrays) {
353
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
354
- const result = new Uint8Array(totalLength);
355
- let offset = 0;
356
- for (const arr of arrays) {
357
- result.set(arr, offset);
358
- offset += arr.length;
359
- }
360
- return result;
361
- }
362
- function constantTimeEqual(a, b) {
363
- if (a.length !== b.length) return false;
364
- let result = 0;
365
- for (let i = 0; i < a.length; i++) {
366
- result |= a[i] ^ b[i];
367
- }
368
- return result === 0;
369
- }
370
- var init_utils = __esm({
371
- "src/crypto/ecies/utils.ts"() {
372
- "use strict";
373
- }
374
- });
375
-
376
- // src/crypto/ecies/constants.ts
377
- var CURVE, CIPHER, KDF, MAC, FORMAT;
378
- var init_constants = __esm({
379
- "src/crypto/ecies/constants.ts"() {
380
- "use strict";
381
- CURVE = {
382
- /** The elliptic curve used (secp256k1 - same as Bitcoin/Ethereum) */
383
- name: "secp256k1",
384
- /** Private key length in bytes */
385
- PRIVATE_KEY_LENGTH: 32,
386
- /** Compressed public key length in bytes (0x02 or 0x03 prefix + 32 bytes) */
387
- COMPRESSED_PUBLIC_KEY_LENGTH: 33,
388
- /** Uncompressed public key length in bytes (0x04 prefix + 64 bytes) */
389
- UNCOMPRESSED_PUBLIC_KEY_LENGTH: 65,
390
- /** ECDH shared secret X coordinate length */
391
- SHARED_SECRET_LENGTH: 32,
392
- /** Public key prefixes */
393
- PREFIX: {
394
- /** Uncompressed public key prefix */
395
- UNCOMPRESSED: 4,
396
- /** Compressed public key prefix for even Y */
397
- COMPRESSED_EVEN: 2,
398
- /** Compressed public key prefix for odd Y */
399
- COMPRESSED_ODD: 3
400
- },
401
- /** X coordinate starts at byte 1 (after prefix) */
402
- X_COORDINATE_OFFSET: 1,
403
- /** X coordinate ends at byte 33 (1 + 32) */
404
- X_COORDINATE_END: 33
405
- };
406
- CIPHER = {
407
- /** Cipher algorithm - must match eccrypto */
408
- algorithm: "aes-256-cbc",
409
- /** AES key length in bytes */
410
- KEY_LENGTH: 32,
411
- /** Initialization vector length in bytes */
412
- IV_LENGTH: 16,
413
- /** Block size for AES */
414
- BLOCK_SIZE: 16
415
- };
416
- KDF = {
417
- /** Hash algorithm for key derivation - must match eccrypto */
418
- algorithm: "sha512",
419
- /** Output length of SHA-512 in bytes */
420
- OUTPUT_LENGTH: 64,
421
- /** Encryption key slice (first 32 bytes of KDF output) */
422
- ENCRYPTION_KEY_OFFSET: 0,
423
- ENCRYPTION_KEY_LENGTH: 32,
424
- /** MAC key slice (last 32 bytes of KDF output) */
425
- MAC_KEY_OFFSET: 32,
426
- MAC_KEY_LENGTH: 32
427
- };
428
- MAC = {
429
- /** MAC algorithm - must match eccrypto */
430
- algorithm: "sha256",
431
- /** HMAC-SHA256 output length in bytes */
432
- LENGTH: 32
433
- };
434
- FORMAT = {
435
- /** Offsets for each component in serialized format */
436
- IV_OFFSET: 0,
437
- IV_LENGTH: CIPHER.IV_LENGTH,
438
- /** Ephemeral public key (always uncompressed in eccrypto format) */
439
- EPHEMERAL_KEY_OFFSET: CIPHER.IV_LENGTH,
440
- EPHEMERAL_KEY_LENGTH: CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
441
- /** Ciphertext starts after IV and ephemeral key */
442
- CIPHERTEXT_OFFSET: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
443
- /** MAC is always the last 32 bytes */
444
- MAC_LENGTH: MAC.LENGTH,
445
- /** Minimum size of encrypted data (IV + ephemKey + MAC, no ciphertext) */
446
- MIN_ENCRYPTED_LENGTH: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + MAC.LENGTH,
447
- /**
448
- * Helper to calculate total length of encrypted data
449
- *
450
- * @param ciphertextLength - Length of the ciphertext portion
451
- * @returns Total length including all components
452
- */
453
- getTotalLength: (ciphertextLength) => CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + ciphertextLength + MAC.LENGTH
454
- };
455
- }
456
- });
457
-
458
- // src/crypto/ecies/interface.ts
459
- function isECIESEncrypted(obj) {
460
- if (!obj || typeof obj !== "object") return false;
461
- const enc = obj;
462
- const isUint8Array = (value) => {
463
- return value instanceof Uint8Array || typeof Buffer !== "undefined" && Buffer.isBuffer(value);
464
- };
465
- return isUint8Array(enc.iv) && enc.iv.length === CIPHER.IV_LENGTH && isUint8Array(enc.ephemPublicKey) && (enc.ephemPublicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH || enc.ephemPublicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) && isUint8Array(enc.ciphertext) && enc.ciphertext.length > 0 && isUint8Array(enc.mac) && enc.mac.length === MAC.LENGTH;
466
- }
467
- var ECIESError;
468
- var init_interface = __esm({
469
- "src/crypto/ecies/interface.ts"() {
470
- "use strict";
471
- init_constants();
472
- ECIESError = class extends Error {
473
- constructor(message, code, cause) {
474
- super(message);
475
- this.code = code;
476
- this.cause = cause;
477
- this.name = "ECIESError";
478
- }
479
- };
480
- }
481
- });
482
-
483
- // src/crypto/ecies/base.ts
484
- var _BaseECIESUint8, BaseECIESUint8;
485
- var init_base = __esm({
486
- "src/crypto/ecies/base.ts"() {
487
- "use strict";
488
- init_interface();
489
- init_constants();
490
- init_utils();
491
- _BaseECIESUint8 = class _BaseECIESUint8 {
492
- /**
493
- * Normalizes a public key to uncompressed format.
494
- *
495
- * @param publicKey - Public key in any format.
496
- * @returns Uncompressed public key (65 bytes).
497
- * @throws {ECIESError} If key format is invalid.
498
- */
499
- normalizePublicKey(publicKey) {
500
- if (_BaseECIESUint8.validatedKeys.has(publicKey)) {
501
- return publicKey;
502
- }
503
- if (publicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH) {
504
- if (publicKey[0] !== CURVE.PREFIX.UNCOMPRESSED) {
505
- throw new ECIESError(
506
- "Invalid uncompressed public key prefix",
507
- "INVALID_KEY"
508
- );
509
- }
510
- if (!this.validatePublicKey(publicKey)) {
511
- throw new ECIESError("Invalid public key", "INVALID_KEY");
512
- }
513
- _BaseECIESUint8.validatedKeys.set(publicKey, true);
514
- return publicKey;
515
- }
516
- if (publicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) {
517
- const decompressed = this.decompressPublicKey(publicKey);
518
- if (!decompressed) {
519
- throw new ECIESError("Failed to decompress public key", "INVALID_KEY");
520
- }
521
- _BaseECIESUint8.validatedKeys.set(decompressed, true);
522
- return decompressed;
523
- }
524
- throw new ECIESError(
525
- `Invalid public key length: ${publicKey.length}`,
526
- "INVALID_KEY"
527
- );
528
- }
529
- /**
530
- * Encrypts data using ECIES.
531
- *
532
- * @param publicKey - The recipient's public key (compressed or uncompressed)
533
- * @param message - The data to encrypt
534
- * @returns Promise resolving to encrypted data structure
535
- */
536
- async encrypt(publicKey, message) {
537
- try {
538
- if (!(publicKey instanceof Uint8Array)) {
539
- throw new ECIESError("Public key must be a Uint8Array", "INVALID_KEY");
540
- }
541
- if (!(message instanceof Uint8Array)) {
542
- throw new ECIESError(
543
- "Message must be a Uint8Array",
544
- "ENCRYPTION_FAILED"
545
- );
546
- }
547
- if (publicKey.length === 0) {
548
- throw new ECIESError("Public key cannot be empty", "INVALID_KEY");
549
- }
550
- const pubKey = this.normalizePublicKey(publicKey);
551
- let ephemeralPrivateKey;
552
- do {
553
- ephemeralPrivateKey = this.generateRandomBytes(
554
- CURVE.PRIVATE_KEY_LENGTH
555
- );
556
- } while (!this.verifyPrivateKey(ephemeralPrivateKey));
557
- const ephemeralPublicKey = this.createPublicKey(
558
- ephemeralPrivateKey,
559
- false
560
- );
561
- if (!ephemeralPublicKey) {
562
- throw new ECIESError(
563
- "Failed to generate ephemeral public key",
564
- "ENCRYPTION_FAILED"
565
- );
566
- }
567
- const sharedSecret = this.performECDH(pubKey, ephemeralPrivateKey);
568
- const kdf = this.sha512(sharedSecret);
569
- const encryptionKey = kdf.slice(
570
- KDF.ENCRYPTION_KEY_OFFSET,
571
- KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
572
- );
573
- const macKey = kdf.slice(
574
- KDF.MAC_KEY_OFFSET,
575
- KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
576
- );
577
- const iv = this.generateRandomBytes(CIPHER.IV_LENGTH);
578
- const ciphertext = await this.aesEncrypt(encryptionKey, iv, message);
579
- const macData = concatBytes2(iv, ephemeralPublicKey, ciphertext);
580
- const mac = this.hmacSha256(macKey, macData);
581
- this.clearBuffer(ephemeralPrivateKey);
582
- this.clearBuffer(sharedSecret);
583
- this.clearBuffer(kdf);
584
- return {
585
- iv,
586
- ephemPublicKey: ephemeralPublicKey,
587
- ciphertext,
588
- mac
589
- };
590
- } catch (error) {
591
- if (error instanceof ECIESError) throw error;
592
- throw new ECIESError(
593
- `Encryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
594
- "ENCRYPTION_FAILED",
595
- error instanceof Error ? error : void 0
596
- );
597
- }
598
- }
599
- /**
600
- * Decrypts ECIES encrypted data.
601
- *
602
- * @param privateKey - The recipient's private key (32 bytes)
603
- * @param encrypted - The encrypted data structure from encrypt()
604
- * @returns Promise resolving to the original plaintext
605
- */
606
- async decrypt(privateKey, encrypted) {
607
- try {
608
- if (!(privateKey instanceof Uint8Array)) {
609
- throw new ECIESError("Private key must be a Uint8Array", "INVALID_KEY");
610
- }
611
- if (!isECIESEncrypted(encrypted)) {
612
- throw new ECIESError(
613
- "Invalid encrypted data structure",
614
- "DECRYPTION_FAILED"
615
- );
616
- }
617
- if (privateKey.length !== CURVE.PRIVATE_KEY_LENGTH) {
618
- throw new ECIESError(
619
- `Invalid private key length: ${privateKey.length}`,
620
- "INVALID_KEY"
621
- );
622
- }
623
- if (!this.verifyPrivateKey(privateKey)) {
624
- throw new ECIESError("Invalid private key", "INVALID_KEY");
625
- }
626
- const ephemeralPublicKey = this.normalizePublicKey(
627
- encrypted.ephemPublicKey
628
- );
629
- const sharedSecret = this.performECDH(ephemeralPublicKey, privateKey);
630
- const kdf = this.sha512(sharedSecret);
631
- const encryptionKey = kdf.slice(
632
- KDF.ENCRYPTION_KEY_OFFSET,
633
- KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
634
- );
635
- const macKey = kdf.slice(
636
- KDF.MAC_KEY_OFFSET,
637
- KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
638
- );
639
- const macData = concatBytes2(
640
- encrypted.iv,
641
- encrypted.ephemPublicKey,
642
- encrypted.ciphertext
643
- );
644
- const expectedMac = this.hmacSha256(macKey, macData);
645
- if (!constantTimeEqual(encrypted.mac, expectedMac)) {
646
- throw new ECIESError("MAC verification failed", "MAC_MISMATCH");
647
- }
648
- const decrypted = await this.aesDecrypt(
649
- encryptionKey,
650
- encrypted.iv,
651
- encrypted.ciphertext
652
- );
653
- this.clearBuffer(sharedSecret);
654
- this.clearBuffer(kdf);
655
- return decrypted;
656
- } catch (error) {
657
- if (error instanceof ECIESError) throw error;
658
- throw new ECIESError(
659
- `Decryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
660
- "DECRYPTION_FAILED",
661
- error instanceof Error ? error : void 0
662
- );
663
- }
664
- }
665
- /**
666
- * Clears sensitive data from memory using multi-pass overwrite.
667
- *
668
- * @remarks
669
- * Uses multiple passes with different patterns to make it harder
670
- * for JIT compilers to optimize away the operation. While not
671
- * guaranteed in JavaScript, this is a best-effort approach to
672
- * clear sensitive data from memory.
673
- *
674
- * @param buffer - The buffer to clear
675
- */
676
- clearBuffer(buffer) {
677
- if (buffer && buffer.length > 0) {
678
- buffer.fill(0);
679
- buffer.fill(255);
680
- buffer.fill(170);
681
- buffer.fill(0);
682
- for (let i = 0; i < buffer.length; i++) {
683
- buffer[i] = i & 255 ^ 90;
684
- }
685
- buffer.fill(0);
686
- }
687
- }
688
- };
689
- // Cache for validated public keys to avoid repeated validation
690
- __publicField(_BaseECIESUint8, "validatedKeys", /* @__PURE__ */ new WeakMap());
691
- BaseECIESUint8 = _BaseECIESUint8;
692
- }
693
- });
694
-
695
- // src/crypto/ecies/browser.ts
696
- import * as secp256k1 from "@noble/secp256k1";
697
- import { hmac } from "@noble/hashes/hmac";
698
- import { sha256, sha512 as nobleSha512 } from "@noble/hashes/sha2";
699
- var BrowserECIESUint8Provider;
700
- var init_browser = __esm({
701
- "src/crypto/ecies/browser.ts"() {
702
- "use strict";
703
- init_base();
704
- BrowserECIESUint8Provider = class extends BaseECIESUint8 {
705
- generateRandomBytes(length) {
706
- const bytes = new Uint8Array(length);
707
- crypto.getRandomValues(bytes);
708
- return bytes;
709
- }
710
- verifyPrivateKey(privateKey) {
711
- try {
712
- return secp256k1.utils.isValidPrivateKey(privateKey);
713
- } catch {
714
- return false;
715
- }
716
- }
717
- createPublicKey(privateKey, compressed) {
718
- try {
719
- return secp256k1.getPublicKey(privateKey, compressed);
720
- } catch {
721
- return null;
722
- }
723
- }
724
- validatePublicKey(publicKey) {
725
- try {
726
- secp256k1.Point.fromHex(publicKey);
727
- return true;
728
- } catch {
729
- return false;
730
- }
731
- }
732
- decompressPublicKey(publicKey) {
733
- try {
734
- const point = secp256k1.Point.fromHex(publicKey);
735
- return point.toRawBytes(false);
736
- } catch {
737
- return null;
738
- }
739
- }
740
- performECDH(publicKey, privateKey) {
741
- try {
742
- const sharedPoint = secp256k1.getSharedSecret(
743
- privateKey,
744
- publicKey,
745
- true
746
- );
747
- return sharedPoint.slice(1);
748
- } catch (error) {
749
- throw new Error(
750
- `ECDH failed: ${error instanceof Error ? error.message : "Unknown error"}`
751
- );
752
- }
753
- }
754
- sha512(data) {
755
- return nobleSha512(data);
756
- }
757
- hmacSha256(key, data) {
758
- return hmac(sha256, key, data);
759
- }
760
- async aesEncrypt(key, iv, plaintext) {
761
- const cryptoKey = await crypto.subtle.importKey(
762
- "raw",
763
- key,
764
- { name: "AES-CBC" },
765
- false,
766
- ["encrypt"]
767
- );
768
- const encrypted = await crypto.subtle.encrypt(
769
- { name: "AES-CBC", iv },
770
- cryptoKey,
771
- plaintext
772
- );
773
- return new Uint8Array(encrypted);
774
- }
775
- async aesDecrypt(key, iv, ciphertext) {
776
- const cryptoKey = await crypto.subtle.importKey(
777
- "raw",
778
- key,
779
- { name: "AES-CBC" },
780
- false,
781
- ["decrypt"]
782
- );
783
- const decrypted = await crypto.subtle.decrypt(
784
- { name: "AES-CBC", iv },
785
- cryptoKey,
786
- ciphertext
787
- );
788
- return new Uint8Array(decrypted);
789
- }
790
- };
791
- }
792
- });
793
-
794
121
  // src/platform/browser.ts
795
- import * as secp256k12 from "@noble/secp256k1";
796
- var getOpenPGP, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter;
797
- var init_browser2 = __esm({
122
+ var getOpenPGP, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter, browserPlatformAdapter;
123
+ var init_browser = __esm({
798
124
  "src/platform/browser.ts"() {
799
125
  "use strict";
126
+ init_crypto_utils();
800
127
  init_pgp_utils();
801
128
  init_error_utils();
802
129
  init_lazy_import();
803
- init_WalletKeyEncryptionService();
804
- init_crypto_utils();
805
- init_utils();
806
- init_browser();
807
130
  getOpenPGP = lazyImport(() => import("openpgp"));
808
131
  BrowserCryptoAdapter = class {
809
- constructor() {
810
- __publicField(this, "eciesProvider", new BrowserECIESUint8Provider());
811
- __publicField(this, "walletKeyEncryptionService", new WalletKeyEncryptionService({
812
- eciesProvider: this.eciesProvider
813
- }));
814
- }
815
132
  async encryptWithPublicKey(data, publicKeyHex) {
816
133
  try {
817
- const publicKeyBytes = hexToBytes2(publicKeyHex);
818
- const encrypted = await this.eciesProvider.encrypt(
819
- publicKeyBytes,
820
- stringToBytes2(data)
134
+ const eccrypto = await import("eccrypto-js");
135
+ const publicKeyBuffer = Buffer.from(publicKeyHex, "hex");
136
+ const encrypted = await eccrypto.encrypt(
137
+ publicKeyBuffer,
138
+ Buffer.from(data, "utf8")
821
139
  );
822
- const result = concatBytes2(
140
+ const result = Buffer.concat([
823
141
  encrypted.iv,
824
142
  encrypted.ephemPublicKey,
825
143
  encrypted.ciphertext,
826
144
  encrypted.mac
827
- );
828
- return bytesToHex2(result);
145
+ ]);
146
+ return result.toString("hex");
829
147
  } catch (error) {
830
- throw wrapCryptoError("encryptWithPublicKey", error);
148
+ throw new Error(`Encryption failed: ${error}`);
831
149
  }
832
150
  }
833
151
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
834
152
  try {
835
- const encryptedBytes = hexToBytes2(encryptedData);
836
- const privateKeyBytes = hexToBytes2(privateKeyHex);
837
- const encrypted = parseEncryptedDataBuffer(encryptedBytes);
838
- const decrypted = await this.eciesProvider.decrypt(
839
- privateKeyBytes,
840
- encrypted
153
+ const eccrypto = await import("eccrypto-js");
154
+ const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
155
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
156
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
157
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
158
+ const decryptedBuffer = await eccrypto.decrypt(
159
+ privateKeyBuffer,
160
+ encryptedObj
841
161
  );
842
- return bytesToString2(decrypted);
162
+ return decryptedBuffer.toString("utf8");
843
163
  } catch (error) {
844
- throw wrapCryptoError("decryptWithPrivateKey", error);
164
+ throw new Error(`Decryption failed: ${error}`);
845
165
  }
846
166
  }
847
- async encryptWithWalletPublicKey(data, publicKey) {
167
+ async generateKeyPair() {
848
168
  try {
849
- return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
850
- data,
851
- publicKey
852
- );
169
+ const eccrypto = await import("eccrypto-js");
170
+ const privateKeyBytes = new Uint8Array(32);
171
+ crypto.getRandomValues(privateKeyBytes);
172
+ const privateKey = Buffer.from(privateKeyBytes);
173
+ const publicKey = eccrypto.getPublicCompressed(privateKey);
174
+ return {
175
+ privateKey: privateKey.toString("hex"),
176
+ publicKey: publicKey.toString("hex")
177
+ };
853
178
  } catch (error) {
854
- throw wrapCryptoError("encryptWithWalletPublicKey", error);
179
+ throw wrapCryptoError("key generation", error);
855
180
  }
856
181
  }
857
- async decryptWithWalletPrivateKey(encryptedData, privateKey) {
182
+ async encryptWithWalletPublicKey(data, publicKey) {
858
183
  try {
859
- return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
860
- encryptedData,
861
- privateKey
184
+ const eccrypto = await import("eccrypto-js");
185
+ const uncompressedKey = processWalletPublicKey(publicKey);
186
+ const encryptedBuffer = await eccrypto.encrypt(
187
+ uncompressedKey,
188
+ Buffer.from(data)
862
189
  );
190
+ const result = Buffer.concat([
191
+ encryptedBuffer.iv,
192
+ encryptedBuffer.ephemPublicKey,
193
+ encryptedBuffer.ciphertext,
194
+ encryptedBuffer.mac
195
+ ]);
196
+ return result.toString("hex");
863
197
  } catch (error) {
864
- throw wrapCryptoError("decryptWithWalletPrivateKey", error);
198
+ throw wrapCryptoError("encrypt with wallet public key", error);
865
199
  }
866
200
  }
867
- async generateKeyPair() {
201
+ async decryptWithWalletPrivateKey(encryptedData, privateKey) {
868
202
  try {
869
- const privateKeyBytes = secp256k12.utils.randomPrivateKey();
870
- const publicKeyBytes = secp256k12.getPublicKey(privateKeyBytes, true);
871
- return {
872
- privateKey: bytesToHex2(privateKeyBytes),
873
- publicKey: bytesToHex2(publicKeyBytes)
874
- };
203
+ const eccrypto = await import("eccrypto-js");
204
+ const privateKeyBuffer = processWalletPrivateKey(privateKey);
205
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
206
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
207
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
208
+ const decryptedBuffer = await eccrypto.decrypt(
209
+ privateKeyBuffer,
210
+ encryptedObj
211
+ );
212
+ return decryptedBuffer.toString("utf8");
875
213
  } catch (error) {
876
- throw wrapCryptoError("generateKeyPair", error);
214
+ throw wrapCryptoError("decrypt with wallet private key", error);
877
215
  }
878
216
  }
879
217
  async encryptWithPassword(data, password) {
880
218
  try {
881
219
  const openpgp = await getOpenPGP();
882
- const message = await openpgp.createMessage({ binary: data });
220
+ const message = await openpgp.createMessage({
221
+ binary: data
222
+ });
883
223
  const encrypted = await openpgp.encrypt({
884
224
  message,
885
225
  passwords: [password],
886
226
  format: "binary"
887
227
  });
888
- return new Uint8Array(encrypted);
228
+ const response = new Response(encrypted);
229
+ const arrayBuffer = await response.arrayBuffer();
230
+ return new Uint8Array(arrayBuffer);
889
231
  } catch (error) {
890
- throw wrapCryptoError("encryptWithPassword", error);
232
+ throw new Error(`Failed to encrypt with password: ${error}`);
891
233
  }
892
234
  }
893
235
  async decryptWithPassword(encryptedData, password) {
@@ -896,14 +238,14 @@ var init_browser2 = __esm({
896
238
  const message = await openpgp.readMessage({
897
239
  binaryMessage: encryptedData
898
240
  });
899
- const { data } = await openpgp.decrypt({
241
+ const { data: decrypted } = await openpgp.decrypt({
900
242
  message,
901
243
  passwords: [password],
902
244
  format: "binary"
903
245
  });
904
- return new Uint8Array(data);
246
+ return new Uint8Array(decrypted);
905
247
  } catch (error) {
906
- throw wrapCryptoError("decryptWithPassword", error);
248
+ throw new Error(`Failed to decrypt with password: ${error}`);
907
249
  }
908
250
  }
909
251
  };
@@ -955,6 +297,9 @@ var init_browser2 = __esm({
955
297
  };
956
298
  BrowserHttpAdapter = class {
957
299
  async fetch(url, options) {
300
+ if (typeof fetch === "undefined") {
301
+ throw new Error("Fetch API not available in this browser environment");
302
+ }
958
303
  return fetch(url, options);
959
304
  }
960
305
  };
@@ -974,19 +319,17 @@ var init_browser2 = __esm({
974
319
  }
975
320
  set(key, value) {
976
321
  try {
977
- if (typeof sessionStorage === "undefined") {
978
- return;
322
+ if (typeof sessionStorage !== "undefined") {
323
+ sessionStorage.setItem(this.prefix + key, value);
979
324
  }
980
- sessionStorage.setItem(this.prefix + key, value);
981
325
  } catch {
982
326
  }
983
327
  }
984
328
  delete(key) {
985
329
  try {
986
- if (typeof sessionStorage === "undefined") {
987
- return;
330
+ if (typeof sessionStorage !== "undefined") {
331
+ sessionStorage.removeItem(this.prefix + key);
988
332
  }
989
- sessionStorage.removeItem(this.prefix + key);
990
333
  } catch {
991
334
  }
992
335
  }
@@ -995,27 +338,30 @@ var init_browser2 = __esm({
995
338
  if (typeof sessionStorage === "undefined") {
996
339
  return;
997
340
  }
998
- const keysToRemove = [];
999
- for (let i = 0; i < sessionStorage.length; i++) {
1000
- const key = sessionStorage.key(i);
1001
- if (key?.startsWith(this.prefix)) {
1002
- keysToRemove.push(key);
341
+ const keys = Object.keys(sessionStorage);
342
+ for (const key of keys) {
343
+ if (key.startsWith(this.prefix)) {
344
+ sessionStorage.removeItem(key);
1003
345
  }
1004
346
  }
1005
- keysToRemove.forEach((key) => sessionStorage.removeItem(key));
1006
347
  } catch {
1007
348
  }
1008
349
  }
1009
350
  };
1010
351
  BrowserPlatformAdapter = class {
1011
352
  constructor() {
1012
- __publicField(this, "crypto", new BrowserCryptoAdapter());
1013
- __publicField(this, "pgp", new BrowserPGPAdapter());
1014
- __publicField(this, "http", new BrowserHttpAdapter());
1015
- __publicField(this, "cache", new BrowserCacheAdapter());
353
+ __publicField(this, "crypto");
354
+ __publicField(this, "pgp");
355
+ __publicField(this, "http");
356
+ __publicField(this, "cache");
1016
357
  __publicField(this, "platform", "browser");
358
+ this.crypto = new BrowserCryptoAdapter();
359
+ this.pgp = new BrowserPGPAdapter();
360
+ this.http = new BrowserHttpAdapter();
361
+ this.cache = new BrowserCacheAdapter();
1017
362
  }
1018
363
  };
364
+ browserPlatformAdapter = new BrowserPlatformAdapter();
1019
365
  }
1020
366
  });
1021
367
 
@@ -1082,8 +428,10 @@ var init_dataSchema_schema = __esm({
1082
428
  // src/utils/schemaValidation.ts
1083
429
  import Ajv from "ajv";
1084
430
  import addFormats from "ajv-formats";
1085
- function validateDataSchema(schema) {
1086
- return schemaValidator.validateDataSchema(schema);
431
+ function validateDataSchemaAgainstMetaSchema(schema) {
432
+ const validator = schemaValidator;
433
+ validator.validateDataSchemaAgainstMetaSchema(schema);
434
+ return schema;
1087
435
  }
1088
436
  function validateDataAgainstSchema(data, schema) {
1089
437
  return schemaValidator.validateDataAgainstSchema(data, schema);
@@ -1116,9 +464,9 @@ var init_schemaValidation = __esm({
1116
464
  this.dataSchemaValidator = this.ajv.compile(dataSchema_schema_default);
1117
465
  }
1118
466
  /**
1119
- * Validates a data schema against the Vana meta-schema
467
+ * Validates a data schema definition against the Vana meta-schema
1120
468
  *
1121
- * @param schema - The data schema to validate
469
+ * @param schema - The data schema definition to validate
1122
470
  * @throws SchemaValidationError if invalid
1123
471
  * @example
1124
472
  * ```typescript
@@ -1137,10 +485,10 @@ var init_schemaValidation = __esm({
1137
485
  * }
1138
486
  * };
1139
487
  *
1140
- * validator.validateDataSchema(schema); // throws if invalid
488
+ * validator.validateDataSchemaAgainstMetaSchema(schema); // throws if invalid
1141
489
  * ```
1142
490
  */
1143
- validateDataSchema(schema) {
491
+ validateDataSchemaAgainstMetaSchema(schema) {
1144
492
  const isValid = this.dataSchemaValidator(schema);
1145
493
  if (!isValid) {
1146
494
  const errors = this.dataSchemaValidator.errors || [];
@@ -1160,10 +508,10 @@ var init_schemaValidation = __esm({
1160
508
  }
1161
509
  }
1162
510
  /**
1163
- * Validates data against a JSON Schema from a schema
511
+ * Validates data against a JSON Schema
1164
512
  *
1165
513
  * @param data - The data to validate
1166
- * @param schema - The schema containing the validation rules (DataSchema or Schema)
514
+ * @param schema - The schema containing the validation rules (must have been validated or fetched from chain)
1167
515
  * @throws SchemaValidationError if invalid
1168
516
  * @example
1169
517
  * ```typescript
@@ -1173,25 +521,22 @@ var init_schemaValidation = __esm({
1173
521
  * const schema = await vana.schemas.get(1);
1174
522
  * validator.validateDataAgainstSchema(userData, schema);
1175
523
  *
1176
- * // Also works with DataSchema object
1177
- * const dataSchema: DataSchema = {
524
+ * // Also works with pre-validated DataSchema object
525
+ * const dataSchema = validator.validateDataSchemaAgainstMetaSchema({
1178
526
  * name: "User Profile",
1179
527
  * version: "1.0.0",
1180
528
  * dialect: "json",
1181
529
  * schema: { type: "object", properties: { name: { type: "string" } } }
1182
- * };
530
+ * });
1183
531
  * validator.validateDataAgainstSchema(userData, dataSchema);
1184
532
  * ```
1185
533
  */
1186
534
  validateDataAgainstSchema(data, schema) {
1187
- if (!("id" in schema)) {
1188
- this.validateDataSchema(schema);
1189
- }
1190
535
  if (schema.dialect !== "json") {
1191
- throw new SchemaValidationError(
1192
- `Data validation only supported for JSON dialect, got: ${schema.dialect}`,
1193
- []
536
+ console.warn(
537
+ `[SchemaValidator] Data validation skipped: dialect '${schema.dialect}' does not support data validation. Only JSON schemas can validate data structure.`
1194
538
  );
539
+ return;
1195
540
  }
1196
541
  if (typeof schema.schema !== "object") {
1197
542
  throw new SchemaValidationError(
@@ -1257,9 +602,9 @@ var init_schemaValidation = __esm({
1257
602
  }
1258
603
  }
1259
604
  /**
1260
- * Fetches and validates a schema from a URL
605
+ * Fetches and validates a data schema from a URL
1261
606
  *
1262
- * @param url - The URL to fetch the schema from
607
+ * @param url - The URL to fetch the data schema from
1263
608
  * @returns The validated data schema
1264
609
  * @throws SchemaValidationError if invalid or fetch fails
1265
610
  * @example
@@ -1275,7 +620,7 @@ var init_schemaValidation = __esm({
1275
620
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1276
621
  }
1277
622
  const schema = await response.json();
1278
- this.validateDataSchema(schema);
623
+ this.validateDataSchemaAgainstMetaSchema(schema);
1279
624
  if (schema.dialect === "sqlite" && typeof schema.schema === "string") {
1280
625
  this.validateSQLiteDDL(schema.schema, schema.dialectVersion);
1281
626
  }
@@ -1924,19 +1269,19 @@ var init_eventMappings = __esm({
1924
1269
  // DataRegistry operations
1925
1270
  addFile: {
1926
1271
  contract: "DataRegistry",
1927
- event: "FileAdded"
1272
+ event: "FileAddedV2"
1928
1273
  },
1929
1274
  addFileWithPermissionsAndSchema: {
1930
1275
  contract: "DataRegistry",
1931
- event: "FileAdded"
1276
+ event: "FileAddedV2"
1932
1277
  },
1933
1278
  addFileWithSchema: {
1934
1279
  contract: "DataRegistry",
1935
- event: "FileAdded"
1280
+ event: "FileAddedV2"
1936
1281
  },
1937
1282
  addFileWithPermissions: {
1938
1283
  contract: "DataRegistry",
1939
- event: "FileAdded"
1284
+ event: "FileAddedV2"
1940
1285
  },
1941
1286
  addRefinement: {
1942
1287
  contract: "DataRegistry",
@@ -3423,6 +2768,37 @@ var init_DataRegistryImplementation = __esm({
3423
2768
  name: "FileAdded",
3424
2769
  type: "event"
3425
2770
  },
2771
+ {
2772
+ anonymous: false,
2773
+ inputs: [
2774
+ {
2775
+ indexed: true,
2776
+ internalType: "uint256",
2777
+ name: "fileId",
2778
+ type: "uint256"
2779
+ },
2780
+ {
2781
+ indexed: true,
2782
+ internalType: "address",
2783
+ name: "ownerAddress",
2784
+ type: "address"
2785
+ },
2786
+ {
2787
+ indexed: false,
2788
+ internalType: "string",
2789
+ name: "url",
2790
+ type: "string"
2791
+ },
2792
+ {
2793
+ indexed: false,
2794
+ internalType: "uint256",
2795
+ name: "schemaId",
2796
+ type: "uint256"
2797
+ }
2798
+ ],
2799
+ name: "FileAddedV2",
2800
+ type: "event"
2801
+ },
3426
2802
  {
3427
2803
  anonymous: false,
3428
2804
  inputs: [
@@ -3970,6 +3346,19 @@ var init_DataRegistryImplementation = __esm({
3970
3346
  stateMutability: "view",
3971
3347
  type: "function"
3972
3348
  },
3349
+ {
3350
+ inputs: [],
3351
+ name: "emitLegacyEvents",
3352
+ outputs: [
3353
+ {
3354
+ internalType: "bool",
3355
+ name: "",
3356
+ type: "bool"
3357
+ }
3358
+ ],
3359
+ stateMutability: "view",
3360
+ type: "function"
3361
+ },
3973
3362
  {
3974
3363
  inputs: [
3975
3364
  {
@@ -4127,6 +3516,11 @@ var init_DataRegistryImplementation = __esm({
4127
3516
  name: "url",
4128
3517
  type: "string"
4129
3518
  },
3519
+ {
3520
+ internalType: "uint256",
3521
+ name: "schemaId",
3522
+ type: "uint256"
3523
+ },
4130
3524
  {
4131
3525
  internalType: "uint256",
4132
3526
  name: "addedAtBlock",
@@ -4410,6 +3804,19 @@ var init_DataRegistryImplementation = __esm({
4410
3804
  stateMutability: "nonpayable",
4411
3805
  type: "function"
4412
3806
  },
3807
+ {
3808
+ inputs: [
3809
+ {
3810
+ internalType: "bool",
3811
+ name: "newEmitLegacyEvents",
3812
+ type: "bool"
3813
+ }
3814
+ ],
3815
+ name: "updateEmitLegacyEvents",
3816
+ outputs: [],
3817
+ stateMutability: "nonpayable",
3818
+ type: "function"
3819
+ },
4413
3820
  {
4414
3821
  inputs: [
4415
3822
  {
@@ -37215,7 +36622,7 @@ var init_schemas = __esm({
37215
36622
  dialect,
37216
36623
  schema: schemaDefinition
37217
36624
  };
37218
- validateDataSchema(dataSchema);
36625
+ validateDataSchemaAgainstMetaSchema(dataSchema);
37219
36626
  if (!this.context.storageManager) {
37220
36627
  if (this.context.validateStorageRequired) {
37221
36628
  this.context.validateStorageRequired();
@@ -37324,7 +36731,7 @@ var init_schemas = __esm({
37324
36731
  `Invalid schema definition format for schema ${schemaId}`
37325
36732
  );
37326
36733
  }
37327
- validateDataSchema(definition);
36734
+ validateDataSchemaAgainstMetaSchema(definition);
37328
36735
  const dataSchema = definition;
37329
36736
  if (dataSchema.name !== metadata.name) {
37330
36737
  throw new Error(
@@ -37659,7 +37066,7 @@ var init_schemas = __esm({
37659
37066
  try {
37660
37067
  const definition = await fetchFromUrl(schema.definitionUrl);
37661
37068
  if (definition && typeof definition === "object") {
37662
- validateDataSchema(definition);
37069
+ validateDataSchemaAgainstMetaSchema(definition);
37663
37070
  const dataSchema = definition;
37664
37071
  schema.version = dataSchema.version;
37665
37072
  schema.description = dataSchema.description;
@@ -37679,7 +37086,7 @@ var init_schemas = __esm({
37679
37086
  });
37680
37087
 
37681
37088
  // src/index.browser.ts
37682
- init_browser2();
37089
+ init_browser();
37683
37090
 
37684
37091
  // src/types/config.ts
37685
37092
  function isWalletConfig(config) {
@@ -37710,6 +37117,9 @@ var StorageError = class extends Error {
37710
37117
  }
37711
37118
  };
37712
37119
 
37120
+ // src/types/index.ts
37121
+ init_schemaValidation();
37122
+
37713
37123
  // src/types/external-apis.ts
37714
37124
  function isReplicateAPIResponse(value) {
37715
37125
  if (typeof value !== "object" || value === null) return false;
@@ -37751,7 +37161,7 @@ init_abi();
37751
37161
 
37752
37162
  // src/utils/grantFiles.ts
37753
37163
  init_errors();
37754
- import { keccak256, toHex as toHex2 } from "viem";
37164
+ import { keccak256, toHex } from "viem";
37755
37165
  function createGrantFile(params) {
37756
37166
  const grantFile = {
37757
37167
  grantee: params.grantee,
@@ -37874,8 +37284,8 @@ function getGrantFileHash(grantFile) {
37874
37284
  sortedFile.expires = grantFile.expires;
37875
37285
  }
37876
37286
  const jsonString = JSON.stringify(sortedFile);
37877
- console.info(`Hash: ${keccak256(toHex2(jsonString))}`);
37878
- return keccak256(toHex2(jsonString));
37287
+ console.info(`Hash: ${keccak256(toHex(jsonString))}`);
37288
+ return keccak256(toHex(jsonString));
37879
37289
  } catch (error) {
37880
37290
  throw new SerializationError(
37881
37291
  `Failed to generate grant file hash: ${error instanceof Error ? error.message : "Unknown error"}`
@@ -38152,8 +37562,7 @@ function validateOperationAccess(grantFile, requestedOperation) {
38152
37562
  }
38153
37563
 
38154
37564
  // src/utils/signatureCache.ts
38155
- import { sha256 as sha2562 } from "@noble/hashes/sha256";
38156
- import { bytesToHex as bytesToHex3 } from "@noble/hashes/utils";
37565
+ init_crypto_utils();
38157
37566
  var SignatureCache = class {
38158
37567
  /**
38159
37568
  * Get a cached signature if it exists and hasn't expired
@@ -38250,12 +37659,12 @@ var SignatureCache = class {
38250
37659
  * Generate a deterministic hash of a message object for cache key generation
38251
37660
  *
38252
37661
  * @remarks
38253
- * Creates a cryptographically secure hash from complex objects including EIP-712 typed data.
38254
- * Uses SHA-256 for collision resistance and deterministic key generation.
38255
- * Handles BigInt serialization and sorts object keys for consistency.
37662
+ * Creates a consistent hash from complex objects including EIP-712 typed data.
37663
+ * Handles BigInt serialization and produces a 32-character hash that balances
37664
+ * uniqueness with key length constraints.
38256
37665
  *
38257
37666
  * @param message - The message object to hash (typically EIP-712 typed data)
38258
- * @returns A hex string hash (SHA-256) suitable for cache keys
37667
+ * @returns A 32-character hash string suitable for cache keys
38259
37668
  * @example
38260
37669
  * ```typescript
38261
37670
  * const typedData = {
@@ -38264,35 +37673,30 @@ var SignatureCache = class {
38264
37673
  * };
38265
37674
  *
38266
37675
  * const hash = SignatureCache.hashMessage(typedData);
38267
- * // Returns SHA-256 hash like: "a1b2c3d4e5f6..."
37676
+ * // Returns something like: "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"
38268
37677
  * ```
38269
37678
  */
38270
37679
  static hashMessage(message) {
38271
- const jsonString = JSON.stringify(message, this.deterministicReplacer);
38272
- const hashBytes = sha2562(new TextEncoder().encode(jsonString));
38273
- return bytesToHex3(hashBytes);
37680
+ const jsonString = JSON.stringify(message, this.bigIntReplacer);
37681
+ const base64Hash = toBase64(jsonString);
37682
+ const cleaned = base64Hash.replace(/[^a-zA-Z0-9]/g, "");
37683
+ if (cleaned.length > 32) {
37684
+ return cleaned.substring(0, 16) + cleaned.substring(cleaned.length - 16);
37685
+ }
37686
+ return cleaned.substring(0, 32);
38274
37687
  }
38275
37688
  /**
38276
- * Deterministic JSON replacer that handles BigInt values and sorts object keys
38277
- * This ensures consistent cache key generation for EIP-712 typed data
37689
+ * Custom JSON replacer that converts BigInt values to strings for serialization
37690
+ * This ensures deterministic cache key generation for EIP-712 typed data
38278
37691
  *
38279
37692
  * @param _key - The object key being serialized (unused)
38280
37693
  * @param value - The value to serialize
38281
- * @returns The serialized value with sorted keys for objects
37694
+ * @returns The serialized value
38282
37695
  */
38283
- static deterministicReplacer(_key, value) {
37696
+ static bigIntReplacer(_key, value) {
38284
37697
  if (typeof value === "bigint") {
38285
37698
  return `__BIGINT__${value.toString()}`;
38286
37699
  }
38287
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
38288
- return Object.keys(value).sort().reduce(
38289
- (sorted, key) => {
38290
- sorted[key] = value[key];
38291
- return sorted;
38292
- },
38293
- {}
38294
- );
38295
- }
38296
37700
  return value;
38297
37701
  }
38298
37702
  };
@@ -42535,6 +41939,29 @@ var DataController = class {
42535
41939
  const userFiles = Array.from(fileMap.values()).sort(
42536
41940
  (a, b) => Number((b.addedAtTimestamp || 0n) - (a.addedAtTimestamp || 0n))
42537
41941
  );
41942
+ if (userFiles.length > 0) {
41943
+ try {
41944
+ const fileIds = userFiles.map((f) => f.id);
41945
+ let proofMap;
41946
+ try {
41947
+ proofMap = await this._fetchProofsFromSubgraph(fileIds, endpoint);
41948
+ } catch (subgraphError) {
41949
+ console.debug(
41950
+ "Failed to fetch proofs from subgraph, trying chain:",
41951
+ subgraphError
41952
+ );
41953
+ proofMap = await this._fetchProofsFromChain(fileIds);
41954
+ }
41955
+ for (const file of userFiles) {
41956
+ const dlpIds = proofMap.get(file.id);
41957
+ if (dlpIds && dlpIds.length > 0) {
41958
+ file.dlpIds = dlpIds;
41959
+ }
41960
+ }
41961
+ } catch (error) {
41962
+ console.warn("Failed to fetch proof data for files:", error);
41963
+ }
41964
+ }
42538
41965
  return userFiles;
42539
41966
  } catch (error) {
42540
41967
  console.error("Failed to fetch user files from subgraph:", error);
@@ -42543,6 +41970,349 @@ var DataController = class {
42543
41970
  );
42544
41971
  }
42545
41972
  }
41973
+ /**
41974
+ * Fetches proof data for multiple files from the subgraph.
41975
+ *
41976
+ * @private
41977
+ * @param fileIds - Array of file IDs to fetch proofs for
41978
+ * @param subgraphUrl - The subgraph endpoint URL
41979
+ * @returns Map of file IDs to their associated DLP IDs
41980
+ */
41981
+ async _fetchProofsFromSubgraph(fileIds, subgraphUrl) {
41982
+ const query = `
41983
+ query GetFileProofs($fileIds: [BigInt!]!) {
41984
+ dataRegistryProofs(where: { fileId_in: $fileIds }) {
41985
+ fileId
41986
+ dlp {
41987
+ id
41988
+ }
41989
+ }
41990
+ }
41991
+ `;
41992
+ const response = await fetch(subgraphUrl, {
41993
+ method: "POST",
41994
+ headers: {
41995
+ "Content-Type": "application/json"
41996
+ },
41997
+ body: JSON.stringify({
41998
+ query,
41999
+ variables: {
42000
+ fileIds: fileIds.map((id) => id.toString())
42001
+ }
42002
+ })
42003
+ });
42004
+ if (!response.ok) {
42005
+ throw new Error(
42006
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42007
+ );
42008
+ }
42009
+ const result = await response.json();
42010
+ if (result.errors) {
42011
+ throw new Error(
42012
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42013
+ );
42014
+ }
42015
+ const proofMap = /* @__PURE__ */ new Map();
42016
+ if (result.data?.dataRegistryProofs) {
42017
+ for (const proof of result.data.dataRegistryProofs) {
42018
+ if (proof.dlp?.id) {
42019
+ const fileId = parseInt(proof.fileId);
42020
+ const dlpId = parseInt(proof.dlp.id);
42021
+ if (!proofMap.has(fileId)) {
42022
+ proofMap.set(fileId, []);
42023
+ }
42024
+ const dlpIds = proofMap.get(fileId);
42025
+ if (!dlpIds.includes(dlpId)) {
42026
+ dlpIds.push(dlpId);
42027
+ }
42028
+ }
42029
+ }
42030
+ }
42031
+ return proofMap;
42032
+ }
42033
+ /**
42034
+ * Fetches proof data for multiple files from the blockchain.
42035
+ * Falls back to this when subgraph is unavailable.
42036
+ *
42037
+ * @private
42038
+ * @param fileIds - Array of file IDs to fetch proofs for
42039
+ * @returns Map of file IDs to their associated DLP IDs
42040
+ */
42041
+ async _fetchProofsFromChain(fileIds) {
42042
+ const chainId = this.context.walletClient.chain?.id;
42043
+ if (!chainId) {
42044
+ throw new Error("Chain ID not available");
42045
+ }
42046
+ const dataRegistryAddress = getContractAddress(chainId, "DataRegistry");
42047
+ const dataRegistryAbi = getAbi("DataRegistry");
42048
+ const proofMap = /* @__PURE__ */ new Map();
42049
+ for (const fileId of fileIds) {
42050
+ const dlpIds = [];
42051
+ let proofIndex = 0;
42052
+ let hasMoreProofs = true;
42053
+ while (hasMoreProofs) {
42054
+ try {
42055
+ const proof = await this.context.publicClient.readContract({
42056
+ address: dataRegistryAddress,
42057
+ abi: dataRegistryAbi,
42058
+ functionName: "fileProofs",
42059
+ args: [BigInt(fileId), BigInt(proofIndex)]
42060
+ });
42061
+ if (proof?.data?.dlpId) {
42062
+ const dlpId = Number(proof.data.dlpId);
42063
+ if (!dlpIds.includes(dlpId)) {
42064
+ dlpIds.push(dlpId);
42065
+ }
42066
+ }
42067
+ proofIndex++;
42068
+ } catch {
42069
+ hasMoreProofs = false;
42070
+ }
42071
+ }
42072
+ if (dlpIds.length > 0) {
42073
+ proofMap.set(fileId, dlpIds);
42074
+ }
42075
+ }
42076
+ return proofMap;
42077
+ }
42078
+ /**
42079
+ * Retrieves information about a specific Data Liquidity Pool (DLP).
42080
+ *
42081
+ * @remarks
42082
+ * DLPs are entities that process and verify data files in the Vana network.
42083
+ * This method fetches DLP metadata including name, status, and performance rating.
42084
+ * Uses subgraph first for efficiency, falls back to chain if unavailable.
42085
+ *
42086
+ * @param dlpId - The unique identifier of the DLP
42087
+ * @param options - Optional parameters
42088
+ * @param options.subgraphUrl - Custom subgraph URL to override default
42089
+ * @returns Promise resolving to DLP information
42090
+ * @throws {Error} When DLP cannot be found - "DLP not found: {dlpId}"
42091
+ * @throws {Error} When query fails - "Failed to fetch DLP: {error}"
42092
+ * @example
42093
+ * ```typescript
42094
+ * const dlp = await vana.data.getDLP(26);
42095
+ * console.log(`DLP ${dlp.name}: ${dlp.status}`);
42096
+ * ```
42097
+ */
42098
+ async getDLP(dlpId, options = {}) {
42099
+ const subgraphUrl = options.subgraphUrl || this.context.subgraphUrl;
42100
+ if (subgraphUrl) {
42101
+ try {
42102
+ const query = `
42103
+ query GetDLP($id: ID!) {
42104
+ dlp(id: $id) {
42105
+ id
42106
+ name
42107
+ metadata
42108
+ status
42109
+ address
42110
+ owner
42111
+ }
42112
+ }
42113
+ `;
42114
+ const response = await fetch(subgraphUrl, {
42115
+ method: "POST",
42116
+ headers: {
42117
+ "Content-Type": "application/json"
42118
+ },
42119
+ body: JSON.stringify({
42120
+ query,
42121
+ variables: {
42122
+ id: dlpId.toString()
42123
+ }
42124
+ })
42125
+ });
42126
+ if (!response.ok) {
42127
+ throw new Error(
42128
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42129
+ );
42130
+ }
42131
+ const result = await response.json();
42132
+ if (result.errors) {
42133
+ throw new Error(
42134
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42135
+ );
42136
+ }
42137
+ if (!result.data?.dlp) {
42138
+ throw new Error(`DLP not found: ${dlpId}`);
42139
+ }
42140
+ return {
42141
+ id: parseInt(result.data.dlp.id),
42142
+ name: result.data.dlp.name || "",
42143
+ metadata: result.data.dlp.metadata,
42144
+ status: result.data.dlp.status ? parseInt(result.data.dlp.status) : void 0,
42145
+ address: result.data.dlp.address,
42146
+ owner: result.data.dlp.owner
42147
+ };
42148
+ } catch (error) {
42149
+ console.debug("Subgraph query failed, falling back to chain:", error);
42150
+ }
42151
+ }
42152
+ try {
42153
+ const chainId = this.context.walletClient.chain?.id;
42154
+ if (!chainId) {
42155
+ throw new Error("Chain ID not available");
42156
+ }
42157
+ const dlpRegistryAddress = getContractAddress(chainId, "DLPRegistry");
42158
+ const dlpRegistryAbi = getAbi("DLPRegistry");
42159
+ const dlpData = await this.context.publicClient.readContract({
42160
+ address: dlpRegistryAddress,
42161
+ abi: dlpRegistryAbi,
42162
+ functionName: "dlps",
42163
+ args: [BigInt(dlpId)]
42164
+ });
42165
+ if (!dlpData || !dlpData.name) {
42166
+ throw new Error(`DLP not found: ${dlpId}`);
42167
+ }
42168
+ return {
42169
+ id: dlpId,
42170
+ name: dlpData.name,
42171
+ metadata: dlpData.metadata,
42172
+ status: dlpData.status,
42173
+ address: dlpData.dlpAddress,
42174
+ owner: dlpData.ownerAddress
42175
+ };
42176
+ } catch (error) {
42177
+ throw new Error(
42178
+ `Failed to fetch DLP: ${error instanceof Error ? error.message : "Unknown error"}`
42179
+ );
42180
+ }
42181
+ }
42182
+ /**
42183
+ * Lists all Data Liquidity Pools (DLPs) with optional pagination.
42184
+ *
42185
+ * @remarks
42186
+ * Fetches a paginated list of all DLPs registered in the network.
42187
+ * Uses subgraph for efficient querying with fallback to chain multicall.
42188
+ *
42189
+ * @param options - Optional parameters for pagination and filtering
42190
+ * @param options.limit - Maximum number of DLPs to return (default: 100)
42191
+ * @param options.offset - Number of DLPs to skip (default: 0)
42192
+ * @param options.subgraphUrl - Custom subgraph URL to override default
42193
+ * @returns Promise resolving to array of DLP information
42194
+ * @throws {Error} When query fails - "Failed to list DLPs: {error}"
42195
+ * @example
42196
+ * ```typescript
42197
+ * // Get first 10 DLPs
42198
+ * const dlps = await vana.data.listDLPs({ limit: 10 });
42199
+ * dlps.forEach(dlp => console.log(`${dlp.id}: ${dlp.name}`));
42200
+ *
42201
+ * // Get next page
42202
+ * const nextPage = await vana.data.listDLPs({ limit: 10, offset: 10 });
42203
+ * ```
42204
+ */
42205
+ async listDLPs(options = {}) {
42206
+ const { limit = 100, offset = 0 } = options;
42207
+ const subgraphUrl = options.subgraphUrl || this.context.subgraphUrl;
42208
+ if (subgraphUrl) {
42209
+ try {
42210
+ const query = `
42211
+ query ListDLPs($first: Int!, $skip: Int!) {
42212
+ dlps(first: $first, skip: $skip, orderBy: id) {
42213
+ id
42214
+ name
42215
+ metadata
42216
+ status
42217
+ address
42218
+ owner
42219
+ }
42220
+ }
42221
+ `;
42222
+ const response = await fetch(subgraphUrl, {
42223
+ method: "POST",
42224
+ headers: {
42225
+ "Content-Type": "application/json"
42226
+ },
42227
+ body: JSON.stringify({
42228
+ query,
42229
+ variables: {
42230
+ first: limit,
42231
+ skip: offset
42232
+ }
42233
+ })
42234
+ });
42235
+ if (!response.ok) {
42236
+ throw new Error(
42237
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42238
+ );
42239
+ }
42240
+ const result = await response.json();
42241
+ if (result.errors) {
42242
+ throw new Error(
42243
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42244
+ );
42245
+ }
42246
+ const dlps = result.data?.dlps || [];
42247
+ return dlps.map((dlp) => ({
42248
+ id: parseInt(dlp.id),
42249
+ name: dlp.name || "",
42250
+ metadata: dlp.metadata,
42251
+ status: dlp.status ? parseInt(dlp.status) : void 0,
42252
+ address: dlp.address,
42253
+ owner: dlp.owner
42254
+ }));
42255
+ } catch (error) {
42256
+ console.debug("Subgraph query failed, falling back to chain:", error);
42257
+ }
42258
+ }
42259
+ try {
42260
+ const chainId = this.context.walletClient.chain?.id;
42261
+ if (!chainId) {
42262
+ throw new Error("Chain ID not available");
42263
+ }
42264
+ const dlpRegistryAddress = getContractAddress(chainId, "DLPRegistry");
42265
+ const dlpRegistryAbi = getAbi("DLPRegistry");
42266
+ const dlpCount = await this.context.publicClient.readContract({
42267
+ address: dlpRegistryAddress,
42268
+ abi: dlpRegistryAbi,
42269
+ functionName: "dlpsCount",
42270
+ args: []
42271
+ });
42272
+ const totalCount = Number(dlpCount);
42273
+ const start = offset;
42274
+ const end = Math.min(start + limit, totalCount);
42275
+ if (end <= start) {
42276
+ return [];
42277
+ }
42278
+ const calls = [];
42279
+ for (let i = start + 1; i <= end; i++) {
42280
+ calls.push({
42281
+ address: dlpRegistryAddress,
42282
+ abi: dlpRegistryAbi,
42283
+ functionName: "dlps",
42284
+ args: [BigInt(i)]
42285
+ });
42286
+ }
42287
+ const results = await gasAwareMulticall(this.context.publicClient, {
42288
+ contracts: calls,
42289
+ allowFailure: true,
42290
+ batchSize: 50
42291
+ });
42292
+ const dlps = [];
42293
+ for (let i = 0; i < results.length; i++) {
42294
+ const result = results[i];
42295
+ if (result.status === "success" && result.result) {
42296
+ const dlpData = result.result;
42297
+ if (dlpData.name) {
42298
+ dlps.push({
42299
+ id: start + i + 1,
42300
+ name: dlpData.name,
42301
+ metadata: dlpData.metadata,
42302
+ status: dlpData.status,
42303
+ address: dlpData.dlpAddress,
42304
+ owner: dlpData.ownerAddress
42305
+ });
42306
+ }
42307
+ }
42308
+ }
42309
+ return dlps;
42310
+ } catch (error) {
42311
+ throw new Error(
42312
+ `Failed to list DLPs: ${error instanceof Error ? error.message : "Unknown error"}`
42313
+ );
42314
+ }
42315
+ }
42546
42316
  /**
42547
42317
  * Retrieves a list of permissions granted by a user.
42548
42318
  *
@@ -43969,10 +43739,10 @@ var DataController = class {
43969
43739
  );
43970
43740
  }
43971
43741
  /**
43972
- * Validates a data schema against the Vana meta-schema.
43742
+ * Validates a data schema definition against the Vana meta-schema.
43973
43743
  *
43974
- * @param schema - The data schema to validate
43975
- * @returns Assertion that schema is valid (throws if invalid)
43744
+ * @param schema - The data schema definition to validate
43745
+ * @returns The validated DataSchema
43976
43746
  * @throws SchemaValidationError if invalid
43977
43747
  * @example
43978
43748
  * ```typescript
@@ -43989,11 +43759,11 @@ var DataController = class {
43989
43759
  * }
43990
43760
  * };
43991
43761
  *
43992
- * vana.data.validateDataSchema(schema);
43762
+ * const validatedSchema = vana.data.validateDataSchemaAgainstMetaSchema(schema);
43993
43763
  * ```
43994
43764
  */
43995
- validateDataSchema(schema) {
43996
- return validateDataSchema(schema);
43765
+ validateDataSchemaAgainstMetaSchema(schema) {
43766
+ return validateDataSchemaAgainstMetaSchema(schema);
43997
43767
  }
43998
43768
  /**
43999
43769
  * Validates data against a JSON Schema from a data schema.
@@ -44026,9 +43796,9 @@ var DataController = class {
44026
43796
  return validateDataAgainstSchema(data, schema);
44027
43797
  }
44028
43798
  /**
44029
- * Fetches and validates a schema from a URL, then returns the parsed data schema.
43799
+ * Fetches and validates a data schema from a URL, then returns the parsed data schema.
44030
43800
  *
44031
- * @param url - The URL to fetch the schema from
43801
+ * @param url - The URL to fetch the data schema from
44032
43802
  * @returns The validated data schema
44033
43803
  * @throws SchemaValidationError if invalid or fetch fails
44034
43804
  * @example
@@ -45226,7 +44996,7 @@ var GoogleDriveStorage = class {
45226
44996
  };
45227
44997
 
45228
44998
  // src/storage/providers/ipfs.ts
45229
- init_encoding();
44999
+ init_crypto_utils();
45230
45000
  var IpfsStorage = class _IpfsStorage {
45231
45001
  constructor(config) {
45232
45002
  this.config = config;
@@ -45266,9 +45036,8 @@ var IpfsStorage = class _IpfsStorage {
45266
45036
  * ```
45267
45037
  */
45268
45038
  static forInfura(credentials) {
45269
- const encoder = new TextEncoder();
45270
45039
  const auth = toBase64(
45271
- encoder.encode(`${credentials.projectId}:${credentials.projectSecret}`)
45040
+ `${credentials.projectId}:${credentials.projectSecret}`
45272
45041
  );
45273
45042
  return new _IpfsStorage({
45274
45043
  apiEndpoint: "https://ipfs.infura.io:5001/api/v0/add",
@@ -46130,7 +45899,7 @@ var vanaMainnet2 = {
46130
45899
  url: "https://vanascan.io"
46131
45900
  }
46132
45901
  },
46133
- subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/vana/7.0.7/gn"
45902
+ subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/vana/prod/gn"
46134
45903
  };
46135
45904
  var moksha = {
46136
45905
  id: 14800,
@@ -46151,7 +45920,7 @@ var moksha = {
46151
45920
  url: "https://moksha.vanascan.io"
46152
45921
  }
46153
45922
  },
46154
- subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/moksha/7.0.7/gn"
45923
+ subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/moksha/prod/gn"
46155
45924
  };
46156
45925
  function getChainConfig(chainId) {
46157
45926
  switch (chainId) {
@@ -47111,11 +46880,10 @@ var CircuitBreaker = class {
47111
46880
  };
47112
46881
 
47113
46882
  // src/index.browser.ts
47114
- init_browser2();
47115
46883
  init_browser();
47116
46884
 
47117
46885
  // src/platform/browser-only.ts
47118
- init_browser2();
46886
+ init_browser();
47119
46887
  function createBrowserPlatformAdapter() {
47120
46888
  return new BrowserPlatformAdapter();
47121
46889
  }
@@ -47463,7 +47231,6 @@ export {
47463
47231
  AsyncQueue,
47464
47232
  BaseController,
47465
47233
  BlockchainError,
47466
- BrowserECIESUint8Provider as BrowserECIESProvider,
47467
47234
  BrowserPlatformAdapter,
47468
47235
  CallbackStorage,
47469
47236
  CircuitBreaker,
@@ -47565,7 +47332,7 @@ export {
47565
47332
  storeGrantFile,
47566
47333
  summarizeGrant,
47567
47334
  validateDataAgainstSchema,
47568
- validateDataSchema,
47335
+ validateDataSchemaAgainstMetaSchema,
47569
47336
  validateGrant,
47570
47337
  validateGrantExpiry,
47571
47338
  validateGrantFile,