@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
@@ -30,6 +30,53 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  ));
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
+ // src/platform/shared/crypto-utils.ts
34
+ function processWalletPublicKey(publicKey) {
35
+ const publicKeyHex = publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey;
36
+ const publicKeyBytes = Buffer.from(publicKeyHex, "hex");
37
+ return publicKeyBytes.length === 64 ? Buffer.concat([Buffer.from([4]), publicKeyBytes]) : publicKeyBytes;
38
+ }
39
+ function processWalletPrivateKey(privateKey) {
40
+ const privateKeyHex = privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey;
41
+ return Buffer.from(privateKeyHex, "hex");
42
+ }
43
+ function parseEncryptedDataBuffer(encryptedBuffer) {
44
+ return {
45
+ iv: encryptedBuffer.slice(0, 16),
46
+ ephemPublicKey: encryptedBuffer.slice(16, 81),
47
+ // 65 bytes for uncompressed public key
48
+ ciphertext: encryptedBuffer.slice(81, -32),
49
+ mac: encryptedBuffer.slice(-32)
50
+ };
51
+ }
52
+ function toBase64(str) {
53
+ if (typeof Buffer !== "undefined") {
54
+ return Buffer.from(str, "utf8").toString("base64");
55
+ } else if (typeof btoa !== "undefined") {
56
+ return btoa(str);
57
+ } else {
58
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
59
+ let result = "";
60
+ let i = 0;
61
+ while (i < str.length) {
62
+ const a = str.charCodeAt(i++);
63
+ const b = i < str.length ? str.charCodeAt(i++) : 0;
64
+ const c = i < str.length ? str.charCodeAt(i++) : 0;
65
+ const bitmap = a << 16 | b << 8 | c;
66
+ result += chars.charAt(bitmap >> 18 & 63);
67
+ result += chars.charAt(bitmap >> 12 & 63);
68
+ result += i - 2 < str.length ? chars.charAt(bitmap >> 6 & 63) : "=";
69
+ result += i - 1 < str.length ? chars.charAt(bitmap & 63) : "=";
70
+ }
71
+ return result;
72
+ }
73
+ }
74
+ var init_crypto_utils = __esm({
75
+ "src/platform/shared/crypto-utils.ts"() {
76
+ "use strict";
77
+ }
78
+ });
79
+
33
80
  // src/platform/shared/pgp-utils.ts
34
81
  function processPGPKeyOptions(options) {
35
82
  return {
@@ -91,626 +138,6 @@ var init_lazy_import = __esm({
91
138
  }
92
139
  });
93
140
 
94
- // src/utils/encoding.ts
95
- function toBase64(data) {
96
- if (typeof Buffer !== "undefined" && Buffer.from) {
97
- return Buffer.from(data).toString("base64");
98
- }
99
- if (typeof btoa !== "undefined") {
100
- const binary = Array.from(data, (byte) => String.fromCharCode(byte)).join(
101
- ""
102
- );
103
- return btoa(binary);
104
- }
105
- throw new Error("No base64 encoding method available in this environment");
106
- }
107
- function toHex(data) {
108
- if (typeof Buffer !== "undefined" && Buffer.from) {
109
- return Buffer.from(data).toString("hex");
110
- }
111
- return Array.from(data, (byte) => byte.toString(16).padStart(2, "0")).join(
112
- ""
113
- );
114
- }
115
- function fromHex(hex) {
116
- const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
117
- if (cleanHex.length % 2 !== 0) {
118
- throw new Error("Invalid hex string: odd length");
119
- }
120
- if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {
121
- throw new Error("Invalid hex string: contains non-hex characters");
122
- }
123
- if (typeof Buffer !== "undefined" && Buffer.from) {
124
- return new Uint8Array(Buffer.from(cleanHex, "hex"));
125
- }
126
- const bytes = new Uint8Array(cleanHex.length / 2);
127
- for (let i = 0; i < cleanHex.length; i += 2) {
128
- bytes[i / 2] = parseInt(cleanHex.substr(i, 2), 16);
129
- }
130
- return bytes;
131
- }
132
- function stringToBytes(str) {
133
- if (typeof Buffer !== "undefined" && Buffer.from) {
134
- return new Uint8Array(Buffer.from(str, "utf8"));
135
- }
136
- if (typeof TextEncoder !== "undefined") {
137
- return new TextEncoder().encode(str);
138
- }
139
- const bytes = [];
140
- for (let i = 0; i < str.length; i++) {
141
- const char = str.charCodeAt(i);
142
- if (char < 128) {
143
- bytes.push(char);
144
- } else if (char < 2048) {
145
- bytes.push(192 | char >> 6, 128 | char & 63);
146
- } else if (char < 55296 || char >= 57344) {
147
- bytes.push(
148
- 224 | char >> 12,
149
- 128 | char >> 6 & 63,
150
- 128 | char & 63
151
- );
152
- } else {
153
- i++;
154
- const char2 = str.charCodeAt(i);
155
- const codePoint = 65536 + ((char & 1023) << 10 | char2 & 1023);
156
- bytes.push(
157
- 240 | codePoint >> 18,
158
- 128 | codePoint >> 12 & 63,
159
- 128 | codePoint >> 6 & 63,
160
- 128 | codePoint & 63
161
- );
162
- }
163
- }
164
- return new Uint8Array(bytes);
165
- }
166
- function bytesToString(bytes) {
167
- if (typeof Buffer !== "undefined" && Buffer.from) {
168
- return Buffer.from(bytes).toString("utf8");
169
- }
170
- if (typeof TextDecoder !== "undefined") {
171
- return new TextDecoder().decode(bytes);
172
- }
173
- let str = "";
174
- let i = 0;
175
- while (i < bytes.length) {
176
- const byte = bytes[i];
177
- if (byte < 128) {
178
- str += String.fromCharCode(byte);
179
- i++;
180
- } else if ((byte & 224) === 192) {
181
- str += String.fromCharCode((byte & 31) << 6 | bytes[i + 1] & 63);
182
- i += 2;
183
- } else if ((byte & 240) === 224) {
184
- str += String.fromCharCode(
185
- (byte & 15) << 12 | (bytes[i + 1] & 63) << 6 | bytes[i + 2] & 63
186
- );
187
- i += 3;
188
- } else {
189
- const codePoint = ((byte & 7) << 18 | (bytes[i + 1] & 63) << 12 | (bytes[i + 2] & 63) << 6 | bytes[i + 3] & 63) - 65536;
190
- str += String.fromCharCode(
191
- 55296 + (codePoint >> 10),
192
- 56320 + (codePoint & 1023)
193
- );
194
- i += 4;
195
- }
196
- }
197
- return str;
198
- }
199
- var init_encoding = __esm({
200
- "src/utils/encoding.ts"() {
201
- "use strict";
202
- }
203
- });
204
-
205
- // src/utils/crypto-utils.ts
206
- function concatBytes(...arrays) {
207
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
208
- const result = new Uint8Array(totalLength);
209
- let offset = 0;
210
- for (const arr of arrays) {
211
- result.set(arr, offset);
212
- offset += arr.length;
213
- }
214
- return result;
215
- }
216
- function hexToBytes(hex) {
217
- return fromHex(hex);
218
- }
219
- function bytesToHex(bytes) {
220
- return toHex(bytes);
221
- }
222
- function processWalletPublicKey(publicKey) {
223
- const publicKeyHex = typeof publicKey === "string" ? publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey : bytesToHex(publicKey);
224
- const publicKeyBytes = hexToBytes(publicKeyHex);
225
- return publicKeyBytes.length === 64 ? concatBytes(new Uint8Array([4]), publicKeyBytes) : publicKeyBytes;
226
- }
227
- function processWalletPrivateKey(privateKey) {
228
- const privateKeyHex = typeof privateKey === "string" ? privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey : bytesToHex(privateKey);
229
- return hexToBytes(privateKeyHex);
230
- }
231
- function parseEncryptedDataBuffer(encryptedBuffer) {
232
- return {
233
- iv: encryptedBuffer.slice(0, 16),
234
- ephemPublicKey: encryptedBuffer.slice(16, 81),
235
- // 65 bytes for uncompressed public key
236
- ciphertext: encryptedBuffer.slice(81, -32),
237
- mac: encryptedBuffer.slice(-32)
238
- };
239
- }
240
- var init_crypto_utils = __esm({
241
- "src/utils/crypto-utils.ts"() {
242
- "use strict";
243
- init_encoding();
244
- }
245
- });
246
-
247
- // src/crypto/services/WalletKeyEncryptionService.ts
248
- var WalletKeyEncryptionService;
249
- var init_WalletKeyEncryptionService = __esm({
250
- "src/crypto/services/WalletKeyEncryptionService.ts"() {
251
- "use strict";
252
- init_crypto_utils();
253
- init_encoding();
254
- WalletKeyEncryptionService = class {
255
- eciesProvider;
256
- constructor(config) {
257
- this.eciesProvider = config.eciesProvider;
258
- }
259
- /**
260
- * Encrypts data using a wallet's public key.
261
- *
262
- * @param data - The plaintext message to encrypt for the wallet owner.
263
- * @param publicKey - The recipient wallet's public key for encryption.
264
- * @returns A promise that resolves to the encrypted data as a hex string.
265
- * @throws {Error} When encryption fails due to invalid key format.
266
- *
267
- * @example
268
- * ```typescript
269
- * const encrypted = await processor.encryptWithWalletPublicKey(
270
- * "Secret message",
271
- * "0x04..." // 65-byte uncompressed public key
272
- * );
273
- * console.log(`Encrypted: ${encrypted}`);
274
- * ```
275
- */
276
- async encryptWithWalletPublicKey(data, publicKey) {
277
- const publicKeyBytes = processWalletPublicKey(publicKey);
278
- const dataBytes = stringToBytes(data);
279
- const encrypted = await this.eciesProvider.encrypt(
280
- publicKeyBytes,
281
- dataBytes
282
- );
283
- const result = concatBytes(
284
- encrypted.iv,
285
- encrypted.ephemPublicKey,
286
- encrypted.ciphertext,
287
- encrypted.mac
288
- );
289
- return bytesToHex(result);
290
- }
291
- /**
292
- * Decrypts data using a wallet's private key.
293
- *
294
- * @param encryptedData - The hex-encoded encrypted data to decrypt.
295
- * @param privateKey - The wallet's private key for decryption.
296
- * @returns A promise that resolves to the decrypted plaintext message.
297
- * @throws {Error} When decryption fails due to invalid data or key format.
298
- *
299
- * @example
300
- * ```typescript
301
- * const decrypted = await processor.decryptWithWalletPrivateKey(
302
- * encryptedHexString,
303
- * "0x..." // 32-byte private key
304
- * );
305
- * console.log(`Decrypted: ${decrypted}`);
306
- * ```
307
- */
308
- async decryptWithWalletPrivateKey(encryptedData, privateKey) {
309
- const privateKeyBytes = processWalletPrivateKey(privateKey);
310
- const encryptedBytes = hexToBytes(encryptedData);
311
- const encrypted = parseEncryptedDataBuffer(encryptedBytes);
312
- const decrypted = await this.eciesProvider.decrypt(
313
- privateKeyBytes,
314
- encrypted
315
- );
316
- return bytesToString(decrypted);
317
- }
318
- /**
319
- * Encrypts a Uint8Array with a wallet public key
320
- *
321
- * @param data - Binary data to encrypt
322
- * @param publicKey - Public key as hex string or Uint8Array
323
- * @returns Encrypted data structure
324
- */
325
- async encryptBinary(data, publicKey) {
326
- const publicKeyBytes = processWalletPublicKey(publicKey);
327
- return this.eciesProvider.encrypt(publicKeyBytes, data);
328
- }
329
- /**
330
- * Decrypts to a Uint8Array with a wallet private key
331
- *
332
- * @param encrypted - Encrypted data structure
333
- * @param privateKey - Private key as hex string or Uint8Array
334
- * @returns Decrypted binary data
335
- */
336
- async decryptBinary(encrypted, privateKey) {
337
- const privateKeyBytes = processWalletPrivateKey(privateKey);
338
- return this.eciesProvider.decrypt(privateKeyBytes, encrypted);
339
- }
340
- /**
341
- * Gets the underlying ECIES provider
342
- *
343
- * @returns The ECIES provider instance
344
- */
345
- getECIESProvider() {
346
- return this.eciesProvider;
347
- }
348
- };
349
- }
350
- });
351
-
352
- // src/crypto/ecies/constants.ts
353
- var CURVE, CIPHER, KDF, MAC, FORMAT;
354
- var init_constants = __esm({
355
- "src/crypto/ecies/constants.ts"() {
356
- "use strict";
357
- CURVE = {
358
- /** The elliptic curve used (secp256k1 - same as Bitcoin/Ethereum) */
359
- name: "secp256k1",
360
- /** Private key length in bytes */
361
- PRIVATE_KEY_LENGTH: 32,
362
- /** Compressed public key length in bytes (0x02 or 0x03 prefix + 32 bytes) */
363
- COMPRESSED_PUBLIC_KEY_LENGTH: 33,
364
- /** Uncompressed public key length in bytes (0x04 prefix + 64 bytes) */
365
- UNCOMPRESSED_PUBLIC_KEY_LENGTH: 65,
366
- /** ECDH shared secret X coordinate length */
367
- SHARED_SECRET_LENGTH: 32,
368
- /** Public key prefixes */
369
- PREFIX: {
370
- /** Uncompressed public key prefix */
371
- UNCOMPRESSED: 4,
372
- /** Compressed public key prefix for even Y */
373
- COMPRESSED_EVEN: 2,
374
- /** Compressed public key prefix for odd Y */
375
- COMPRESSED_ODD: 3
376
- },
377
- /** X coordinate starts at byte 1 (after prefix) */
378
- X_COORDINATE_OFFSET: 1,
379
- /** X coordinate ends at byte 33 (1 + 32) */
380
- X_COORDINATE_END: 33
381
- };
382
- CIPHER = {
383
- /** Cipher algorithm - must match eccrypto */
384
- algorithm: "aes-256-cbc",
385
- /** AES key length in bytes */
386
- KEY_LENGTH: 32,
387
- /** Initialization vector length in bytes */
388
- IV_LENGTH: 16,
389
- /** Block size for AES */
390
- BLOCK_SIZE: 16
391
- };
392
- KDF = {
393
- /** Hash algorithm for key derivation - must match eccrypto */
394
- algorithm: "sha512",
395
- /** Output length of SHA-512 in bytes */
396
- OUTPUT_LENGTH: 64,
397
- /** Encryption key slice (first 32 bytes of KDF output) */
398
- ENCRYPTION_KEY_OFFSET: 0,
399
- ENCRYPTION_KEY_LENGTH: 32,
400
- /** MAC key slice (last 32 bytes of KDF output) */
401
- MAC_KEY_OFFSET: 32,
402
- MAC_KEY_LENGTH: 32
403
- };
404
- MAC = {
405
- /** MAC algorithm - must match eccrypto */
406
- algorithm: "sha256",
407
- /** HMAC-SHA256 output length in bytes */
408
- LENGTH: 32
409
- };
410
- FORMAT = {
411
- /** Offsets for each component in serialized format */
412
- IV_OFFSET: 0,
413
- IV_LENGTH: CIPHER.IV_LENGTH,
414
- /** Ephemeral public key (always uncompressed in eccrypto format) */
415
- EPHEMERAL_KEY_OFFSET: CIPHER.IV_LENGTH,
416
- EPHEMERAL_KEY_LENGTH: CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
417
- /** Ciphertext starts after IV and ephemeral key */
418
- CIPHERTEXT_OFFSET: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
419
- /** MAC is always the last 32 bytes */
420
- MAC_LENGTH: MAC.LENGTH,
421
- /** Minimum size of encrypted data (IV + ephemKey + MAC, no ciphertext) */
422
- MIN_ENCRYPTED_LENGTH: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + MAC.LENGTH,
423
- /**
424
- * Helper to calculate total length of encrypted data
425
- *
426
- * @param ciphertextLength - Length of the ciphertext portion
427
- * @returns Total length including all components
428
- */
429
- getTotalLength: (ciphertextLength) => CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + ciphertextLength + MAC.LENGTH
430
- };
431
- }
432
- });
433
-
434
- // src/crypto/ecies/interface.ts
435
- function isECIESEncrypted(obj) {
436
- if (!obj || typeof obj !== "object") return false;
437
- const enc = obj;
438
- const isUint8Array = (value) => {
439
- return value instanceof Uint8Array || typeof Buffer !== "undefined" && Buffer.isBuffer(value);
440
- };
441
- 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;
442
- }
443
- var ECIESError;
444
- var init_interface = __esm({
445
- "src/crypto/ecies/interface.ts"() {
446
- "use strict";
447
- init_constants();
448
- ECIESError = class extends Error {
449
- constructor(message, code, cause) {
450
- super(message);
451
- this.code = code;
452
- this.cause = cause;
453
- this.name = "ECIESError";
454
- }
455
- };
456
- }
457
- });
458
-
459
- // src/crypto/ecies/utils.ts
460
- function hexToBytes2(hex) {
461
- if (hex.length % 2 !== 0) {
462
- throw new Error("Hex string must have even length");
463
- }
464
- const bytes = new Uint8Array(hex.length / 2);
465
- for (let i = 0; i < hex.length; i += 2) {
466
- bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
467
- }
468
- return bytes;
469
- }
470
- function bytesToHex2(bytes) {
471
- return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
472
- }
473
- function stringToBytes2(str) {
474
- return new TextEncoder().encode(str);
475
- }
476
- function bytesToString2(bytes) {
477
- return new TextDecoder().decode(bytes);
478
- }
479
- function concatBytes2(...arrays) {
480
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
481
- const result = new Uint8Array(totalLength);
482
- let offset = 0;
483
- for (const arr of arrays) {
484
- result.set(arr, offset);
485
- offset += arr.length;
486
- }
487
- return result;
488
- }
489
- function constantTimeEqual(a, b) {
490
- if (a.length !== b.length) return false;
491
- let result = 0;
492
- for (let i = 0; i < a.length; i++) {
493
- result |= a[i] ^ b[i];
494
- }
495
- return result === 0;
496
- }
497
- var init_utils = __esm({
498
- "src/crypto/ecies/utils.ts"() {
499
- "use strict";
500
- }
501
- });
502
-
503
- // src/crypto/ecies/base.ts
504
- var BaseECIESUint8;
505
- var init_base = __esm({
506
- "src/crypto/ecies/base.ts"() {
507
- "use strict";
508
- init_interface();
509
- init_constants();
510
- init_utils();
511
- BaseECIESUint8 = class _BaseECIESUint8 {
512
- // Cache for validated public keys to avoid repeated validation
513
- static validatedKeys = /* @__PURE__ */ new WeakMap();
514
- /**
515
- * Normalizes a public key to uncompressed format.
516
- *
517
- * @param publicKey - Public key in any format.
518
- * @returns Uncompressed public key (65 bytes).
519
- * @throws {ECIESError} If key format is invalid.
520
- */
521
- normalizePublicKey(publicKey) {
522
- if (_BaseECIESUint8.validatedKeys.has(publicKey)) {
523
- return publicKey;
524
- }
525
- if (publicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH) {
526
- if (publicKey[0] !== CURVE.PREFIX.UNCOMPRESSED) {
527
- throw new ECIESError(
528
- "Invalid uncompressed public key prefix",
529
- "INVALID_KEY"
530
- );
531
- }
532
- if (!this.validatePublicKey(publicKey)) {
533
- throw new ECIESError("Invalid public key", "INVALID_KEY");
534
- }
535
- _BaseECIESUint8.validatedKeys.set(publicKey, true);
536
- return publicKey;
537
- }
538
- if (publicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) {
539
- const decompressed = this.decompressPublicKey(publicKey);
540
- if (!decompressed) {
541
- throw new ECIESError("Failed to decompress public key", "INVALID_KEY");
542
- }
543
- _BaseECIESUint8.validatedKeys.set(decompressed, true);
544
- return decompressed;
545
- }
546
- throw new ECIESError(
547
- `Invalid public key length: ${publicKey.length}`,
548
- "INVALID_KEY"
549
- );
550
- }
551
- /**
552
- * Encrypts data using ECIES.
553
- *
554
- * @param publicKey - The recipient's public key (compressed or uncompressed)
555
- * @param message - The data to encrypt
556
- * @returns Promise resolving to encrypted data structure
557
- */
558
- async encrypt(publicKey, message) {
559
- try {
560
- if (!(publicKey instanceof Uint8Array)) {
561
- throw new ECIESError("Public key must be a Uint8Array", "INVALID_KEY");
562
- }
563
- if (!(message instanceof Uint8Array)) {
564
- throw new ECIESError(
565
- "Message must be a Uint8Array",
566
- "ENCRYPTION_FAILED"
567
- );
568
- }
569
- if (publicKey.length === 0) {
570
- throw new ECIESError("Public key cannot be empty", "INVALID_KEY");
571
- }
572
- const pubKey = this.normalizePublicKey(publicKey);
573
- let ephemeralPrivateKey;
574
- do {
575
- ephemeralPrivateKey = this.generateRandomBytes(
576
- CURVE.PRIVATE_KEY_LENGTH
577
- );
578
- } while (!this.verifyPrivateKey(ephemeralPrivateKey));
579
- const ephemeralPublicKey = this.createPublicKey(
580
- ephemeralPrivateKey,
581
- false
582
- );
583
- if (!ephemeralPublicKey) {
584
- throw new ECIESError(
585
- "Failed to generate ephemeral public key",
586
- "ENCRYPTION_FAILED"
587
- );
588
- }
589
- const sharedSecret = this.performECDH(pubKey, ephemeralPrivateKey);
590
- const kdf = this.sha512(sharedSecret);
591
- const encryptionKey = kdf.slice(
592
- KDF.ENCRYPTION_KEY_OFFSET,
593
- KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
594
- );
595
- const macKey = kdf.slice(
596
- KDF.MAC_KEY_OFFSET,
597
- KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
598
- );
599
- const iv = this.generateRandomBytes(CIPHER.IV_LENGTH);
600
- const ciphertext = await this.aesEncrypt(encryptionKey, iv, message);
601
- const macData = concatBytes2(iv, ephemeralPublicKey, ciphertext);
602
- const mac = this.hmacSha256(macKey, macData);
603
- this.clearBuffer(ephemeralPrivateKey);
604
- this.clearBuffer(sharedSecret);
605
- this.clearBuffer(kdf);
606
- return {
607
- iv,
608
- ephemPublicKey: ephemeralPublicKey,
609
- ciphertext,
610
- mac
611
- };
612
- } catch (error) {
613
- if (error instanceof ECIESError) throw error;
614
- throw new ECIESError(
615
- `Encryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
616
- "ENCRYPTION_FAILED",
617
- error instanceof Error ? error : void 0
618
- );
619
- }
620
- }
621
- /**
622
- * Decrypts ECIES encrypted data.
623
- *
624
- * @param privateKey - The recipient's private key (32 bytes)
625
- * @param encrypted - The encrypted data structure from encrypt()
626
- * @returns Promise resolving to the original plaintext
627
- */
628
- async decrypt(privateKey, encrypted) {
629
- try {
630
- if (!(privateKey instanceof Uint8Array)) {
631
- throw new ECIESError("Private key must be a Uint8Array", "INVALID_KEY");
632
- }
633
- if (!isECIESEncrypted(encrypted)) {
634
- throw new ECIESError(
635
- "Invalid encrypted data structure",
636
- "DECRYPTION_FAILED"
637
- );
638
- }
639
- if (privateKey.length !== CURVE.PRIVATE_KEY_LENGTH) {
640
- throw new ECIESError(
641
- `Invalid private key length: ${privateKey.length}`,
642
- "INVALID_KEY"
643
- );
644
- }
645
- if (!this.verifyPrivateKey(privateKey)) {
646
- throw new ECIESError("Invalid private key", "INVALID_KEY");
647
- }
648
- const ephemeralPublicKey = this.normalizePublicKey(
649
- encrypted.ephemPublicKey
650
- );
651
- const sharedSecret = this.performECDH(ephemeralPublicKey, privateKey);
652
- const kdf = this.sha512(sharedSecret);
653
- const encryptionKey = kdf.slice(
654
- KDF.ENCRYPTION_KEY_OFFSET,
655
- KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
656
- );
657
- const macKey = kdf.slice(
658
- KDF.MAC_KEY_OFFSET,
659
- KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
660
- );
661
- const macData = concatBytes2(
662
- encrypted.iv,
663
- encrypted.ephemPublicKey,
664
- encrypted.ciphertext
665
- );
666
- const expectedMac = this.hmacSha256(macKey, macData);
667
- if (!constantTimeEqual(encrypted.mac, expectedMac)) {
668
- throw new ECIESError("MAC verification failed", "MAC_MISMATCH");
669
- }
670
- const decrypted = await this.aesDecrypt(
671
- encryptionKey,
672
- encrypted.iv,
673
- encrypted.ciphertext
674
- );
675
- this.clearBuffer(sharedSecret);
676
- this.clearBuffer(kdf);
677
- return decrypted;
678
- } catch (error) {
679
- if (error instanceof ECIESError) throw error;
680
- throw new ECIESError(
681
- `Decryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
682
- "DECRYPTION_FAILED",
683
- error instanceof Error ? error : void 0
684
- );
685
- }
686
- }
687
- /**
688
- * Clears sensitive data from memory using multi-pass overwrite.
689
- *
690
- * @remarks
691
- * Uses multiple passes with different patterns to make it harder
692
- * for JIT compilers to optimize away the operation. While not
693
- * guaranteed in JavaScript, this is a best-effort approach to
694
- * clear sensitive data from memory.
695
- *
696
- * @param buffer - The buffer to clear
697
- */
698
- clearBuffer(buffer) {
699
- if (buffer && buffer.length > 0) {
700
- buffer.fill(0);
701
- buffer.fill(255);
702
- buffer.fill(170);
703
- buffer.fill(0);
704
- for (let i = 0; i < buffer.length; i++) {
705
- buffer[i] = i & 255 ^ 90;
706
- }
707
- buffer.fill(0);
708
- }
709
- }
710
- };
711
- }
712
- });
713
-
714
141
  // src/schemas/dataSchema.schema.json
715
142
  var dataSchema_schema_default;
716
143
  var init_dataSchema_schema = __esm({
@@ -772,8 +199,10 @@ var init_dataSchema_schema = __esm({
772
199
  });
773
200
 
774
201
  // src/utils/schemaValidation.ts
775
- function validateDataSchema(schema) {
776
- return schemaValidator.validateDataSchema(schema);
202
+ function validateDataSchemaAgainstMetaSchema(schema) {
203
+ const validator = schemaValidator;
204
+ validator.validateDataSchemaAgainstMetaSchema(schema);
205
+ return schema;
777
206
  }
778
207
  function validateDataAgainstSchema(data, schema) {
779
208
  return schemaValidator.validateDataAgainstSchema(data, schema);
@@ -808,9 +237,9 @@ var init_schemaValidation = __esm({
808
237
  this.dataSchemaValidator = this.ajv.compile(dataSchema_schema_default);
809
238
  }
810
239
  /**
811
- * Validates a data schema against the Vana meta-schema
240
+ * Validates a data schema definition against the Vana meta-schema
812
241
  *
813
- * @param schema - The data schema to validate
242
+ * @param schema - The data schema definition to validate
814
243
  * @throws SchemaValidationError if invalid
815
244
  * @example
816
245
  * ```typescript
@@ -829,10 +258,10 @@ var init_schemaValidation = __esm({
829
258
  * }
830
259
  * };
831
260
  *
832
- * validator.validateDataSchema(schema); // throws if invalid
261
+ * validator.validateDataSchemaAgainstMetaSchema(schema); // throws if invalid
833
262
  * ```
834
263
  */
835
- validateDataSchema(schema) {
264
+ validateDataSchemaAgainstMetaSchema(schema) {
836
265
  const isValid = this.dataSchemaValidator(schema);
837
266
  if (!isValid) {
838
267
  const errors = this.dataSchemaValidator.errors || [];
@@ -852,10 +281,10 @@ var init_schemaValidation = __esm({
852
281
  }
853
282
  }
854
283
  /**
855
- * Validates data against a JSON Schema from a schema
284
+ * Validates data against a JSON Schema
856
285
  *
857
286
  * @param data - The data to validate
858
- * @param schema - The schema containing the validation rules (DataSchema or Schema)
287
+ * @param schema - The schema containing the validation rules (must have been validated or fetched from chain)
859
288
  * @throws SchemaValidationError if invalid
860
289
  * @example
861
290
  * ```typescript
@@ -865,25 +294,22 @@ var init_schemaValidation = __esm({
865
294
  * const schema = await vana.schemas.get(1);
866
295
  * validator.validateDataAgainstSchema(userData, schema);
867
296
  *
868
- * // Also works with DataSchema object
869
- * const dataSchema: DataSchema = {
297
+ * // Also works with pre-validated DataSchema object
298
+ * const dataSchema = validator.validateDataSchemaAgainstMetaSchema({
870
299
  * name: "User Profile",
871
300
  * version: "1.0.0",
872
301
  * dialect: "json",
873
302
  * schema: { type: "object", properties: { name: { type: "string" } } }
874
- * };
303
+ * });
875
304
  * validator.validateDataAgainstSchema(userData, dataSchema);
876
305
  * ```
877
306
  */
878
307
  validateDataAgainstSchema(data, schema) {
879
- if (!("id" in schema)) {
880
- this.validateDataSchema(schema);
881
- }
882
308
  if (schema.dialect !== "json") {
883
- throw new SchemaValidationError(
884
- `Data validation only supported for JSON dialect, got: ${schema.dialect}`,
885
- []
309
+ console.warn(
310
+ `[SchemaValidator] Data validation skipped: dialect '${schema.dialect}' does not support data validation. Only JSON schemas can validate data structure.`
886
311
  );
312
+ return;
887
313
  }
888
314
  if (typeof schema.schema !== "object") {
889
315
  throw new SchemaValidationError(
@@ -949,9 +375,9 @@ var init_schemaValidation = __esm({
949
375
  }
950
376
  }
951
377
  /**
952
- * Fetches and validates a schema from a URL
378
+ * Fetches and validates a data schema from a URL
953
379
  *
954
- * @param url - The URL to fetch the schema from
380
+ * @param url - The URL to fetch the data schema from
955
381
  * @returns The validated data schema
956
382
  * @throws SchemaValidationError if invalid or fetch fails
957
383
  * @example
@@ -967,7 +393,7 @@ var init_schemaValidation = __esm({
967
393
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
968
394
  }
969
395
  const schema = await response.json();
970
- this.validateDataSchema(schema);
396
+ this.validateDataSchemaAgainstMetaSchema(schema);
971
397
  if (schema.dialect === "sqlite" && typeof schema.schema === "string") {
972
398
  this.validateSQLiteDDL(schema.schema, schema.dialectVersion);
973
399
  }
@@ -1616,19 +1042,19 @@ var init_eventMappings = __esm({
1616
1042
  // DataRegistry operations
1617
1043
  addFile: {
1618
1044
  contract: "DataRegistry",
1619
- event: "FileAdded"
1045
+ event: "FileAddedV2"
1620
1046
  },
1621
1047
  addFileWithPermissionsAndSchema: {
1622
1048
  contract: "DataRegistry",
1623
- event: "FileAdded"
1049
+ event: "FileAddedV2"
1624
1050
  },
1625
1051
  addFileWithSchema: {
1626
1052
  contract: "DataRegistry",
1627
- event: "FileAdded"
1053
+ event: "FileAddedV2"
1628
1054
  },
1629
1055
  addFileWithPermissions: {
1630
1056
  contract: "DataRegistry",
1631
- event: "FileAdded"
1057
+ event: "FileAddedV2"
1632
1058
  },
1633
1059
  addRefinement: {
1634
1060
  contract: "DataRegistry",
@@ -3115,6 +2541,37 @@ var init_DataRegistryImplementation = __esm({
3115
2541
  name: "FileAdded",
3116
2542
  type: "event"
3117
2543
  },
2544
+ {
2545
+ anonymous: false,
2546
+ inputs: [
2547
+ {
2548
+ indexed: true,
2549
+ internalType: "uint256",
2550
+ name: "fileId",
2551
+ type: "uint256"
2552
+ },
2553
+ {
2554
+ indexed: true,
2555
+ internalType: "address",
2556
+ name: "ownerAddress",
2557
+ type: "address"
2558
+ },
2559
+ {
2560
+ indexed: false,
2561
+ internalType: "string",
2562
+ name: "url",
2563
+ type: "string"
2564
+ },
2565
+ {
2566
+ indexed: false,
2567
+ internalType: "uint256",
2568
+ name: "schemaId",
2569
+ type: "uint256"
2570
+ }
2571
+ ],
2572
+ name: "FileAddedV2",
2573
+ type: "event"
2574
+ },
3118
2575
  {
3119
2576
  anonymous: false,
3120
2577
  inputs: [
@@ -3662,6 +3119,19 @@ var init_DataRegistryImplementation = __esm({
3662
3119
  stateMutability: "view",
3663
3120
  type: "function"
3664
3121
  },
3122
+ {
3123
+ inputs: [],
3124
+ name: "emitLegacyEvents",
3125
+ outputs: [
3126
+ {
3127
+ internalType: "bool",
3128
+ name: "",
3129
+ type: "bool"
3130
+ }
3131
+ ],
3132
+ stateMutability: "view",
3133
+ type: "function"
3134
+ },
3665
3135
  {
3666
3136
  inputs: [
3667
3137
  {
@@ -3819,6 +3289,11 @@ var init_DataRegistryImplementation = __esm({
3819
3289
  name: "url",
3820
3290
  type: "string"
3821
3291
  },
3292
+ {
3293
+ internalType: "uint256",
3294
+ name: "schemaId",
3295
+ type: "uint256"
3296
+ },
3822
3297
  {
3823
3298
  internalType: "uint256",
3824
3299
  name: "addedAtBlock",
@@ -4102,6 +3577,19 @@ var init_DataRegistryImplementation = __esm({
4102
3577
  stateMutability: "nonpayable",
4103
3578
  type: "function"
4104
3579
  },
3580
+ {
3581
+ inputs: [
3582
+ {
3583
+ internalType: "bool",
3584
+ name: "newEmitLegacyEvents",
3585
+ type: "bool"
3586
+ }
3587
+ ],
3588
+ name: "updateEmitLegacyEvents",
3589
+ outputs: [],
3590
+ stateMutability: "nonpayable",
3591
+ type: "function"
3592
+ },
4105
3593
  {
4106
3594
  inputs: [
4107
3595
  {
@@ -36909,7 +36397,7 @@ var init_schemas = __esm({
36909
36397
  dialect,
36910
36398
  schema: schemaDefinition
36911
36399
  };
36912
- validateDataSchema(dataSchema);
36400
+ validateDataSchemaAgainstMetaSchema(dataSchema);
36913
36401
  if (!this.context.storageManager) {
36914
36402
  if (this.context.validateStorageRequired) {
36915
36403
  this.context.validateStorageRequired();
@@ -37018,7 +36506,7 @@ var init_schemas = __esm({
37018
36506
  `Invalid schema definition format for schema ${schemaId}`
37019
36507
  );
37020
36508
  }
37021
- validateDataSchema(definition);
36509
+ validateDataSchemaAgainstMetaSchema(definition);
37022
36510
  const dataSchema = definition;
37023
36511
  if (dataSchema.name !== metadata.name) {
37024
36512
  throw new Error(
@@ -37353,7 +36841,7 @@ var init_schemas = __esm({
37353
36841
  try {
37354
36842
  const definition = await fetchFromUrl(schema.definitionUrl);
37355
36843
  if (definition && typeof definition === "object") {
37356
- validateDataSchema(definition);
36844
+ validateDataSchemaAgainstMetaSchema(definition);
37357
36845
  const dataSchema = definition;
37358
36846
  schema.version = dataSchema.version;
37359
36847
  schema.description = dataSchema.description;
@@ -37372,204 +36860,123 @@ var init_schemas = __esm({
37372
36860
  }
37373
36861
  });
37374
36862
 
37375
- // src/crypto/ecies/browser.ts
37376
- var secp256k12, import_hmac, import_sha2, BrowserECIESUint8Provider;
37377
- var init_browser = __esm({
37378
- "src/crypto/ecies/browser.ts"() {
37379
- "use strict";
37380
- secp256k12 = __toESM(require("@noble/secp256k1"), 1);
37381
- init_base();
37382
- import_hmac = require("@noble/hashes/hmac");
37383
- import_sha2 = require("@noble/hashes/sha2");
37384
- BrowserECIESUint8Provider = class extends BaseECIESUint8 {
37385
- generateRandomBytes(length) {
37386
- const bytes = new Uint8Array(length);
37387
- crypto.getRandomValues(bytes);
37388
- return bytes;
37389
- }
37390
- verifyPrivateKey(privateKey) {
37391
- try {
37392
- return secp256k12.utils.isValidPrivateKey(privateKey);
37393
- } catch {
37394
- return false;
37395
- }
37396
- }
37397
- createPublicKey(privateKey, compressed) {
37398
- try {
37399
- return secp256k12.getPublicKey(privateKey, compressed);
37400
- } catch {
37401
- return null;
37402
- }
37403
- }
37404
- validatePublicKey(publicKey) {
37405
- try {
37406
- secp256k12.Point.fromHex(publicKey);
37407
- return true;
37408
- } catch {
37409
- return false;
37410
- }
37411
- }
37412
- decompressPublicKey(publicKey) {
37413
- try {
37414
- const point = secp256k12.Point.fromHex(publicKey);
37415
- return point.toRawBytes(false);
37416
- } catch {
37417
- return null;
37418
- }
37419
- }
37420
- performECDH(publicKey, privateKey) {
37421
- try {
37422
- const sharedPoint = secp256k12.getSharedSecret(
37423
- privateKey,
37424
- publicKey,
37425
- true
37426
- );
37427
- return sharedPoint.slice(1);
37428
- } catch (error) {
37429
- throw new Error(
37430
- `ECDH failed: ${error instanceof Error ? error.message : "Unknown error"}`
37431
- );
37432
- }
37433
- }
37434
- sha512(data) {
37435
- return (0, import_sha2.sha512)(data);
37436
- }
37437
- hmacSha256(key, data) {
37438
- return (0, import_hmac.hmac)(import_sha2.sha256, key, data);
37439
- }
37440
- async aesEncrypt(key, iv, plaintext) {
37441
- const cryptoKey = await crypto.subtle.importKey(
37442
- "raw",
37443
- key,
37444
- { name: "AES-CBC" },
37445
- false,
37446
- ["encrypt"]
37447
- );
37448
- const encrypted = await crypto.subtle.encrypt(
37449
- { name: "AES-CBC", iv },
37450
- cryptoKey,
37451
- plaintext
37452
- );
37453
- return new Uint8Array(encrypted);
37454
- }
37455
- async aesDecrypt(key, iv, ciphertext) {
37456
- const cryptoKey = await crypto.subtle.importKey(
37457
- "raw",
37458
- key,
37459
- { name: "AES-CBC" },
37460
- false,
37461
- ["decrypt"]
37462
- );
37463
- const decrypted = await crypto.subtle.decrypt(
37464
- { name: "AES-CBC", iv },
37465
- cryptoKey,
37466
- ciphertext
37467
- );
37468
- return new Uint8Array(decrypted);
37469
- }
37470
- };
37471
- }
37472
- });
37473
-
37474
36863
  // src/platform/browser.ts
37475
36864
  var browser_exports = {};
37476
36865
  __export(browser_exports, {
37477
- BrowserPlatformAdapter: () => BrowserPlatformAdapter
36866
+ BrowserPlatformAdapter: () => BrowserPlatformAdapter,
36867
+ browserPlatformAdapter: () => browserPlatformAdapter
37478
36868
  });
37479
- var secp256k13, getOpenPGP2, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter;
37480
- var init_browser2 = __esm({
36869
+ var getOpenPGP2, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter, browserPlatformAdapter;
36870
+ var init_browser = __esm({
37481
36871
  "src/platform/browser.ts"() {
37482
36872
  "use strict";
36873
+ init_crypto_utils();
37483
36874
  init_pgp_utils();
37484
36875
  init_error_utils();
37485
36876
  init_lazy_import();
37486
- init_WalletKeyEncryptionService();
37487
- init_crypto_utils();
37488
- init_utils();
37489
- secp256k13 = __toESM(require("@noble/secp256k1"), 1);
37490
- init_browser();
37491
36877
  getOpenPGP2 = lazyImport(() => import("openpgp"));
37492
36878
  BrowserCryptoAdapter = class {
37493
- eciesProvider = new BrowserECIESUint8Provider();
37494
- walletKeyEncryptionService = new WalletKeyEncryptionService({
37495
- eciesProvider: this.eciesProvider
37496
- });
37497
36879
  async encryptWithPublicKey(data, publicKeyHex) {
37498
36880
  try {
37499
- const publicKeyBytes = hexToBytes2(publicKeyHex);
37500
- const encrypted = await this.eciesProvider.encrypt(
37501
- publicKeyBytes,
37502
- stringToBytes2(data)
36881
+ const eccrypto = await import("eccrypto-js");
36882
+ const publicKeyBuffer = Buffer.from(publicKeyHex, "hex");
36883
+ const encrypted = await eccrypto.encrypt(
36884
+ publicKeyBuffer,
36885
+ Buffer.from(data, "utf8")
37503
36886
  );
37504
- const result = concatBytes2(
36887
+ const result = Buffer.concat([
37505
36888
  encrypted.iv,
37506
36889
  encrypted.ephemPublicKey,
37507
36890
  encrypted.ciphertext,
37508
36891
  encrypted.mac
37509
- );
37510
- return bytesToHex2(result);
36892
+ ]);
36893
+ return result.toString("hex");
37511
36894
  } catch (error) {
37512
- throw wrapCryptoError("encryptWithPublicKey", error);
36895
+ throw new Error(`Encryption failed: ${error}`);
37513
36896
  }
37514
36897
  }
37515
36898
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
37516
36899
  try {
37517
- const encryptedBytes = hexToBytes2(encryptedData);
37518
- const privateKeyBytes = hexToBytes2(privateKeyHex);
37519
- const encrypted = parseEncryptedDataBuffer(encryptedBytes);
37520
- const decrypted = await this.eciesProvider.decrypt(
37521
- privateKeyBytes,
37522
- encrypted
36900
+ const eccrypto = await import("eccrypto-js");
36901
+ const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
36902
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
36903
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
36904
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
36905
+ const decryptedBuffer = await eccrypto.decrypt(
36906
+ privateKeyBuffer,
36907
+ encryptedObj
37523
36908
  );
37524
- return bytesToString2(decrypted);
36909
+ return decryptedBuffer.toString("utf8");
37525
36910
  } catch (error) {
37526
- throw wrapCryptoError("decryptWithPrivateKey", error);
36911
+ throw new Error(`Decryption failed: ${error}`);
37527
36912
  }
37528
36913
  }
37529
- async encryptWithWalletPublicKey(data, publicKey) {
36914
+ async generateKeyPair() {
37530
36915
  try {
37531
- return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
37532
- data,
37533
- publicKey
37534
- );
36916
+ const eccrypto = await import("eccrypto-js");
36917
+ const privateKeyBytes = new Uint8Array(32);
36918
+ crypto.getRandomValues(privateKeyBytes);
36919
+ const privateKey = Buffer.from(privateKeyBytes);
36920
+ const publicKey = eccrypto.getPublicCompressed(privateKey);
36921
+ return {
36922
+ privateKey: privateKey.toString("hex"),
36923
+ publicKey: publicKey.toString("hex")
36924
+ };
37535
36925
  } catch (error) {
37536
- throw wrapCryptoError("encryptWithWalletPublicKey", error);
36926
+ throw wrapCryptoError("key generation", error);
37537
36927
  }
37538
36928
  }
37539
- async decryptWithWalletPrivateKey(encryptedData, privateKey) {
36929
+ async encryptWithWalletPublicKey(data, publicKey) {
37540
36930
  try {
37541
- return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
37542
- encryptedData,
37543
- privateKey
36931
+ const eccrypto = await import("eccrypto-js");
36932
+ const uncompressedKey = processWalletPublicKey(publicKey);
36933
+ const encryptedBuffer = await eccrypto.encrypt(
36934
+ uncompressedKey,
36935
+ Buffer.from(data)
37544
36936
  );
36937
+ const result = Buffer.concat([
36938
+ encryptedBuffer.iv,
36939
+ encryptedBuffer.ephemPublicKey,
36940
+ encryptedBuffer.ciphertext,
36941
+ encryptedBuffer.mac
36942
+ ]);
36943
+ return result.toString("hex");
37545
36944
  } catch (error) {
37546
- throw wrapCryptoError("decryptWithWalletPrivateKey", error);
36945
+ throw wrapCryptoError("encrypt with wallet public key", error);
37547
36946
  }
37548
36947
  }
37549
- async generateKeyPair() {
36948
+ async decryptWithWalletPrivateKey(encryptedData, privateKey) {
37550
36949
  try {
37551
- const privateKeyBytes = secp256k13.utils.randomPrivateKey();
37552
- const publicKeyBytes = secp256k13.getPublicKey(privateKeyBytes, true);
37553
- return {
37554
- privateKey: bytesToHex2(privateKeyBytes),
37555
- publicKey: bytesToHex2(publicKeyBytes)
37556
- };
36950
+ const eccrypto = await import("eccrypto-js");
36951
+ const privateKeyBuffer = processWalletPrivateKey(privateKey);
36952
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
36953
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
36954
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
36955
+ const decryptedBuffer = await eccrypto.decrypt(
36956
+ privateKeyBuffer,
36957
+ encryptedObj
36958
+ );
36959
+ return decryptedBuffer.toString("utf8");
37557
36960
  } catch (error) {
37558
- throw wrapCryptoError("generateKeyPair", error);
36961
+ throw wrapCryptoError("decrypt with wallet private key", error);
37559
36962
  }
37560
36963
  }
37561
36964
  async encryptWithPassword(data, password) {
37562
36965
  try {
37563
36966
  const openpgp = await getOpenPGP2();
37564
- const message = await openpgp.createMessage({ binary: data });
36967
+ const message = await openpgp.createMessage({
36968
+ binary: data
36969
+ });
37565
36970
  const encrypted = await openpgp.encrypt({
37566
36971
  message,
37567
36972
  passwords: [password],
37568
36973
  format: "binary"
37569
36974
  });
37570
- return new Uint8Array(encrypted);
36975
+ const response = new Response(encrypted);
36976
+ const arrayBuffer = await response.arrayBuffer();
36977
+ return new Uint8Array(arrayBuffer);
37571
36978
  } catch (error) {
37572
- throw wrapCryptoError("encryptWithPassword", error);
36979
+ throw new Error(`Failed to encrypt with password: ${error}`);
37573
36980
  }
37574
36981
  }
37575
36982
  async decryptWithPassword(encryptedData, password) {
@@ -37578,14 +36985,14 @@ var init_browser2 = __esm({
37578
36985
  const message = await openpgp.readMessage({
37579
36986
  binaryMessage: encryptedData
37580
36987
  });
37581
- const { data } = await openpgp.decrypt({
36988
+ const { data: decrypted } = await openpgp.decrypt({
37582
36989
  message,
37583
36990
  passwords: [password],
37584
36991
  format: "binary"
37585
36992
  });
37586
- return new Uint8Array(data);
36993
+ return new Uint8Array(decrypted);
37587
36994
  } catch (error) {
37588
- throw wrapCryptoError("decryptWithPassword", error);
36995
+ throw new Error(`Failed to decrypt with password: ${error}`);
37589
36996
  }
37590
36997
  }
37591
36998
  };
@@ -37637,6 +37044,9 @@ var init_browser2 = __esm({
37637
37044
  };
37638
37045
  BrowserHttpAdapter = class {
37639
37046
  async fetch(url, options) {
37047
+ if (typeof fetch === "undefined") {
37048
+ throw new Error("Fetch API not available in this browser environment");
37049
+ }
37640
37050
  return fetch(url, options);
37641
37051
  }
37642
37052
  };
@@ -37654,19 +37064,17 @@ var init_browser2 = __esm({
37654
37064
  }
37655
37065
  set(key, value) {
37656
37066
  try {
37657
- if (typeof sessionStorage === "undefined") {
37658
- return;
37067
+ if (typeof sessionStorage !== "undefined") {
37068
+ sessionStorage.setItem(this.prefix + key, value);
37659
37069
  }
37660
- sessionStorage.setItem(this.prefix + key, value);
37661
37070
  } catch {
37662
37071
  }
37663
37072
  }
37664
37073
  delete(key) {
37665
37074
  try {
37666
- if (typeof sessionStorage === "undefined") {
37667
- return;
37075
+ if (typeof sessionStorage !== "undefined") {
37076
+ sessionStorage.removeItem(this.prefix + key);
37668
37077
  }
37669
- sessionStorage.removeItem(this.prefix + key);
37670
37078
  } catch {
37671
37079
  }
37672
37080
  }
@@ -37675,25 +37083,30 @@ var init_browser2 = __esm({
37675
37083
  if (typeof sessionStorage === "undefined") {
37676
37084
  return;
37677
37085
  }
37678
- const keysToRemove = [];
37679
- for (let i = 0; i < sessionStorage.length; i++) {
37680
- const key = sessionStorage.key(i);
37681
- if (key?.startsWith(this.prefix)) {
37682
- keysToRemove.push(key);
37086
+ const keys = Object.keys(sessionStorage);
37087
+ for (const key of keys) {
37088
+ if (key.startsWith(this.prefix)) {
37089
+ sessionStorage.removeItem(key);
37683
37090
  }
37684
37091
  }
37685
- keysToRemove.forEach((key) => sessionStorage.removeItem(key));
37686
37092
  } catch {
37687
37093
  }
37688
37094
  }
37689
37095
  };
37690
37096
  BrowserPlatformAdapter = class {
37691
- crypto = new BrowserCryptoAdapter();
37692
- pgp = new BrowserPGPAdapter();
37693
- http = new BrowserHttpAdapter();
37694
- cache = new BrowserCacheAdapter();
37097
+ crypto;
37098
+ pgp;
37099
+ http;
37100
+ cache;
37695
37101
  platform = "browser";
37102
+ constructor() {
37103
+ this.crypto = new BrowserCryptoAdapter();
37104
+ this.pgp = new BrowserPGPAdapter();
37105
+ this.http = new BrowserHttpAdapter();
37106
+ this.cache = new BrowserCacheAdapter();
37107
+ }
37696
37108
  };
37109
+ browserPlatformAdapter = new BrowserPlatformAdapter();
37697
37110
  }
37698
37111
  });
37699
37112
 
@@ -37811,7 +37224,7 @@ __export(index_node_exports, {
37811
37224
  storeGrantFile: () => storeGrantFile,
37812
37225
  summarizeGrant: () => summarizeGrant,
37813
37226
  validateDataAgainstSchema: () => validateDataAgainstSchema,
37814
- validateDataSchema: () => validateDataSchema,
37227
+ validateDataSchemaAgainstMetaSchema: () => validateDataSchemaAgainstMetaSchema,
37815
37228
  validateGrant: () => validateGrant,
37816
37229
  validateGrantExpiry: () => validateGrantExpiry,
37817
37230
  validateGrantFile: () => validateGrantFile,
@@ -37823,6 +37236,7 @@ __export(index_node_exports, {
37823
37236
  module.exports = __toCommonJS(index_node_exports);
37824
37237
 
37825
37238
  // src/platform/node.ts
37239
+ init_crypto_utils();
37826
37240
  init_pgp_utils();
37827
37241
  init_error_utils();
37828
37242
 
@@ -37851,123 +37265,15 @@ async function streamToUint8Array(stream) {
37851
37265
 
37852
37266
  // src/platform/node.ts
37853
37267
  init_lazy_import();
37854
- init_WalletKeyEncryptionService();
37855
- init_crypto_utils();
37856
-
37857
- // src/crypto/ecies/node.ts
37858
- var import_crypto = require("crypto");
37859
- init_base();
37860
- var secp256k1;
37861
- try {
37862
- secp256k1 = require("secp256k1");
37863
- } catch {
37864
- throw new Error(
37865
- "Native secp256k1 module not found. Please install with: npm install secp256k1\nThis is required for optimal performance in Node.js environments."
37866
- );
37867
- }
37868
- var NodeECIESUint8Provider = class extends BaseECIESUint8 {
37869
- // Identity hash function for ECDH - returns raw X coordinate
37870
- // CRITICAL: Must handle (x, y, output) signature correctly
37871
- identityHashFn = (x, y, output) => {
37872
- if (output && output.length >= 32) {
37873
- output.set(x);
37874
- return output;
37875
- }
37876
- return x;
37877
- };
37878
- generateRandomBytes(length) {
37879
- return new Uint8Array((0, import_crypto.randomBytes)(length));
37880
- }
37881
- verifyPrivateKey(privateKey) {
37882
- return secp256k1.privateKeyVerify(Buffer.from(privateKey)) === true;
37883
- }
37884
- createPublicKey(privateKey, compressed) {
37885
- try {
37886
- return new Uint8Array(
37887
- secp256k1.publicKeyCreate(Buffer.from(privateKey), compressed)
37888
- );
37889
- } catch {
37890
- return null;
37891
- }
37892
- }
37893
- validatePublicKey(publicKey) {
37894
- return secp256k1.publicKeyVerify(Buffer.from(publicKey)) === true;
37895
- }
37896
- decompressPublicKey(publicKey) {
37897
- try {
37898
- return new Uint8Array(
37899
- secp256k1.publicKeyConvert(Buffer.from(publicKey), false)
37900
- );
37901
- } catch {
37902
- return null;
37903
- }
37904
- }
37905
- performECDH(publicKey, privateKey) {
37906
- try {
37907
- const output = Buffer.alloc(32);
37908
- secp256k1.ecdh(
37909
- Buffer.from(publicKey),
37910
- Buffer.from(privateKey),
37911
- { hashfn: this.identityHashFn },
37912
- output
37913
- );
37914
- return new Uint8Array(output);
37915
- } catch (error) {
37916
- throw new Error(
37917
- `ECDH failed: ${error instanceof Error ? error.message : "Unknown error"}`
37918
- );
37919
- }
37920
- }
37921
- sha512(data) {
37922
- return new Uint8Array(
37923
- (0, import_crypto.createHash)("sha512").update(Buffer.from(data)).digest()
37924
- );
37925
- }
37926
- hmacSha256(key, data) {
37927
- return new Uint8Array(
37928
- (0, import_crypto.createHmac)("sha256", Buffer.from(key)).update(Buffer.from(data)).digest()
37929
- );
37930
- }
37931
- async aesEncrypt(key, iv, plaintext) {
37932
- const cipher = (0, import_crypto.createCipheriv)(
37933
- "aes-256-cbc",
37934
- Buffer.from(key),
37935
- Buffer.from(iv)
37936
- );
37937
- const encrypted = Buffer.concat([
37938
- cipher.update(Buffer.from(plaintext)),
37939
- cipher.final()
37940
- ]);
37941
- return new Uint8Array(encrypted);
37942
- }
37943
- async aesDecrypt(key, iv, ciphertext) {
37944
- const decipher = (0, import_crypto.createDecipheriv)(
37945
- "aes-256-cbc",
37946
- Buffer.from(key),
37947
- Buffer.from(iv)
37948
- );
37949
- const decrypted = Buffer.concat([
37950
- decipher.update(Buffer.from(ciphertext)),
37951
- decipher.final()
37952
- ]);
37953
- return new Uint8Array(decrypted);
37954
- }
37955
- // No Buffer compatibility methods - Uint8Array only public API
37956
- };
37957
-
37958
- // src/platform/node.ts
37959
- init_interface();
37960
37268
  var getOpenPGP = lazyImport(() => import("openpgp"));
37269
+ var getEccrypto = lazyImport(() => import("eccrypto"));
37961
37270
  var NodeCryptoAdapter = class {
37962
- eciesProvider = new NodeECIESUint8Provider();
37963
- walletKeyEncryptionService = new WalletKeyEncryptionService({
37964
- eciesProvider: this.eciesProvider
37965
- });
37966
37271
  async encryptWithPublicKey(data, publicKeyHex) {
37967
37272
  try {
37273
+ const eccrypto = await getEccrypto();
37968
37274
  const publicKey = Buffer.from(publicKeyHex, "hex");
37969
37275
  const message = Buffer.from(data, "utf8");
37970
- const encrypted = await this.eciesProvider.encrypt(publicKey, message);
37276
+ const encrypted = await eccrypto.encrypt(publicKey, message);
37971
37277
  const result = Buffer.concat([
37972
37278
  encrypted.iv,
37973
37279
  encrypted.ephemPublicKey,
@@ -37976,54 +37282,27 @@ var NodeCryptoAdapter = class {
37976
37282
  ]);
37977
37283
  return result.toString("hex");
37978
37284
  } catch (error) {
37979
- if (error instanceof ECIESError) {
37980
- throw error;
37981
- }
37982
- throw new ECIESError(
37983
- `Encryption failed: ${error instanceof Error ? error.message : String(error)}`,
37984
- "ENCRYPTION_FAILED",
37985
- error instanceof Error ? error : void 0
37986
- );
37285
+ throw new Error(`Encryption failed: ${error}`);
37987
37286
  }
37988
37287
  }
37989
37288
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
37990
37289
  try {
37290
+ const eccrypto = await getEccrypto();
37991
37291
  const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
37992
37292
  const encryptedBuffer = Buffer.from(encryptedData, "hex");
37993
37293
  const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
37994
- const encryptedObj = {
37995
- iv,
37996
- ephemPublicKey,
37997
- ciphertext,
37998
- mac
37999
- };
38000
- const decrypted = await this.eciesProvider.decrypt(
38001
- privateKeyBuffer,
38002
- encryptedObj
38003
- );
38004
- return new TextDecoder().decode(decrypted);
37294
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
37295
+ const decrypted = await eccrypto.decrypt(privateKeyBuffer, encryptedObj);
37296
+ return decrypted.toString("utf8");
38005
37297
  } catch (error) {
38006
- if (error instanceof ECIESError) {
38007
- throw error;
38008
- }
38009
- throw new ECIESError(
38010
- `Decryption failed: ${error instanceof Error ? error.message : String(error)}`,
38011
- "DECRYPTION_FAILED",
38012
- error instanceof Error ? error : void 0
38013
- );
37298
+ throw new Error(`Decryption failed: ${error}`);
38014
37299
  }
38015
37300
  }
38016
37301
  async generateKeyPair() {
38017
37302
  try {
38018
- const { randomBytes: randomBytes2 } = await import("crypto");
38019
- const secp256k14 = await import("secp256k1");
38020
- let privateKey;
38021
- do {
38022
- privateKey = randomBytes2(32);
38023
- } while (!secp256k14.privateKeyVerify(privateKey));
38024
- const publicKey = Buffer.from(
38025
- secp256k14.publicKeyCreate(privateKey, true)
38026
- );
37303
+ const eccrypto = await getEccrypto();
37304
+ const privateKey = eccrypto.generatePrivate();
37305
+ const publicKey = eccrypto.getPublicCompressed(privateKey);
38027
37306
  return {
38028
37307
  privateKey: privateKey.toString("hex"),
38029
37308
  publicKey: publicKey.toString("hex")
@@ -38034,20 +37313,35 @@ var NodeCryptoAdapter = class {
38034
37313
  }
38035
37314
  async encryptWithWalletPublicKey(data, publicKey) {
38036
37315
  try {
38037
- return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
38038
- data,
38039
- publicKey
37316
+ const eccrypto = await getEccrypto();
37317
+ const uncompressedKey = processWalletPublicKey(publicKey);
37318
+ const encrypted = await eccrypto.encrypt(
37319
+ uncompressedKey,
37320
+ Buffer.from(data)
38040
37321
  );
37322
+ const result = Buffer.concat([
37323
+ encrypted.iv,
37324
+ encrypted.ephemPublicKey,
37325
+ encrypted.ciphertext,
37326
+ encrypted.mac
37327
+ ]);
37328
+ return result.toString("hex");
38041
37329
  } catch (error) {
38042
37330
  throw wrapCryptoError("encrypt with wallet public key", error);
38043
37331
  }
38044
37332
  }
38045
37333
  async decryptWithWalletPrivateKey(encryptedData, privateKey) {
38046
37334
  try {
38047
- return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
38048
- encryptedData,
38049
- privateKey
37335
+ const eccrypto = await getEccrypto();
37336
+ const privateKeyBuffer = processWalletPrivateKey(privateKey);
37337
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
37338
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
37339
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
37340
+ const decryptedBuffer = await eccrypto.decrypt(
37341
+ privateKeyBuffer,
37342
+ encryptedObj
38050
37343
  );
37344
+ return decryptedBuffer.toString("utf8");
38051
37345
  } catch (error) {
38052
37346
  throw wrapCryptoError("decrypt with wallet private key", error);
38053
37347
  }
@@ -38219,6 +37513,9 @@ var StorageError = class extends Error {
38219
37513
  }
38220
37514
  };
38221
37515
 
37516
+ // src/types/index.ts
37517
+ init_schemaValidation();
37518
+
38222
37519
  // src/types/external-apis.ts
38223
37520
  function isReplicateAPIResponse(value) {
38224
37521
  if (typeof value !== "object" || value === null) return false;
@@ -38661,8 +37958,7 @@ function validateOperationAccess(grantFile, requestedOperation) {
38661
37958
  }
38662
37959
 
38663
37960
  // src/utils/signatureCache.ts
38664
- var import_sha256 = require("@noble/hashes/sha256");
38665
- var import_utils2 = require("@noble/hashes/utils");
37961
+ init_crypto_utils();
38666
37962
  var SignatureCache = class {
38667
37963
  static PREFIX = "vana_sig_";
38668
37964
  static DEFAULT_TTL_HOURS = 2;
@@ -38761,12 +38057,12 @@ var SignatureCache = class {
38761
38057
  * Generate a deterministic hash of a message object for cache key generation
38762
38058
  *
38763
38059
  * @remarks
38764
- * Creates a cryptographically secure hash from complex objects including EIP-712 typed data.
38765
- * Uses SHA-256 for collision resistance and deterministic key generation.
38766
- * Handles BigInt serialization and sorts object keys for consistency.
38060
+ * Creates a consistent hash from complex objects including EIP-712 typed data.
38061
+ * Handles BigInt serialization and produces a 32-character hash that balances
38062
+ * uniqueness with key length constraints.
38767
38063
  *
38768
38064
  * @param message - The message object to hash (typically EIP-712 typed data)
38769
- * @returns A hex string hash (SHA-256) suitable for cache keys
38065
+ * @returns A 32-character hash string suitable for cache keys
38770
38066
  * @example
38771
38067
  * ```typescript
38772
38068
  * const typedData = {
@@ -38775,35 +38071,30 @@ var SignatureCache = class {
38775
38071
  * };
38776
38072
  *
38777
38073
  * const hash = SignatureCache.hashMessage(typedData);
38778
- * // Returns SHA-256 hash like: "a1b2c3d4e5f6..."
38074
+ * // Returns something like: "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"
38779
38075
  * ```
38780
38076
  */
38781
38077
  static hashMessage(message) {
38782
- const jsonString = JSON.stringify(message, this.deterministicReplacer);
38783
- const hashBytes = (0, import_sha256.sha256)(new TextEncoder().encode(jsonString));
38784
- return (0, import_utils2.bytesToHex)(hashBytes);
38078
+ const jsonString = JSON.stringify(message, this.bigIntReplacer);
38079
+ const base64Hash = toBase64(jsonString);
38080
+ const cleaned = base64Hash.replace(/[^a-zA-Z0-9]/g, "");
38081
+ if (cleaned.length > 32) {
38082
+ return cleaned.substring(0, 16) + cleaned.substring(cleaned.length - 16);
38083
+ }
38084
+ return cleaned.substring(0, 32);
38785
38085
  }
38786
38086
  /**
38787
- * Deterministic JSON replacer that handles BigInt values and sorts object keys
38788
- * This ensures consistent cache key generation for EIP-712 typed data
38087
+ * Custom JSON replacer that converts BigInt values to strings for serialization
38088
+ * This ensures deterministic cache key generation for EIP-712 typed data
38789
38089
  *
38790
38090
  * @param _key - The object key being serialized (unused)
38791
38091
  * @param value - The value to serialize
38792
- * @returns The serialized value with sorted keys for objects
38092
+ * @returns The serialized value
38793
38093
  */
38794
- static deterministicReplacer(_key, value) {
38094
+ static bigIntReplacer(_key, value) {
38795
38095
  if (typeof value === "bigint") {
38796
38096
  return `__BIGINT__${value.toString()}`;
38797
38097
  }
38798
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
38799
- return Object.keys(value).sort().reduce(
38800
- (sorted, key) => {
38801
- sorted[key] = value[key];
38802
- return sorted;
38803
- },
38804
- {}
38805
- );
38806
- }
38807
38098
  return value;
38808
38099
  }
38809
38100
  };
@@ -43044,6 +42335,29 @@ var DataController = class {
43044
42335
  const userFiles = Array.from(fileMap.values()).sort(
43045
42336
  (a, b) => Number((b.addedAtTimestamp || 0n) - (a.addedAtTimestamp || 0n))
43046
42337
  );
42338
+ if (userFiles.length > 0) {
42339
+ try {
42340
+ const fileIds = userFiles.map((f) => f.id);
42341
+ let proofMap;
42342
+ try {
42343
+ proofMap = await this._fetchProofsFromSubgraph(fileIds, endpoint);
42344
+ } catch (subgraphError) {
42345
+ console.debug(
42346
+ "Failed to fetch proofs from subgraph, trying chain:",
42347
+ subgraphError
42348
+ );
42349
+ proofMap = await this._fetchProofsFromChain(fileIds);
42350
+ }
42351
+ for (const file of userFiles) {
42352
+ const dlpIds = proofMap.get(file.id);
42353
+ if (dlpIds && dlpIds.length > 0) {
42354
+ file.dlpIds = dlpIds;
42355
+ }
42356
+ }
42357
+ } catch (error) {
42358
+ console.warn("Failed to fetch proof data for files:", error);
42359
+ }
42360
+ }
43047
42361
  return userFiles;
43048
42362
  } catch (error) {
43049
42363
  console.error("Failed to fetch user files from subgraph:", error);
@@ -43052,6 +42366,349 @@ var DataController = class {
43052
42366
  );
43053
42367
  }
43054
42368
  }
42369
+ /**
42370
+ * Fetches proof data for multiple files from the subgraph.
42371
+ *
42372
+ * @private
42373
+ * @param fileIds - Array of file IDs to fetch proofs for
42374
+ * @param subgraphUrl - The subgraph endpoint URL
42375
+ * @returns Map of file IDs to their associated DLP IDs
42376
+ */
42377
+ async _fetchProofsFromSubgraph(fileIds, subgraphUrl) {
42378
+ const query = `
42379
+ query GetFileProofs($fileIds: [BigInt!]!) {
42380
+ dataRegistryProofs(where: { fileId_in: $fileIds }) {
42381
+ fileId
42382
+ dlp {
42383
+ id
42384
+ }
42385
+ }
42386
+ }
42387
+ `;
42388
+ const response = await fetch(subgraphUrl, {
42389
+ method: "POST",
42390
+ headers: {
42391
+ "Content-Type": "application/json"
42392
+ },
42393
+ body: JSON.stringify({
42394
+ query,
42395
+ variables: {
42396
+ fileIds: fileIds.map((id) => id.toString())
42397
+ }
42398
+ })
42399
+ });
42400
+ if (!response.ok) {
42401
+ throw new Error(
42402
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42403
+ );
42404
+ }
42405
+ const result = await response.json();
42406
+ if (result.errors) {
42407
+ throw new Error(
42408
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42409
+ );
42410
+ }
42411
+ const proofMap = /* @__PURE__ */ new Map();
42412
+ if (result.data?.dataRegistryProofs) {
42413
+ for (const proof of result.data.dataRegistryProofs) {
42414
+ if (proof.dlp?.id) {
42415
+ const fileId = parseInt(proof.fileId);
42416
+ const dlpId = parseInt(proof.dlp.id);
42417
+ if (!proofMap.has(fileId)) {
42418
+ proofMap.set(fileId, []);
42419
+ }
42420
+ const dlpIds = proofMap.get(fileId);
42421
+ if (!dlpIds.includes(dlpId)) {
42422
+ dlpIds.push(dlpId);
42423
+ }
42424
+ }
42425
+ }
42426
+ }
42427
+ return proofMap;
42428
+ }
42429
+ /**
42430
+ * Fetches proof data for multiple files from the blockchain.
42431
+ * Falls back to this when subgraph is unavailable.
42432
+ *
42433
+ * @private
42434
+ * @param fileIds - Array of file IDs to fetch proofs for
42435
+ * @returns Map of file IDs to their associated DLP IDs
42436
+ */
42437
+ async _fetchProofsFromChain(fileIds) {
42438
+ const chainId = this.context.walletClient.chain?.id;
42439
+ if (!chainId) {
42440
+ throw new Error("Chain ID not available");
42441
+ }
42442
+ const dataRegistryAddress = getContractAddress(chainId, "DataRegistry");
42443
+ const dataRegistryAbi = getAbi("DataRegistry");
42444
+ const proofMap = /* @__PURE__ */ new Map();
42445
+ for (const fileId of fileIds) {
42446
+ const dlpIds = [];
42447
+ let proofIndex = 0;
42448
+ let hasMoreProofs = true;
42449
+ while (hasMoreProofs) {
42450
+ try {
42451
+ const proof = await this.context.publicClient.readContract({
42452
+ address: dataRegistryAddress,
42453
+ abi: dataRegistryAbi,
42454
+ functionName: "fileProofs",
42455
+ args: [BigInt(fileId), BigInt(proofIndex)]
42456
+ });
42457
+ if (proof?.data?.dlpId) {
42458
+ const dlpId = Number(proof.data.dlpId);
42459
+ if (!dlpIds.includes(dlpId)) {
42460
+ dlpIds.push(dlpId);
42461
+ }
42462
+ }
42463
+ proofIndex++;
42464
+ } catch {
42465
+ hasMoreProofs = false;
42466
+ }
42467
+ }
42468
+ if (dlpIds.length > 0) {
42469
+ proofMap.set(fileId, dlpIds);
42470
+ }
42471
+ }
42472
+ return proofMap;
42473
+ }
42474
+ /**
42475
+ * Retrieves information about a specific Data Liquidity Pool (DLP).
42476
+ *
42477
+ * @remarks
42478
+ * DLPs are entities that process and verify data files in the Vana network.
42479
+ * This method fetches DLP metadata including name, status, and performance rating.
42480
+ * Uses subgraph first for efficiency, falls back to chain if unavailable.
42481
+ *
42482
+ * @param dlpId - The unique identifier of the DLP
42483
+ * @param options - Optional parameters
42484
+ * @param options.subgraphUrl - Custom subgraph URL to override default
42485
+ * @returns Promise resolving to DLP information
42486
+ * @throws {Error} When DLP cannot be found - "DLP not found: {dlpId}"
42487
+ * @throws {Error} When query fails - "Failed to fetch DLP: {error}"
42488
+ * @example
42489
+ * ```typescript
42490
+ * const dlp = await vana.data.getDLP(26);
42491
+ * console.log(`DLP ${dlp.name}: ${dlp.status}`);
42492
+ * ```
42493
+ */
42494
+ async getDLP(dlpId, options = {}) {
42495
+ const subgraphUrl = options.subgraphUrl || this.context.subgraphUrl;
42496
+ if (subgraphUrl) {
42497
+ try {
42498
+ const query = `
42499
+ query GetDLP($id: ID!) {
42500
+ dlp(id: $id) {
42501
+ id
42502
+ name
42503
+ metadata
42504
+ status
42505
+ address
42506
+ owner
42507
+ }
42508
+ }
42509
+ `;
42510
+ const response = await fetch(subgraphUrl, {
42511
+ method: "POST",
42512
+ headers: {
42513
+ "Content-Type": "application/json"
42514
+ },
42515
+ body: JSON.stringify({
42516
+ query,
42517
+ variables: {
42518
+ id: dlpId.toString()
42519
+ }
42520
+ })
42521
+ });
42522
+ if (!response.ok) {
42523
+ throw new Error(
42524
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42525
+ );
42526
+ }
42527
+ const result = await response.json();
42528
+ if (result.errors) {
42529
+ throw new Error(
42530
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42531
+ );
42532
+ }
42533
+ if (!result.data?.dlp) {
42534
+ throw new Error(`DLP not found: ${dlpId}`);
42535
+ }
42536
+ return {
42537
+ id: parseInt(result.data.dlp.id),
42538
+ name: result.data.dlp.name || "",
42539
+ metadata: result.data.dlp.metadata,
42540
+ status: result.data.dlp.status ? parseInt(result.data.dlp.status) : void 0,
42541
+ address: result.data.dlp.address,
42542
+ owner: result.data.dlp.owner
42543
+ };
42544
+ } catch (error) {
42545
+ console.debug("Subgraph query failed, falling back to chain:", error);
42546
+ }
42547
+ }
42548
+ try {
42549
+ const chainId = this.context.walletClient.chain?.id;
42550
+ if (!chainId) {
42551
+ throw new Error("Chain ID not available");
42552
+ }
42553
+ const dlpRegistryAddress = getContractAddress(chainId, "DLPRegistry");
42554
+ const dlpRegistryAbi = getAbi("DLPRegistry");
42555
+ const dlpData = await this.context.publicClient.readContract({
42556
+ address: dlpRegistryAddress,
42557
+ abi: dlpRegistryAbi,
42558
+ functionName: "dlps",
42559
+ args: [BigInt(dlpId)]
42560
+ });
42561
+ if (!dlpData || !dlpData.name) {
42562
+ throw new Error(`DLP not found: ${dlpId}`);
42563
+ }
42564
+ return {
42565
+ id: dlpId,
42566
+ name: dlpData.name,
42567
+ metadata: dlpData.metadata,
42568
+ status: dlpData.status,
42569
+ address: dlpData.dlpAddress,
42570
+ owner: dlpData.ownerAddress
42571
+ };
42572
+ } catch (error) {
42573
+ throw new Error(
42574
+ `Failed to fetch DLP: ${error instanceof Error ? error.message : "Unknown error"}`
42575
+ );
42576
+ }
42577
+ }
42578
+ /**
42579
+ * Lists all Data Liquidity Pools (DLPs) with optional pagination.
42580
+ *
42581
+ * @remarks
42582
+ * Fetches a paginated list of all DLPs registered in the network.
42583
+ * Uses subgraph for efficient querying with fallback to chain multicall.
42584
+ *
42585
+ * @param options - Optional parameters for pagination and filtering
42586
+ * @param options.limit - Maximum number of DLPs to return (default: 100)
42587
+ * @param options.offset - Number of DLPs to skip (default: 0)
42588
+ * @param options.subgraphUrl - Custom subgraph URL to override default
42589
+ * @returns Promise resolving to array of DLP information
42590
+ * @throws {Error} When query fails - "Failed to list DLPs: {error}"
42591
+ * @example
42592
+ * ```typescript
42593
+ * // Get first 10 DLPs
42594
+ * const dlps = await vana.data.listDLPs({ limit: 10 });
42595
+ * dlps.forEach(dlp => console.log(`${dlp.id}: ${dlp.name}`));
42596
+ *
42597
+ * // Get next page
42598
+ * const nextPage = await vana.data.listDLPs({ limit: 10, offset: 10 });
42599
+ * ```
42600
+ */
42601
+ async listDLPs(options = {}) {
42602
+ const { limit = 100, offset = 0 } = options;
42603
+ const subgraphUrl = options.subgraphUrl || this.context.subgraphUrl;
42604
+ if (subgraphUrl) {
42605
+ try {
42606
+ const query = `
42607
+ query ListDLPs($first: Int!, $skip: Int!) {
42608
+ dlps(first: $first, skip: $skip, orderBy: id) {
42609
+ id
42610
+ name
42611
+ metadata
42612
+ status
42613
+ address
42614
+ owner
42615
+ }
42616
+ }
42617
+ `;
42618
+ const response = await fetch(subgraphUrl, {
42619
+ method: "POST",
42620
+ headers: {
42621
+ "Content-Type": "application/json"
42622
+ },
42623
+ body: JSON.stringify({
42624
+ query,
42625
+ variables: {
42626
+ first: limit,
42627
+ skip: offset
42628
+ }
42629
+ })
42630
+ });
42631
+ if (!response.ok) {
42632
+ throw new Error(
42633
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42634
+ );
42635
+ }
42636
+ const result = await response.json();
42637
+ if (result.errors) {
42638
+ throw new Error(
42639
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42640
+ );
42641
+ }
42642
+ const dlps = result.data?.dlps || [];
42643
+ return dlps.map((dlp) => ({
42644
+ id: parseInt(dlp.id),
42645
+ name: dlp.name || "",
42646
+ metadata: dlp.metadata,
42647
+ status: dlp.status ? parseInt(dlp.status) : void 0,
42648
+ address: dlp.address,
42649
+ owner: dlp.owner
42650
+ }));
42651
+ } catch (error) {
42652
+ console.debug("Subgraph query failed, falling back to chain:", error);
42653
+ }
42654
+ }
42655
+ try {
42656
+ const chainId = this.context.walletClient.chain?.id;
42657
+ if (!chainId) {
42658
+ throw new Error("Chain ID not available");
42659
+ }
42660
+ const dlpRegistryAddress = getContractAddress(chainId, "DLPRegistry");
42661
+ const dlpRegistryAbi = getAbi("DLPRegistry");
42662
+ const dlpCount = await this.context.publicClient.readContract({
42663
+ address: dlpRegistryAddress,
42664
+ abi: dlpRegistryAbi,
42665
+ functionName: "dlpsCount",
42666
+ args: []
42667
+ });
42668
+ const totalCount = Number(dlpCount);
42669
+ const start = offset;
42670
+ const end = Math.min(start + limit, totalCount);
42671
+ if (end <= start) {
42672
+ return [];
42673
+ }
42674
+ const calls = [];
42675
+ for (let i = start + 1; i <= end; i++) {
42676
+ calls.push({
42677
+ address: dlpRegistryAddress,
42678
+ abi: dlpRegistryAbi,
42679
+ functionName: "dlps",
42680
+ args: [BigInt(i)]
42681
+ });
42682
+ }
42683
+ const results = await gasAwareMulticall(this.context.publicClient, {
42684
+ contracts: calls,
42685
+ allowFailure: true,
42686
+ batchSize: 50
42687
+ });
42688
+ const dlps = [];
42689
+ for (let i = 0; i < results.length; i++) {
42690
+ const result = results[i];
42691
+ if (result.status === "success" && result.result) {
42692
+ const dlpData = result.result;
42693
+ if (dlpData.name) {
42694
+ dlps.push({
42695
+ id: start + i + 1,
42696
+ name: dlpData.name,
42697
+ metadata: dlpData.metadata,
42698
+ status: dlpData.status,
42699
+ address: dlpData.dlpAddress,
42700
+ owner: dlpData.ownerAddress
42701
+ });
42702
+ }
42703
+ }
42704
+ }
42705
+ return dlps;
42706
+ } catch (error) {
42707
+ throw new Error(
42708
+ `Failed to list DLPs: ${error instanceof Error ? error.message : "Unknown error"}`
42709
+ );
42710
+ }
42711
+ }
43055
42712
  /**
43056
42713
  * Retrieves a list of permissions granted by a user.
43057
42714
  *
@@ -44478,10 +44135,10 @@ var DataController = class {
44478
44135
  );
44479
44136
  }
44480
44137
  /**
44481
- * Validates a data schema against the Vana meta-schema.
44138
+ * Validates a data schema definition against the Vana meta-schema.
44482
44139
  *
44483
- * @param schema - The data schema to validate
44484
- * @returns Assertion that schema is valid (throws if invalid)
44140
+ * @param schema - The data schema definition to validate
44141
+ * @returns The validated DataSchema
44485
44142
  * @throws SchemaValidationError if invalid
44486
44143
  * @example
44487
44144
  * ```typescript
@@ -44498,11 +44155,11 @@ var DataController = class {
44498
44155
  * }
44499
44156
  * };
44500
44157
  *
44501
- * vana.data.validateDataSchema(schema);
44158
+ * const validatedSchema = vana.data.validateDataSchemaAgainstMetaSchema(schema);
44502
44159
  * ```
44503
44160
  */
44504
- validateDataSchema(schema) {
44505
- return validateDataSchema(schema);
44161
+ validateDataSchemaAgainstMetaSchema(schema) {
44162
+ return validateDataSchemaAgainstMetaSchema(schema);
44506
44163
  }
44507
44164
  /**
44508
44165
  * Validates data against a JSON Schema from a data schema.
@@ -44535,9 +44192,9 @@ var DataController = class {
44535
44192
  return validateDataAgainstSchema(data, schema);
44536
44193
  }
44537
44194
  /**
44538
- * Fetches and validates a schema from a URL, then returns the parsed data schema.
44195
+ * Fetches and validates a data schema from a URL, then returns the parsed data schema.
44539
44196
  *
44540
- * @param url - The URL to fetch the schema from
44197
+ * @param url - The URL to fetch the data schema from
44541
44198
  * @returns The validated data schema
44542
44199
  * @throws SchemaValidationError if invalid or fetch fails
44543
44200
  * @example
@@ -45729,7 +45386,7 @@ var GoogleDriveStorage = class {
45729
45386
  };
45730
45387
 
45731
45388
  // src/storage/providers/ipfs.ts
45732
- init_encoding();
45389
+ init_crypto_utils();
45733
45390
  var IpfsStorage = class _IpfsStorage {
45734
45391
  constructor(config) {
45735
45392
  this.config = config;
@@ -45769,9 +45426,8 @@ var IpfsStorage = class _IpfsStorage {
45769
45426
  * ```
45770
45427
  */
45771
45428
  static forInfura(credentials) {
45772
- const encoder = new TextEncoder();
45773
45429
  const auth = toBase64(
45774
- encoder.encode(`${credentials.projectId}:${credentials.projectSecret}`)
45430
+ `${credentials.projectId}:${credentials.projectSecret}`
45775
45431
  );
45776
45432
  return new _IpfsStorage({
45777
45433
  apiEndpoint: "https://ipfs.infura.io:5001/api/v0/add",
@@ -46631,7 +46287,7 @@ var vanaMainnet2 = {
46631
46287
  url: "https://vanascan.io"
46632
46288
  }
46633
46289
  },
46634
- subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/vana/7.0.7/gn"
46290
+ subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/vana/prod/gn"
46635
46291
  };
46636
46292
  var moksha = {
46637
46293
  id: 14800,
@@ -46652,7 +46308,7 @@ var moksha = {
46652
46308
  url: "https://moksha.vanascan.io"
46653
46309
  }
46654
46310
  },
46655
- subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/moksha/7.0.7/gn"
46311
+ subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/moksha/prod/gn"
46656
46312
  };
46657
46313
  function getChainConfig(chainId) {
46658
46314
  switch (chainId) {
@@ -47681,7 +47337,7 @@ async function handleRelayerRequest(sdk, payload) {
47681
47337
 
47682
47338
  // src/index.node.ts
47683
47339
  init_transactionHandle();
47684
- init_browser2();
47340
+ init_browser();
47685
47341
 
47686
47342
  // src/platform/utils.ts
47687
47343
  function detectPlatform() {
@@ -47706,7 +47362,7 @@ async function createPlatformAdapter() {
47706
47362
  const { NodePlatformAdapter: NodePlatformAdapter2 } = await import(moduleName);
47707
47363
  return new NodePlatformAdapter2();
47708
47364
  } else {
47709
- const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser2(), browser_exports));
47365
+ const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser(), browser_exports));
47710
47366
  return new BrowserPlatformAdapter2();
47711
47367
  }
47712
47368
  } catch (error) {
@@ -47727,7 +47383,7 @@ async function createPlatformAdapterFor(platformType) {
47727
47383
  const { NodePlatformAdapter: NodePlatformAdapter2 } = await import(moduleName);
47728
47384
  return new NodePlatformAdapter2();
47729
47385
  } else {
47730
- const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser2(), browser_exports));
47386
+ const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser(), browser_exports));
47731
47387
  return new BrowserPlatformAdapter2();
47732
47388
  }
47733
47389
  } catch (error) {
@@ -47754,7 +47410,7 @@ function getPlatformCapabilities() {
47754
47410
  }
47755
47411
 
47756
47412
  // src/platform/browser-safe.ts
47757
- init_browser2();
47413
+ init_browser();
47758
47414
  async function createNodePlatformAdapter() {
47759
47415
  if (typeof window !== "undefined") {
47760
47416
  throw new Error(
@@ -48200,7 +47856,7 @@ var index_node_default = Vana;
48200
47856
  storeGrantFile,
48201
47857
  summarizeGrant,
48202
47858
  validateDataAgainstSchema,
48203
- validateDataSchema,
47859
+ validateDataSchemaAgainstMetaSchema,
48204
47860
  validateGrant,
48205
47861
  validateGrantExpiry,
48206
47862
  validateGrantFile,