@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
@@ -1,11 +1,5 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
- }) : x)(function(x) {
6
- if (typeof require !== "undefined") return require.apply(this, arguments);
7
- throw Error('Dynamic require of "' + x + '" is not supported');
8
- });
9
3
  var __esm = (fn, res) => function __init() {
10
4
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
5
  };
@@ -14,6 +8,53 @@ var __export = (target, all) => {
14
8
  __defProp(target, name, { get: all[name], enumerable: true });
15
9
  };
16
10
 
11
+ // src/platform/shared/crypto-utils.ts
12
+ function processWalletPublicKey(publicKey) {
13
+ const publicKeyHex = publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey;
14
+ const publicKeyBytes = Buffer.from(publicKeyHex, "hex");
15
+ return publicKeyBytes.length === 64 ? Buffer.concat([Buffer.from([4]), publicKeyBytes]) : publicKeyBytes;
16
+ }
17
+ function processWalletPrivateKey(privateKey) {
18
+ const privateKeyHex = privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey;
19
+ return Buffer.from(privateKeyHex, "hex");
20
+ }
21
+ function parseEncryptedDataBuffer(encryptedBuffer) {
22
+ return {
23
+ iv: encryptedBuffer.slice(0, 16),
24
+ ephemPublicKey: encryptedBuffer.slice(16, 81),
25
+ // 65 bytes for uncompressed public key
26
+ ciphertext: encryptedBuffer.slice(81, -32),
27
+ mac: encryptedBuffer.slice(-32)
28
+ };
29
+ }
30
+ function toBase64(str) {
31
+ if (typeof Buffer !== "undefined") {
32
+ return Buffer.from(str, "utf8").toString("base64");
33
+ } else if (typeof btoa !== "undefined") {
34
+ return btoa(str);
35
+ } else {
36
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
37
+ let result = "";
38
+ let i = 0;
39
+ while (i < str.length) {
40
+ const a = str.charCodeAt(i++);
41
+ const b = i < str.length ? str.charCodeAt(i++) : 0;
42
+ const c = i < str.length ? str.charCodeAt(i++) : 0;
43
+ const bitmap = a << 16 | b << 8 | c;
44
+ result += chars.charAt(bitmap >> 18 & 63);
45
+ result += chars.charAt(bitmap >> 12 & 63);
46
+ result += i - 2 < str.length ? chars.charAt(bitmap >> 6 & 63) : "=";
47
+ result += i - 1 < str.length ? chars.charAt(bitmap & 63) : "=";
48
+ }
49
+ return result;
50
+ }
51
+ }
52
+ var init_crypto_utils = __esm({
53
+ "src/platform/shared/crypto-utils.ts"() {
54
+ "use strict";
55
+ }
56
+ });
57
+
17
58
  // src/platform/shared/pgp-utils.ts
18
59
  function processPGPKeyOptions(options) {
19
60
  return {
@@ -75,626 +116,6 @@ var init_lazy_import = __esm({
75
116
  }
76
117
  });
77
118
 
78
- // src/utils/encoding.ts
79
- function toBase64(data) {
80
- if (typeof Buffer !== "undefined" && Buffer.from) {
81
- return Buffer.from(data).toString("base64");
82
- }
83
- if (typeof btoa !== "undefined") {
84
- const binary = Array.from(data, (byte) => String.fromCharCode(byte)).join(
85
- ""
86
- );
87
- return btoa(binary);
88
- }
89
- throw new Error("No base64 encoding method available in this environment");
90
- }
91
- function toHex(data) {
92
- if (typeof Buffer !== "undefined" && Buffer.from) {
93
- return Buffer.from(data).toString("hex");
94
- }
95
- return Array.from(data, (byte) => byte.toString(16).padStart(2, "0")).join(
96
- ""
97
- );
98
- }
99
- function fromHex(hex) {
100
- const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
101
- if (cleanHex.length % 2 !== 0) {
102
- throw new Error("Invalid hex string: odd length");
103
- }
104
- if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {
105
- throw new Error("Invalid hex string: contains non-hex characters");
106
- }
107
- if (typeof Buffer !== "undefined" && Buffer.from) {
108
- return new Uint8Array(Buffer.from(cleanHex, "hex"));
109
- }
110
- const bytes = new Uint8Array(cleanHex.length / 2);
111
- for (let i = 0; i < cleanHex.length; i += 2) {
112
- bytes[i / 2] = parseInt(cleanHex.substr(i, 2), 16);
113
- }
114
- return bytes;
115
- }
116
- function stringToBytes(str) {
117
- if (typeof Buffer !== "undefined" && Buffer.from) {
118
- return new Uint8Array(Buffer.from(str, "utf8"));
119
- }
120
- if (typeof TextEncoder !== "undefined") {
121
- return new TextEncoder().encode(str);
122
- }
123
- const bytes = [];
124
- for (let i = 0; i < str.length; i++) {
125
- const char = str.charCodeAt(i);
126
- if (char < 128) {
127
- bytes.push(char);
128
- } else if (char < 2048) {
129
- bytes.push(192 | char >> 6, 128 | char & 63);
130
- } else if (char < 55296 || char >= 57344) {
131
- bytes.push(
132
- 224 | char >> 12,
133
- 128 | char >> 6 & 63,
134
- 128 | char & 63
135
- );
136
- } else {
137
- i++;
138
- const char2 = str.charCodeAt(i);
139
- const codePoint = 65536 + ((char & 1023) << 10 | char2 & 1023);
140
- bytes.push(
141
- 240 | codePoint >> 18,
142
- 128 | codePoint >> 12 & 63,
143
- 128 | codePoint >> 6 & 63,
144
- 128 | codePoint & 63
145
- );
146
- }
147
- }
148
- return new Uint8Array(bytes);
149
- }
150
- function bytesToString(bytes) {
151
- if (typeof Buffer !== "undefined" && Buffer.from) {
152
- return Buffer.from(bytes).toString("utf8");
153
- }
154
- if (typeof TextDecoder !== "undefined") {
155
- return new TextDecoder().decode(bytes);
156
- }
157
- let str = "";
158
- let i = 0;
159
- while (i < bytes.length) {
160
- const byte = bytes[i];
161
- if (byte < 128) {
162
- str += String.fromCharCode(byte);
163
- i++;
164
- } else if ((byte & 224) === 192) {
165
- str += String.fromCharCode((byte & 31) << 6 | bytes[i + 1] & 63);
166
- i += 2;
167
- } else if ((byte & 240) === 224) {
168
- str += String.fromCharCode(
169
- (byte & 15) << 12 | (bytes[i + 1] & 63) << 6 | bytes[i + 2] & 63
170
- );
171
- i += 3;
172
- } else {
173
- const codePoint = ((byte & 7) << 18 | (bytes[i + 1] & 63) << 12 | (bytes[i + 2] & 63) << 6 | bytes[i + 3] & 63) - 65536;
174
- str += String.fromCharCode(
175
- 55296 + (codePoint >> 10),
176
- 56320 + (codePoint & 1023)
177
- );
178
- i += 4;
179
- }
180
- }
181
- return str;
182
- }
183
- var init_encoding = __esm({
184
- "src/utils/encoding.ts"() {
185
- "use strict";
186
- }
187
- });
188
-
189
- // src/utils/crypto-utils.ts
190
- function concatBytes(...arrays) {
191
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
192
- const result = new Uint8Array(totalLength);
193
- let offset = 0;
194
- for (const arr of arrays) {
195
- result.set(arr, offset);
196
- offset += arr.length;
197
- }
198
- return result;
199
- }
200
- function hexToBytes(hex) {
201
- return fromHex(hex);
202
- }
203
- function bytesToHex(bytes) {
204
- return toHex(bytes);
205
- }
206
- function processWalletPublicKey(publicKey) {
207
- const publicKeyHex = typeof publicKey === "string" ? publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey : bytesToHex(publicKey);
208
- const publicKeyBytes = hexToBytes(publicKeyHex);
209
- return publicKeyBytes.length === 64 ? concatBytes(new Uint8Array([4]), publicKeyBytes) : publicKeyBytes;
210
- }
211
- function processWalletPrivateKey(privateKey) {
212
- const privateKeyHex = typeof privateKey === "string" ? privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey : bytesToHex(privateKey);
213
- return hexToBytes(privateKeyHex);
214
- }
215
- function parseEncryptedDataBuffer(encryptedBuffer) {
216
- return {
217
- iv: encryptedBuffer.slice(0, 16),
218
- ephemPublicKey: encryptedBuffer.slice(16, 81),
219
- // 65 bytes for uncompressed public key
220
- ciphertext: encryptedBuffer.slice(81, -32),
221
- mac: encryptedBuffer.slice(-32)
222
- };
223
- }
224
- var init_crypto_utils = __esm({
225
- "src/utils/crypto-utils.ts"() {
226
- "use strict";
227
- init_encoding();
228
- }
229
- });
230
-
231
- // src/crypto/services/WalletKeyEncryptionService.ts
232
- var WalletKeyEncryptionService;
233
- var init_WalletKeyEncryptionService = __esm({
234
- "src/crypto/services/WalletKeyEncryptionService.ts"() {
235
- "use strict";
236
- init_crypto_utils();
237
- init_encoding();
238
- WalletKeyEncryptionService = class {
239
- eciesProvider;
240
- constructor(config) {
241
- this.eciesProvider = config.eciesProvider;
242
- }
243
- /**
244
- * Encrypts data using a wallet's public key.
245
- *
246
- * @param data - The plaintext message to encrypt for the wallet owner.
247
- * @param publicKey - The recipient wallet's public key for encryption.
248
- * @returns A promise that resolves to the encrypted data as a hex string.
249
- * @throws {Error} When encryption fails due to invalid key format.
250
- *
251
- * @example
252
- * ```typescript
253
- * const encrypted = await processor.encryptWithWalletPublicKey(
254
- * "Secret message",
255
- * "0x04..." // 65-byte uncompressed public key
256
- * );
257
- * console.log(`Encrypted: ${encrypted}`);
258
- * ```
259
- */
260
- async encryptWithWalletPublicKey(data, publicKey) {
261
- const publicKeyBytes = processWalletPublicKey(publicKey);
262
- const dataBytes = stringToBytes(data);
263
- const encrypted = await this.eciesProvider.encrypt(
264
- publicKeyBytes,
265
- dataBytes
266
- );
267
- const result = concatBytes(
268
- encrypted.iv,
269
- encrypted.ephemPublicKey,
270
- encrypted.ciphertext,
271
- encrypted.mac
272
- );
273
- return bytesToHex(result);
274
- }
275
- /**
276
- * Decrypts data using a wallet's private key.
277
- *
278
- * @param encryptedData - The hex-encoded encrypted data to decrypt.
279
- * @param privateKey - The wallet's private key for decryption.
280
- * @returns A promise that resolves to the decrypted plaintext message.
281
- * @throws {Error} When decryption fails due to invalid data or key format.
282
- *
283
- * @example
284
- * ```typescript
285
- * const decrypted = await processor.decryptWithWalletPrivateKey(
286
- * encryptedHexString,
287
- * "0x..." // 32-byte private key
288
- * );
289
- * console.log(`Decrypted: ${decrypted}`);
290
- * ```
291
- */
292
- async decryptWithWalletPrivateKey(encryptedData, privateKey) {
293
- const privateKeyBytes = processWalletPrivateKey(privateKey);
294
- const encryptedBytes = hexToBytes(encryptedData);
295
- const encrypted = parseEncryptedDataBuffer(encryptedBytes);
296
- const decrypted = await this.eciesProvider.decrypt(
297
- privateKeyBytes,
298
- encrypted
299
- );
300
- return bytesToString(decrypted);
301
- }
302
- /**
303
- * Encrypts a Uint8Array with a wallet public key
304
- *
305
- * @param data - Binary data to encrypt
306
- * @param publicKey - Public key as hex string or Uint8Array
307
- * @returns Encrypted data structure
308
- */
309
- async encryptBinary(data, publicKey) {
310
- const publicKeyBytes = processWalletPublicKey(publicKey);
311
- return this.eciesProvider.encrypt(publicKeyBytes, data);
312
- }
313
- /**
314
- * Decrypts to a Uint8Array with a wallet private key
315
- *
316
- * @param encrypted - Encrypted data structure
317
- * @param privateKey - Private key as hex string or Uint8Array
318
- * @returns Decrypted binary data
319
- */
320
- async decryptBinary(encrypted, privateKey) {
321
- const privateKeyBytes = processWalletPrivateKey(privateKey);
322
- return this.eciesProvider.decrypt(privateKeyBytes, encrypted);
323
- }
324
- /**
325
- * Gets the underlying ECIES provider
326
- *
327
- * @returns The ECIES provider instance
328
- */
329
- getECIESProvider() {
330
- return this.eciesProvider;
331
- }
332
- };
333
- }
334
- });
335
-
336
- // src/crypto/ecies/constants.ts
337
- var CURVE, CIPHER, KDF, MAC, FORMAT;
338
- var init_constants = __esm({
339
- "src/crypto/ecies/constants.ts"() {
340
- "use strict";
341
- CURVE = {
342
- /** The elliptic curve used (secp256k1 - same as Bitcoin/Ethereum) */
343
- name: "secp256k1",
344
- /** Private key length in bytes */
345
- PRIVATE_KEY_LENGTH: 32,
346
- /** Compressed public key length in bytes (0x02 or 0x03 prefix + 32 bytes) */
347
- COMPRESSED_PUBLIC_KEY_LENGTH: 33,
348
- /** Uncompressed public key length in bytes (0x04 prefix + 64 bytes) */
349
- UNCOMPRESSED_PUBLIC_KEY_LENGTH: 65,
350
- /** ECDH shared secret X coordinate length */
351
- SHARED_SECRET_LENGTH: 32,
352
- /** Public key prefixes */
353
- PREFIX: {
354
- /** Uncompressed public key prefix */
355
- UNCOMPRESSED: 4,
356
- /** Compressed public key prefix for even Y */
357
- COMPRESSED_EVEN: 2,
358
- /** Compressed public key prefix for odd Y */
359
- COMPRESSED_ODD: 3
360
- },
361
- /** X coordinate starts at byte 1 (after prefix) */
362
- X_COORDINATE_OFFSET: 1,
363
- /** X coordinate ends at byte 33 (1 + 32) */
364
- X_COORDINATE_END: 33
365
- };
366
- CIPHER = {
367
- /** Cipher algorithm - must match eccrypto */
368
- algorithm: "aes-256-cbc",
369
- /** AES key length in bytes */
370
- KEY_LENGTH: 32,
371
- /** Initialization vector length in bytes */
372
- IV_LENGTH: 16,
373
- /** Block size for AES */
374
- BLOCK_SIZE: 16
375
- };
376
- KDF = {
377
- /** Hash algorithm for key derivation - must match eccrypto */
378
- algorithm: "sha512",
379
- /** Output length of SHA-512 in bytes */
380
- OUTPUT_LENGTH: 64,
381
- /** Encryption key slice (first 32 bytes of KDF output) */
382
- ENCRYPTION_KEY_OFFSET: 0,
383
- ENCRYPTION_KEY_LENGTH: 32,
384
- /** MAC key slice (last 32 bytes of KDF output) */
385
- MAC_KEY_OFFSET: 32,
386
- MAC_KEY_LENGTH: 32
387
- };
388
- MAC = {
389
- /** MAC algorithm - must match eccrypto */
390
- algorithm: "sha256",
391
- /** HMAC-SHA256 output length in bytes */
392
- LENGTH: 32
393
- };
394
- FORMAT = {
395
- /** Offsets for each component in serialized format */
396
- IV_OFFSET: 0,
397
- IV_LENGTH: CIPHER.IV_LENGTH,
398
- /** Ephemeral public key (always uncompressed in eccrypto format) */
399
- EPHEMERAL_KEY_OFFSET: CIPHER.IV_LENGTH,
400
- EPHEMERAL_KEY_LENGTH: CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
401
- /** Ciphertext starts after IV and ephemeral key */
402
- CIPHERTEXT_OFFSET: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
403
- /** MAC is always the last 32 bytes */
404
- MAC_LENGTH: MAC.LENGTH,
405
- /** Minimum size of encrypted data (IV + ephemKey + MAC, no ciphertext) */
406
- MIN_ENCRYPTED_LENGTH: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + MAC.LENGTH,
407
- /**
408
- * Helper to calculate total length of encrypted data
409
- *
410
- * @param ciphertextLength - Length of the ciphertext portion
411
- * @returns Total length including all components
412
- */
413
- getTotalLength: (ciphertextLength) => CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + ciphertextLength + MAC.LENGTH
414
- };
415
- }
416
- });
417
-
418
- // src/crypto/ecies/interface.ts
419
- function isECIESEncrypted(obj) {
420
- if (!obj || typeof obj !== "object") return false;
421
- const enc = obj;
422
- const isUint8Array = (value) => {
423
- return value instanceof Uint8Array || typeof Buffer !== "undefined" && Buffer.isBuffer(value);
424
- };
425
- 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;
426
- }
427
- var ECIESError;
428
- var init_interface = __esm({
429
- "src/crypto/ecies/interface.ts"() {
430
- "use strict";
431
- init_constants();
432
- ECIESError = class extends Error {
433
- constructor(message, code, cause) {
434
- super(message);
435
- this.code = code;
436
- this.cause = cause;
437
- this.name = "ECIESError";
438
- }
439
- };
440
- }
441
- });
442
-
443
- // src/crypto/ecies/utils.ts
444
- function hexToBytes2(hex) {
445
- if (hex.length % 2 !== 0) {
446
- throw new Error("Hex string must have even length");
447
- }
448
- const bytes = new Uint8Array(hex.length / 2);
449
- for (let i = 0; i < hex.length; i += 2) {
450
- bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
451
- }
452
- return bytes;
453
- }
454
- function bytesToHex2(bytes) {
455
- return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
456
- }
457
- function stringToBytes2(str) {
458
- return new TextEncoder().encode(str);
459
- }
460
- function bytesToString2(bytes) {
461
- return new TextDecoder().decode(bytes);
462
- }
463
- function concatBytes2(...arrays) {
464
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
465
- const result = new Uint8Array(totalLength);
466
- let offset = 0;
467
- for (const arr of arrays) {
468
- result.set(arr, offset);
469
- offset += arr.length;
470
- }
471
- return result;
472
- }
473
- function constantTimeEqual(a, b) {
474
- if (a.length !== b.length) return false;
475
- let result = 0;
476
- for (let i = 0; i < a.length; i++) {
477
- result |= a[i] ^ b[i];
478
- }
479
- return result === 0;
480
- }
481
- var init_utils = __esm({
482
- "src/crypto/ecies/utils.ts"() {
483
- "use strict";
484
- }
485
- });
486
-
487
- // src/crypto/ecies/base.ts
488
- var BaseECIESUint8;
489
- var init_base = __esm({
490
- "src/crypto/ecies/base.ts"() {
491
- "use strict";
492
- init_interface();
493
- init_constants();
494
- init_utils();
495
- BaseECIESUint8 = class _BaseECIESUint8 {
496
- // Cache for validated public keys to avoid repeated validation
497
- static validatedKeys = /* @__PURE__ */ new WeakMap();
498
- /**
499
- * Normalizes a public key to uncompressed format.
500
- *
501
- * @param publicKey - Public key in any format.
502
- * @returns Uncompressed public key (65 bytes).
503
- * @throws {ECIESError} If key format is invalid.
504
- */
505
- normalizePublicKey(publicKey) {
506
- if (_BaseECIESUint8.validatedKeys.has(publicKey)) {
507
- return publicKey;
508
- }
509
- if (publicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH) {
510
- if (publicKey[0] !== CURVE.PREFIX.UNCOMPRESSED) {
511
- throw new ECIESError(
512
- "Invalid uncompressed public key prefix",
513
- "INVALID_KEY"
514
- );
515
- }
516
- if (!this.validatePublicKey(publicKey)) {
517
- throw new ECIESError("Invalid public key", "INVALID_KEY");
518
- }
519
- _BaseECIESUint8.validatedKeys.set(publicKey, true);
520
- return publicKey;
521
- }
522
- if (publicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) {
523
- const decompressed = this.decompressPublicKey(publicKey);
524
- if (!decompressed) {
525
- throw new ECIESError("Failed to decompress public key", "INVALID_KEY");
526
- }
527
- _BaseECIESUint8.validatedKeys.set(decompressed, true);
528
- return decompressed;
529
- }
530
- throw new ECIESError(
531
- `Invalid public key length: ${publicKey.length}`,
532
- "INVALID_KEY"
533
- );
534
- }
535
- /**
536
- * Encrypts data using ECIES.
537
- *
538
- * @param publicKey - The recipient's public key (compressed or uncompressed)
539
- * @param message - The data to encrypt
540
- * @returns Promise resolving to encrypted data structure
541
- */
542
- async encrypt(publicKey, message) {
543
- try {
544
- if (!(publicKey instanceof Uint8Array)) {
545
- throw new ECIESError("Public key must be a Uint8Array", "INVALID_KEY");
546
- }
547
- if (!(message instanceof Uint8Array)) {
548
- throw new ECIESError(
549
- "Message must be a Uint8Array",
550
- "ENCRYPTION_FAILED"
551
- );
552
- }
553
- if (publicKey.length === 0) {
554
- throw new ECIESError("Public key cannot be empty", "INVALID_KEY");
555
- }
556
- const pubKey = this.normalizePublicKey(publicKey);
557
- let ephemeralPrivateKey;
558
- do {
559
- ephemeralPrivateKey = this.generateRandomBytes(
560
- CURVE.PRIVATE_KEY_LENGTH
561
- );
562
- } while (!this.verifyPrivateKey(ephemeralPrivateKey));
563
- const ephemeralPublicKey = this.createPublicKey(
564
- ephemeralPrivateKey,
565
- false
566
- );
567
- if (!ephemeralPublicKey) {
568
- throw new ECIESError(
569
- "Failed to generate ephemeral public key",
570
- "ENCRYPTION_FAILED"
571
- );
572
- }
573
- const sharedSecret = this.performECDH(pubKey, ephemeralPrivateKey);
574
- const kdf = this.sha512(sharedSecret);
575
- const encryptionKey = kdf.slice(
576
- KDF.ENCRYPTION_KEY_OFFSET,
577
- KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
578
- );
579
- const macKey = kdf.slice(
580
- KDF.MAC_KEY_OFFSET,
581
- KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
582
- );
583
- const iv = this.generateRandomBytes(CIPHER.IV_LENGTH);
584
- const ciphertext = await this.aesEncrypt(encryptionKey, iv, message);
585
- const macData = concatBytes2(iv, ephemeralPublicKey, ciphertext);
586
- const mac = this.hmacSha256(macKey, macData);
587
- this.clearBuffer(ephemeralPrivateKey);
588
- this.clearBuffer(sharedSecret);
589
- this.clearBuffer(kdf);
590
- return {
591
- iv,
592
- ephemPublicKey: ephemeralPublicKey,
593
- ciphertext,
594
- mac
595
- };
596
- } catch (error) {
597
- if (error instanceof ECIESError) throw error;
598
- throw new ECIESError(
599
- `Encryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
600
- "ENCRYPTION_FAILED",
601
- error instanceof Error ? error : void 0
602
- );
603
- }
604
- }
605
- /**
606
- * Decrypts ECIES encrypted data.
607
- *
608
- * @param privateKey - The recipient's private key (32 bytes)
609
- * @param encrypted - The encrypted data structure from encrypt()
610
- * @returns Promise resolving to the original plaintext
611
- */
612
- async decrypt(privateKey, encrypted) {
613
- try {
614
- if (!(privateKey instanceof Uint8Array)) {
615
- throw new ECIESError("Private key must be a Uint8Array", "INVALID_KEY");
616
- }
617
- if (!isECIESEncrypted(encrypted)) {
618
- throw new ECIESError(
619
- "Invalid encrypted data structure",
620
- "DECRYPTION_FAILED"
621
- );
622
- }
623
- if (privateKey.length !== CURVE.PRIVATE_KEY_LENGTH) {
624
- throw new ECIESError(
625
- `Invalid private key length: ${privateKey.length}`,
626
- "INVALID_KEY"
627
- );
628
- }
629
- if (!this.verifyPrivateKey(privateKey)) {
630
- throw new ECIESError("Invalid private key", "INVALID_KEY");
631
- }
632
- const ephemeralPublicKey = this.normalizePublicKey(
633
- encrypted.ephemPublicKey
634
- );
635
- const sharedSecret = this.performECDH(ephemeralPublicKey, privateKey);
636
- const kdf = this.sha512(sharedSecret);
637
- const encryptionKey = kdf.slice(
638
- KDF.ENCRYPTION_KEY_OFFSET,
639
- KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
640
- );
641
- const macKey = kdf.slice(
642
- KDF.MAC_KEY_OFFSET,
643
- KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
644
- );
645
- const macData = concatBytes2(
646
- encrypted.iv,
647
- encrypted.ephemPublicKey,
648
- encrypted.ciphertext
649
- );
650
- const expectedMac = this.hmacSha256(macKey, macData);
651
- if (!constantTimeEqual(encrypted.mac, expectedMac)) {
652
- throw new ECIESError("MAC verification failed", "MAC_MISMATCH");
653
- }
654
- const decrypted = await this.aesDecrypt(
655
- encryptionKey,
656
- encrypted.iv,
657
- encrypted.ciphertext
658
- );
659
- this.clearBuffer(sharedSecret);
660
- this.clearBuffer(kdf);
661
- return decrypted;
662
- } catch (error) {
663
- if (error instanceof ECIESError) throw error;
664
- throw new ECIESError(
665
- `Decryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
666
- "DECRYPTION_FAILED",
667
- error instanceof Error ? error : void 0
668
- );
669
- }
670
- }
671
- /**
672
- * Clears sensitive data from memory using multi-pass overwrite.
673
- *
674
- * @remarks
675
- * Uses multiple passes with different patterns to make it harder
676
- * for JIT compilers to optimize away the operation. While not
677
- * guaranteed in JavaScript, this is a best-effort approach to
678
- * clear sensitive data from memory.
679
- *
680
- * @param buffer - The buffer to clear
681
- */
682
- clearBuffer(buffer) {
683
- if (buffer && buffer.length > 0) {
684
- buffer.fill(0);
685
- buffer.fill(255);
686
- buffer.fill(170);
687
- buffer.fill(0);
688
- for (let i = 0; i < buffer.length; i++) {
689
- buffer[i] = i & 255 ^ 90;
690
- }
691
- buffer.fill(0);
692
- }
693
- }
694
- };
695
- }
696
- });
697
-
698
119
  // src/schemas/dataSchema.schema.json
699
120
  var dataSchema_schema_default;
700
121
  var init_dataSchema_schema = __esm({
@@ -758,8 +179,10 @@ var init_dataSchema_schema = __esm({
758
179
  // src/utils/schemaValidation.ts
759
180
  import Ajv from "ajv";
760
181
  import addFormats from "ajv-formats";
761
- function validateDataSchema(schema) {
762
- return schemaValidator.validateDataSchema(schema);
182
+ function validateDataSchemaAgainstMetaSchema(schema) {
183
+ const validator = schemaValidator;
184
+ validator.validateDataSchemaAgainstMetaSchema(schema);
185
+ return schema;
763
186
  }
764
187
  function validateDataAgainstSchema(data, schema) {
765
188
  return schemaValidator.validateDataAgainstSchema(data, schema);
@@ -792,9 +215,9 @@ var init_schemaValidation = __esm({
792
215
  this.dataSchemaValidator = this.ajv.compile(dataSchema_schema_default);
793
216
  }
794
217
  /**
795
- * Validates a data schema against the Vana meta-schema
218
+ * Validates a data schema definition against the Vana meta-schema
796
219
  *
797
- * @param schema - The data schema to validate
220
+ * @param schema - The data schema definition to validate
798
221
  * @throws SchemaValidationError if invalid
799
222
  * @example
800
223
  * ```typescript
@@ -813,10 +236,10 @@ var init_schemaValidation = __esm({
813
236
  * }
814
237
  * };
815
238
  *
816
- * validator.validateDataSchema(schema); // throws if invalid
239
+ * validator.validateDataSchemaAgainstMetaSchema(schema); // throws if invalid
817
240
  * ```
818
241
  */
819
- validateDataSchema(schema) {
242
+ validateDataSchemaAgainstMetaSchema(schema) {
820
243
  const isValid = this.dataSchemaValidator(schema);
821
244
  if (!isValid) {
822
245
  const errors = this.dataSchemaValidator.errors || [];
@@ -836,10 +259,10 @@ var init_schemaValidation = __esm({
836
259
  }
837
260
  }
838
261
  /**
839
- * Validates data against a JSON Schema from a schema
262
+ * Validates data against a JSON Schema
840
263
  *
841
264
  * @param data - The data to validate
842
- * @param schema - The schema containing the validation rules (DataSchema or Schema)
265
+ * @param schema - The schema containing the validation rules (must have been validated or fetched from chain)
843
266
  * @throws SchemaValidationError if invalid
844
267
  * @example
845
268
  * ```typescript
@@ -849,25 +272,22 @@ var init_schemaValidation = __esm({
849
272
  * const schema = await vana.schemas.get(1);
850
273
  * validator.validateDataAgainstSchema(userData, schema);
851
274
  *
852
- * // Also works with DataSchema object
853
- * const dataSchema: DataSchema = {
275
+ * // Also works with pre-validated DataSchema object
276
+ * const dataSchema = validator.validateDataSchemaAgainstMetaSchema({
854
277
  * name: "User Profile",
855
278
  * version: "1.0.0",
856
279
  * dialect: "json",
857
280
  * schema: { type: "object", properties: { name: { type: "string" } } }
858
- * };
281
+ * });
859
282
  * validator.validateDataAgainstSchema(userData, dataSchema);
860
283
  * ```
861
284
  */
862
285
  validateDataAgainstSchema(data, schema) {
863
- if (!("id" in schema)) {
864
- this.validateDataSchema(schema);
865
- }
866
286
  if (schema.dialect !== "json") {
867
- throw new SchemaValidationError(
868
- `Data validation only supported for JSON dialect, got: ${schema.dialect}`,
869
- []
287
+ console.warn(
288
+ `[SchemaValidator] Data validation skipped: dialect '${schema.dialect}' does not support data validation. Only JSON schemas can validate data structure.`
870
289
  );
290
+ return;
871
291
  }
872
292
  if (typeof schema.schema !== "object") {
873
293
  throw new SchemaValidationError(
@@ -933,9 +353,9 @@ var init_schemaValidation = __esm({
933
353
  }
934
354
  }
935
355
  /**
936
- * Fetches and validates a schema from a URL
356
+ * Fetches and validates a data schema from a URL
937
357
  *
938
- * @param url - The URL to fetch the schema from
358
+ * @param url - The URL to fetch the data schema from
939
359
  * @returns The validated data schema
940
360
  * @throws SchemaValidationError if invalid or fetch fails
941
361
  * @example
@@ -951,7 +371,7 @@ var init_schemaValidation = __esm({
951
371
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
952
372
  }
953
373
  const schema = await response.json();
954
- this.validateDataSchema(schema);
374
+ this.validateDataSchemaAgainstMetaSchema(schema);
955
375
  if (schema.dialect === "sqlite" && typeof schema.schema === "string") {
956
376
  this.validateSQLiteDDL(schema.schema, schema.dialectVersion);
957
377
  }
@@ -1600,19 +1020,19 @@ var init_eventMappings = __esm({
1600
1020
  // DataRegistry operations
1601
1021
  addFile: {
1602
1022
  contract: "DataRegistry",
1603
- event: "FileAdded"
1023
+ event: "FileAddedV2"
1604
1024
  },
1605
1025
  addFileWithPermissionsAndSchema: {
1606
1026
  contract: "DataRegistry",
1607
- event: "FileAdded"
1027
+ event: "FileAddedV2"
1608
1028
  },
1609
1029
  addFileWithSchema: {
1610
1030
  contract: "DataRegistry",
1611
- event: "FileAdded"
1031
+ event: "FileAddedV2"
1612
1032
  },
1613
1033
  addFileWithPermissions: {
1614
1034
  contract: "DataRegistry",
1615
- event: "FileAdded"
1035
+ event: "FileAddedV2"
1616
1036
  },
1617
1037
  addRefinement: {
1618
1038
  contract: "DataRegistry",
@@ -3099,6 +2519,37 @@ var init_DataRegistryImplementation = __esm({
3099
2519
  name: "FileAdded",
3100
2520
  type: "event"
3101
2521
  },
2522
+ {
2523
+ anonymous: false,
2524
+ inputs: [
2525
+ {
2526
+ indexed: true,
2527
+ internalType: "uint256",
2528
+ name: "fileId",
2529
+ type: "uint256"
2530
+ },
2531
+ {
2532
+ indexed: true,
2533
+ internalType: "address",
2534
+ name: "ownerAddress",
2535
+ type: "address"
2536
+ },
2537
+ {
2538
+ indexed: false,
2539
+ internalType: "string",
2540
+ name: "url",
2541
+ type: "string"
2542
+ },
2543
+ {
2544
+ indexed: false,
2545
+ internalType: "uint256",
2546
+ name: "schemaId",
2547
+ type: "uint256"
2548
+ }
2549
+ ],
2550
+ name: "FileAddedV2",
2551
+ type: "event"
2552
+ },
3102
2553
  {
3103
2554
  anonymous: false,
3104
2555
  inputs: [
@@ -3646,6 +3097,19 @@ var init_DataRegistryImplementation = __esm({
3646
3097
  stateMutability: "view",
3647
3098
  type: "function"
3648
3099
  },
3100
+ {
3101
+ inputs: [],
3102
+ name: "emitLegacyEvents",
3103
+ outputs: [
3104
+ {
3105
+ internalType: "bool",
3106
+ name: "",
3107
+ type: "bool"
3108
+ }
3109
+ ],
3110
+ stateMutability: "view",
3111
+ type: "function"
3112
+ },
3649
3113
  {
3650
3114
  inputs: [
3651
3115
  {
@@ -3803,6 +3267,11 @@ var init_DataRegistryImplementation = __esm({
3803
3267
  name: "url",
3804
3268
  type: "string"
3805
3269
  },
3270
+ {
3271
+ internalType: "uint256",
3272
+ name: "schemaId",
3273
+ type: "uint256"
3274
+ },
3806
3275
  {
3807
3276
  internalType: "uint256",
3808
3277
  name: "addedAtBlock",
@@ -4086,6 +3555,19 @@ var init_DataRegistryImplementation = __esm({
4086
3555
  stateMutability: "nonpayable",
4087
3556
  type: "function"
4088
3557
  },
3558
+ {
3559
+ inputs: [
3560
+ {
3561
+ internalType: "bool",
3562
+ name: "newEmitLegacyEvents",
3563
+ type: "bool"
3564
+ }
3565
+ ],
3566
+ name: "updateEmitLegacyEvents",
3567
+ outputs: [],
3568
+ stateMutability: "nonpayable",
3569
+ type: "function"
3570
+ },
4089
3571
  {
4090
3572
  inputs: [
4091
3573
  {
@@ -36891,7 +36373,7 @@ var init_schemas = __esm({
36891
36373
  dialect,
36892
36374
  schema: schemaDefinition
36893
36375
  };
36894
- validateDataSchema(dataSchema);
36376
+ validateDataSchemaAgainstMetaSchema(dataSchema);
36895
36377
  if (!this.context.storageManager) {
36896
36378
  if (this.context.validateStorageRequired) {
36897
36379
  this.context.validateStorageRequired();
@@ -37000,7 +36482,7 @@ var init_schemas = __esm({
37000
36482
  `Invalid schema definition format for schema ${schemaId}`
37001
36483
  );
37002
36484
  }
37003
- validateDataSchema(definition);
36485
+ validateDataSchemaAgainstMetaSchema(definition);
37004
36486
  const dataSchema = definition;
37005
36487
  if (dataSchema.name !== metadata.name) {
37006
36488
  throw new Error(
@@ -37335,7 +36817,7 @@ var init_schemas = __esm({
37335
36817
  try {
37336
36818
  const definition = await fetchFromUrl(schema.definitionUrl);
37337
36819
  if (definition && typeof definition === "object") {
37338
- validateDataSchema(definition);
36820
+ validateDataSchemaAgainstMetaSchema(definition);
37339
36821
  const dataSchema = definition;
37340
36822
  schema.version = dataSchema.version;
37341
36823
  schema.description = dataSchema.description;
@@ -37354,204 +36836,123 @@ var init_schemas = __esm({
37354
36836
  }
37355
36837
  });
37356
36838
 
37357
- // src/crypto/ecies/browser.ts
37358
- import * as secp256k12 from "@noble/secp256k1";
37359
- import { hmac } from "@noble/hashes/hmac";
37360
- import { sha256 as sha2562, sha512 as nobleSha512 } from "@noble/hashes/sha2";
37361
- var BrowserECIESUint8Provider;
37362
- var init_browser = __esm({
37363
- "src/crypto/ecies/browser.ts"() {
37364
- "use strict";
37365
- init_base();
37366
- BrowserECIESUint8Provider = class extends BaseECIESUint8 {
37367
- generateRandomBytes(length) {
37368
- const bytes = new Uint8Array(length);
37369
- crypto.getRandomValues(bytes);
37370
- return bytes;
37371
- }
37372
- verifyPrivateKey(privateKey) {
37373
- try {
37374
- return secp256k12.utils.isValidPrivateKey(privateKey);
37375
- } catch {
37376
- return false;
37377
- }
37378
- }
37379
- createPublicKey(privateKey, compressed) {
37380
- try {
37381
- return secp256k12.getPublicKey(privateKey, compressed);
37382
- } catch {
37383
- return null;
37384
- }
37385
- }
37386
- validatePublicKey(publicKey) {
37387
- try {
37388
- secp256k12.Point.fromHex(publicKey);
37389
- return true;
37390
- } catch {
37391
- return false;
37392
- }
37393
- }
37394
- decompressPublicKey(publicKey) {
37395
- try {
37396
- const point = secp256k12.Point.fromHex(publicKey);
37397
- return point.toRawBytes(false);
37398
- } catch {
37399
- return null;
37400
- }
37401
- }
37402
- performECDH(publicKey, privateKey) {
37403
- try {
37404
- const sharedPoint = secp256k12.getSharedSecret(
37405
- privateKey,
37406
- publicKey,
37407
- true
37408
- );
37409
- return sharedPoint.slice(1);
37410
- } catch (error) {
37411
- throw new Error(
37412
- `ECDH failed: ${error instanceof Error ? error.message : "Unknown error"}`
37413
- );
37414
- }
37415
- }
37416
- sha512(data) {
37417
- return nobleSha512(data);
37418
- }
37419
- hmacSha256(key, data) {
37420
- return hmac(sha2562, key, data);
37421
- }
37422
- async aesEncrypt(key, iv, plaintext) {
37423
- const cryptoKey = await crypto.subtle.importKey(
37424
- "raw",
37425
- key,
37426
- { name: "AES-CBC" },
37427
- false,
37428
- ["encrypt"]
37429
- );
37430
- const encrypted = await crypto.subtle.encrypt(
37431
- { name: "AES-CBC", iv },
37432
- cryptoKey,
37433
- plaintext
37434
- );
37435
- return new Uint8Array(encrypted);
37436
- }
37437
- async aesDecrypt(key, iv, ciphertext) {
37438
- const cryptoKey = await crypto.subtle.importKey(
37439
- "raw",
37440
- key,
37441
- { name: "AES-CBC" },
37442
- false,
37443
- ["decrypt"]
37444
- );
37445
- const decrypted = await crypto.subtle.decrypt(
37446
- { name: "AES-CBC", iv },
37447
- cryptoKey,
37448
- ciphertext
37449
- );
37450
- return new Uint8Array(decrypted);
37451
- }
37452
- };
37453
- }
37454
- });
37455
-
37456
36839
  // src/platform/browser.ts
37457
36840
  var browser_exports = {};
37458
36841
  __export(browser_exports, {
37459
- BrowserPlatformAdapter: () => BrowserPlatformAdapter
36842
+ BrowserPlatformAdapter: () => BrowserPlatformAdapter,
36843
+ browserPlatformAdapter: () => browserPlatformAdapter
37460
36844
  });
37461
- import * as secp256k13 from "@noble/secp256k1";
37462
- var getOpenPGP2, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter;
37463
- var init_browser2 = __esm({
36845
+ var getOpenPGP2, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter, browserPlatformAdapter;
36846
+ var init_browser = __esm({
37464
36847
  "src/platform/browser.ts"() {
37465
36848
  "use strict";
36849
+ init_crypto_utils();
37466
36850
  init_pgp_utils();
37467
36851
  init_error_utils();
37468
36852
  init_lazy_import();
37469
- init_WalletKeyEncryptionService();
37470
- init_crypto_utils();
37471
- init_utils();
37472
- init_browser();
37473
36853
  getOpenPGP2 = lazyImport(() => import("openpgp"));
37474
36854
  BrowserCryptoAdapter = class {
37475
- eciesProvider = new BrowserECIESUint8Provider();
37476
- walletKeyEncryptionService = new WalletKeyEncryptionService({
37477
- eciesProvider: this.eciesProvider
37478
- });
37479
36855
  async encryptWithPublicKey(data, publicKeyHex) {
37480
36856
  try {
37481
- const publicKeyBytes = hexToBytes2(publicKeyHex);
37482
- const encrypted = await this.eciesProvider.encrypt(
37483
- publicKeyBytes,
37484
- stringToBytes2(data)
36857
+ const eccrypto = await import("eccrypto-js");
36858
+ const publicKeyBuffer = Buffer.from(publicKeyHex, "hex");
36859
+ const encrypted = await eccrypto.encrypt(
36860
+ publicKeyBuffer,
36861
+ Buffer.from(data, "utf8")
37485
36862
  );
37486
- const result = concatBytes2(
36863
+ const result = Buffer.concat([
37487
36864
  encrypted.iv,
37488
36865
  encrypted.ephemPublicKey,
37489
36866
  encrypted.ciphertext,
37490
36867
  encrypted.mac
37491
- );
37492
- return bytesToHex2(result);
36868
+ ]);
36869
+ return result.toString("hex");
37493
36870
  } catch (error) {
37494
- throw wrapCryptoError("encryptWithPublicKey", error);
36871
+ throw new Error(`Encryption failed: ${error}`);
37495
36872
  }
37496
36873
  }
37497
36874
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
37498
36875
  try {
37499
- const encryptedBytes = hexToBytes2(encryptedData);
37500
- const privateKeyBytes = hexToBytes2(privateKeyHex);
37501
- const encrypted = parseEncryptedDataBuffer(encryptedBytes);
37502
- const decrypted = await this.eciesProvider.decrypt(
37503
- privateKeyBytes,
37504
- encrypted
36876
+ const eccrypto = await import("eccrypto-js");
36877
+ const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
36878
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
36879
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
36880
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
36881
+ const decryptedBuffer = await eccrypto.decrypt(
36882
+ privateKeyBuffer,
36883
+ encryptedObj
37505
36884
  );
37506
- return bytesToString2(decrypted);
36885
+ return decryptedBuffer.toString("utf8");
37507
36886
  } catch (error) {
37508
- throw wrapCryptoError("decryptWithPrivateKey", error);
36887
+ throw new Error(`Decryption failed: ${error}`);
37509
36888
  }
37510
36889
  }
37511
- async encryptWithWalletPublicKey(data, publicKey) {
36890
+ async generateKeyPair() {
37512
36891
  try {
37513
- return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
37514
- data,
37515
- publicKey
37516
- );
36892
+ const eccrypto = await import("eccrypto-js");
36893
+ const privateKeyBytes = new Uint8Array(32);
36894
+ crypto.getRandomValues(privateKeyBytes);
36895
+ const privateKey = Buffer.from(privateKeyBytes);
36896
+ const publicKey = eccrypto.getPublicCompressed(privateKey);
36897
+ return {
36898
+ privateKey: privateKey.toString("hex"),
36899
+ publicKey: publicKey.toString("hex")
36900
+ };
37517
36901
  } catch (error) {
37518
- throw wrapCryptoError("encryptWithWalletPublicKey", error);
36902
+ throw wrapCryptoError("key generation", error);
37519
36903
  }
37520
36904
  }
37521
- async decryptWithWalletPrivateKey(encryptedData, privateKey) {
36905
+ async encryptWithWalletPublicKey(data, publicKey) {
37522
36906
  try {
37523
- return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
37524
- encryptedData,
37525
- privateKey
36907
+ const eccrypto = await import("eccrypto-js");
36908
+ const uncompressedKey = processWalletPublicKey(publicKey);
36909
+ const encryptedBuffer = await eccrypto.encrypt(
36910
+ uncompressedKey,
36911
+ Buffer.from(data)
37526
36912
  );
36913
+ const result = Buffer.concat([
36914
+ encryptedBuffer.iv,
36915
+ encryptedBuffer.ephemPublicKey,
36916
+ encryptedBuffer.ciphertext,
36917
+ encryptedBuffer.mac
36918
+ ]);
36919
+ return result.toString("hex");
37527
36920
  } catch (error) {
37528
- throw wrapCryptoError("decryptWithWalletPrivateKey", error);
36921
+ throw wrapCryptoError("encrypt with wallet public key", error);
37529
36922
  }
37530
36923
  }
37531
- async generateKeyPair() {
36924
+ async decryptWithWalletPrivateKey(encryptedData, privateKey) {
37532
36925
  try {
37533
- const privateKeyBytes = secp256k13.utils.randomPrivateKey();
37534
- const publicKeyBytes = secp256k13.getPublicKey(privateKeyBytes, true);
37535
- return {
37536
- privateKey: bytesToHex2(privateKeyBytes),
37537
- publicKey: bytesToHex2(publicKeyBytes)
37538
- };
36926
+ const eccrypto = await import("eccrypto-js");
36927
+ const privateKeyBuffer = processWalletPrivateKey(privateKey);
36928
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
36929
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
36930
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
36931
+ const decryptedBuffer = await eccrypto.decrypt(
36932
+ privateKeyBuffer,
36933
+ encryptedObj
36934
+ );
36935
+ return decryptedBuffer.toString("utf8");
37539
36936
  } catch (error) {
37540
- throw wrapCryptoError("generateKeyPair", error);
36937
+ throw wrapCryptoError("decrypt with wallet private key", error);
37541
36938
  }
37542
36939
  }
37543
36940
  async encryptWithPassword(data, password) {
37544
36941
  try {
37545
36942
  const openpgp = await getOpenPGP2();
37546
- const message = await openpgp.createMessage({ binary: data });
36943
+ const message = await openpgp.createMessage({
36944
+ binary: data
36945
+ });
37547
36946
  const encrypted = await openpgp.encrypt({
37548
36947
  message,
37549
36948
  passwords: [password],
37550
36949
  format: "binary"
37551
36950
  });
37552
- return new Uint8Array(encrypted);
36951
+ const response = new Response(encrypted);
36952
+ const arrayBuffer = await response.arrayBuffer();
36953
+ return new Uint8Array(arrayBuffer);
37553
36954
  } catch (error) {
37554
- throw wrapCryptoError("encryptWithPassword", error);
36955
+ throw new Error(`Failed to encrypt with password: ${error}`);
37555
36956
  }
37556
36957
  }
37557
36958
  async decryptWithPassword(encryptedData, password) {
@@ -37560,14 +36961,14 @@ var init_browser2 = __esm({
37560
36961
  const message = await openpgp.readMessage({
37561
36962
  binaryMessage: encryptedData
37562
36963
  });
37563
- const { data } = await openpgp.decrypt({
36964
+ const { data: decrypted } = await openpgp.decrypt({
37564
36965
  message,
37565
36966
  passwords: [password],
37566
36967
  format: "binary"
37567
36968
  });
37568
- return new Uint8Array(data);
36969
+ return new Uint8Array(decrypted);
37569
36970
  } catch (error) {
37570
- throw wrapCryptoError("decryptWithPassword", error);
36971
+ throw new Error(`Failed to decrypt with password: ${error}`);
37571
36972
  }
37572
36973
  }
37573
36974
  };
@@ -37619,6 +37020,9 @@ var init_browser2 = __esm({
37619
37020
  };
37620
37021
  BrowserHttpAdapter = class {
37621
37022
  async fetch(url, options) {
37023
+ if (typeof fetch === "undefined") {
37024
+ throw new Error("Fetch API not available in this browser environment");
37025
+ }
37622
37026
  return fetch(url, options);
37623
37027
  }
37624
37028
  };
@@ -37636,19 +37040,17 @@ var init_browser2 = __esm({
37636
37040
  }
37637
37041
  set(key, value) {
37638
37042
  try {
37639
- if (typeof sessionStorage === "undefined") {
37640
- return;
37043
+ if (typeof sessionStorage !== "undefined") {
37044
+ sessionStorage.setItem(this.prefix + key, value);
37641
37045
  }
37642
- sessionStorage.setItem(this.prefix + key, value);
37643
37046
  } catch {
37644
37047
  }
37645
37048
  }
37646
37049
  delete(key) {
37647
37050
  try {
37648
- if (typeof sessionStorage === "undefined") {
37649
- return;
37051
+ if (typeof sessionStorage !== "undefined") {
37052
+ sessionStorage.removeItem(this.prefix + key);
37650
37053
  }
37651
- sessionStorage.removeItem(this.prefix + key);
37652
37054
  } catch {
37653
37055
  }
37654
37056
  }
@@ -37657,29 +37059,35 @@ var init_browser2 = __esm({
37657
37059
  if (typeof sessionStorage === "undefined") {
37658
37060
  return;
37659
37061
  }
37660
- const keysToRemove = [];
37661
- for (let i = 0; i < sessionStorage.length; i++) {
37662
- const key = sessionStorage.key(i);
37663
- if (key?.startsWith(this.prefix)) {
37664
- keysToRemove.push(key);
37062
+ const keys = Object.keys(sessionStorage);
37063
+ for (const key of keys) {
37064
+ if (key.startsWith(this.prefix)) {
37065
+ sessionStorage.removeItem(key);
37665
37066
  }
37666
37067
  }
37667
- keysToRemove.forEach((key) => sessionStorage.removeItem(key));
37668
37068
  } catch {
37669
37069
  }
37670
37070
  }
37671
37071
  };
37672
37072
  BrowserPlatformAdapter = class {
37673
- crypto = new BrowserCryptoAdapter();
37674
- pgp = new BrowserPGPAdapter();
37675
- http = new BrowserHttpAdapter();
37676
- cache = new BrowserCacheAdapter();
37073
+ crypto;
37074
+ pgp;
37075
+ http;
37076
+ cache;
37677
37077
  platform = "browser";
37078
+ constructor() {
37079
+ this.crypto = new BrowserCryptoAdapter();
37080
+ this.pgp = new BrowserPGPAdapter();
37081
+ this.http = new BrowserHttpAdapter();
37082
+ this.cache = new BrowserCacheAdapter();
37083
+ }
37678
37084
  };
37085
+ browserPlatformAdapter = new BrowserPlatformAdapter();
37679
37086
  }
37680
37087
  });
37681
37088
 
37682
37089
  // src/platform/node.ts
37090
+ init_crypto_utils();
37683
37091
  init_pgp_utils();
37684
37092
  init_error_utils();
37685
37093
 
@@ -37708,129 +37116,15 @@ async function streamToUint8Array(stream) {
37708
37116
 
37709
37117
  // src/platform/node.ts
37710
37118
  init_lazy_import();
37711
- init_WalletKeyEncryptionService();
37712
- init_crypto_utils();
37713
-
37714
- // src/crypto/ecies/node.ts
37715
- init_base();
37716
- import {
37717
- randomBytes,
37718
- createHash,
37719
- createHmac,
37720
- createCipheriv,
37721
- createDecipheriv
37722
- } from "crypto";
37723
- var secp256k1;
37724
- try {
37725
- secp256k1 = __require("secp256k1");
37726
- } catch {
37727
- throw new Error(
37728
- "Native secp256k1 module not found. Please install with: npm install secp256k1\nThis is required for optimal performance in Node.js environments."
37729
- );
37730
- }
37731
- var NodeECIESUint8Provider = class extends BaseECIESUint8 {
37732
- // Identity hash function for ECDH - returns raw X coordinate
37733
- // CRITICAL: Must handle (x, y, output) signature correctly
37734
- identityHashFn = (x, y, output) => {
37735
- if (output && output.length >= 32) {
37736
- output.set(x);
37737
- return output;
37738
- }
37739
- return x;
37740
- };
37741
- generateRandomBytes(length) {
37742
- return new Uint8Array(randomBytes(length));
37743
- }
37744
- verifyPrivateKey(privateKey) {
37745
- return secp256k1.privateKeyVerify(Buffer.from(privateKey)) === true;
37746
- }
37747
- createPublicKey(privateKey, compressed) {
37748
- try {
37749
- return new Uint8Array(
37750
- secp256k1.publicKeyCreate(Buffer.from(privateKey), compressed)
37751
- );
37752
- } catch {
37753
- return null;
37754
- }
37755
- }
37756
- validatePublicKey(publicKey) {
37757
- return secp256k1.publicKeyVerify(Buffer.from(publicKey)) === true;
37758
- }
37759
- decompressPublicKey(publicKey) {
37760
- try {
37761
- return new Uint8Array(
37762
- secp256k1.publicKeyConvert(Buffer.from(publicKey), false)
37763
- );
37764
- } catch {
37765
- return null;
37766
- }
37767
- }
37768
- performECDH(publicKey, privateKey) {
37769
- try {
37770
- const output = Buffer.alloc(32);
37771
- secp256k1.ecdh(
37772
- Buffer.from(publicKey),
37773
- Buffer.from(privateKey),
37774
- { hashfn: this.identityHashFn },
37775
- output
37776
- );
37777
- return new Uint8Array(output);
37778
- } catch (error) {
37779
- throw new Error(
37780
- `ECDH failed: ${error instanceof Error ? error.message : "Unknown error"}`
37781
- );
37782
- }
37783
- }
37784
- sha512(data) {
37785
- return new Uint8Array(
37786
- createHash("sha512").update(Buffer.from(data)).digest()
37787
- );
37788
- }
37789
- hmacSha256(key, data) {
37790
- return new Uint8Array(
37791
- createHmac("sha256", Buffer.from(key)).update(Buffer.from(data)).digest()
37792
- );
37793
- }
37794
- async aesEncrypt(key, iv, plaintext) {
37795
- const cipher = createCipheriv(
37796
- "aes-256-cbc",
37797
- Buffer.from(key),
37798
- Buffer.from(iv)
37799
- );
37800
- const encrypted = Buffer.concat([
37801
- cipher.update(Buffer.from(plaintext)),
37802
- cipher.final()
37803
- ]);
37804
- return new Uint8Array(encrypted);
37805
- }
37806
- async aesDecrypt(key, iv, ciphertext) {
37807
- const decipher = createDecipheriv(
37808
- "aes-256-cbc",
37809
- Buffer.from(key),
37810
- Buffer.from(iv)
37811
- );
37812
- const decrypted = Buffer.concat([
37813
- decipher.update(Buffer.from(ciphertext)),
37814
- decipher.final()
37815
- ]);
37816
- return new Uint8Array(decrypted);
37817
- }
37818
- // No Buffer compatibility methods - Uint8Array only public API
37819
- };
37820
-
37821
- // src/platform/node.ts
37822
- init_interface();
37823
37119
  var getOpenPGP = lazyImport(() => import("openpgp"));
37120
+ var getEccrypto = lazyImport(() => import("eccrypto"));
37824
37121
  var NodeCryptoAdapter = class {
37825
- eciesProvider = new NodeECIESUint8Provider();
37826
- walletKeyEncryptionService = new WalletKeyEncryptionService({
37827
- eciesProvider: this.eciesProvider
37828
- });
37829
37122
  async encryptWithPublicKey(data, publicKeyHex) {
37830
37123
  try {
37124
+ const eccrypto = await getEccrypto();
37831
37125
  const publicKey = Buffer.from(publicKeyHex, "hex");
37832
37126
  const message = Buffer.from(data, "utf8");
37833
- const encrypted = await this.eciesProvider.encrypt(publicKey, message);
37127
+ const encrypted = await eccrypto.encrypt(publicKey, message);
37834
37128
  const result = Buffer.concat([
37835
37129
  encrypted.iv,
37836
37130
  encrypted.ephemPublicKey,
@@ -37839,54 +37133,27 @@ var NodeCryptoAdapter = class {
37839
37133
  ]);
37840
37134
  return result.toString("hex");
37841
37135
  } catch (error) {
37842
- if (error instanceof ECIESError) {
37843
- throw error;
37844
- }
37845
- throw new ECIESError(
37846
- `Encryption failed: ${error instanceof Error ? error.message : String(error)}`,
37847
- "ENCRYPTION_FAILED",
37848
- error instanceof Error ? error : void 0
37849
- );
37136
+ throw new Error(`Encryption failed: ${error}`);
37850
37137
  }
37851
37138
  }
37852
37139
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
37853
37140
  try {
37141
+ const eccrypto = await getEccrypto();
37854
37142
  const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
37855
37143
  const encryptedBuffer = Buffer.from(encryptedData, "hex");
37856
37144
  const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
37857
- const encryptedObj = {
37858
- iv,
37859
- ephemPublicKey,
37860
- ciphertext,
37861
- mac
37862
- };
37863
- const decrypted = await this.eciesProvider.decrypt(
37864
- privateKeyBuffer,
37865
- encryptedObj
37866
- );
37867
- return new TextDecoder().decode(decrypted);
37145
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
37146
+ const decrypted = await eccrypto.decrypt(privateKeyBuffer, encryptedObj);
37147
+ return decrypted.toString("utf8");
37868
37148
  } catch (error) {
37869
- if (error instanceof ECIESError) {
37870
- throw error;
37871
- }
37872
- throw new ECIESError(
37873
- `Decryption failed: ${error instanceof Error ? error.message : String(error)}`,
37874
- "DECRYPTION_FAILED",
37875
- error instanceof Error ? error : void 0
37876
- );
37149
+ throw new Error(`Decryption failed: ${error}`);
37877
37150
  }
37878
37151
  }
37879
37152
  async generateKeyPair() {
37880
37153
  try {
37881
- const { randomBytes: randomBytes2 } = await import("crypto");
37882
- const secp256k14 = await import("secp256k1");
37883
- let privateKey;
37884
- do {
37885
- privateKey = randomBytes2(32);
37886
- } while (!secp256k14.privateKeyVerify(privateKey));
37887
- const publicKey = Buffer.from(
37888
- secp256k14.publicKeyCreate(privateKey, true)
37889
- );
37154
+ const eccrypto = await getEccrypto();
37155
+ const privateKey = eccrypto.generatePrivate();
37156
+ const publicKey = eccrypto.getPublicCompressed(privateKey);
37890
37157
  return {
37891
37158
  privateKey: privateKey.toString("hex"),
37892
37159
  publicKey: publicKey.toString("hex")
@@ -37897,20 +37164,35 @@ var NodeCryptoAdapter = class {
37897
37164
  }
37898
37165
  async encryptWithWalletPublicKey(data, publicKey) {
37899
37166
  try {
37900
- return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
37901
- data,
37902
- publicKey
37167
+ const eccrypto = await getEccrypto();
37168
+ const uncompressedKey = processWalletPublicKey(publicKey);
37169
+ const encrypted = await eccrypto.encrypt(
37170
+ uncompressedKey,
37171
+ Buffer.from(data)
37903
37172
  );
37173
+ const result = Buffer.concat([
37174
+ encrypted.iv,
37175
+ encrypted.ephemPublicKey,
37176
+ encrypted.ciphertext,
37177
+ encrypted.mac
37178
+ ]);
37179
+ return result.toString("hex");
37904
37180
  } catch (error) {
37905
37181
  throw wrapCryptoError("encrypt with wallet public key", error);
37906
37182
  }
37907
37183
  }
37908
37184
  async decryptWithWalletPrivateKey(encryptedData, privateKey) {
37909
37185
  try {
37910
- return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
37911
- encryptedData,
37912
- privateKey
37186
+ const eccrypto = await getEccrypto();
37187
+ const privateKeyBuffer = processWalletPrivateKey(privateKey);
37188
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
37189
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
37190
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
37191
+ const decryptedBuffer = await eccrypto.decrypt(
37192
+ privateKeyBuffer,
37193
+ encryptedObj
37913
37194
  );
37195
+ return decryptedBuffer.toString("utf8");
37914
37196
  } catch (error) {
37915
37197
  throw wrapCryptoError("decrypt with wallet private key", error);
37916
37198
  }
@@ -38082,6 +37364,9 @@ var StorageError = class extends Error {
38082
37364
  }
38083
37365
  };
38084
37366
 
37367
+ // src/types/index.ts
37368
+ init_schemaValidation();
37369
+
38085
37370
  // src/types/external-apis.ts
38086
37371
  function isReplicateAPIResponse(value) {
38087
37372
  if (typeof value !== "object" || value === null) return false;
@@ -38123,7 +37408,7 @@ init_abi();
38123
37408
 
38124
37409
  // src/utils/grantFiles.ts
38125
37410
  init_errors();
38126
- import { keccak256, toHex as toHex2 } from "viem";
37411
+ import { keccak256, toHex } from "viem";
38127
37412
  function createGrantFile(params) {
38128
37413
  const grantFile = {
38129
37414
  grantee: params.grantee,
@@ -38246,8 +37531,8 @@ function getGrantFileHash(grantFile) {
38246
37531
  sortedFile.expires = grantFile.expires;
38247
37532
  }
38248
37533
  const jsonString = JSON.stringify(sortedFile);
38249
- console.info(`Hash: ${keccak256(toHex2(jsonString))}`);
38250
- return keccak256(toHex2(jsonString));
37534
+ console.info(`Hash: ${keccak256(toHex(jsonString))}`);
37535
+ return keccak256(toHex(jsonString));
38251
37536
  } catch (error) {
38252
37537
  throw new SerializationError(
38253
37538
  `Failed to generate grant file hash: ${error instanceof Error ? error.message : "Unknown error"}`
@@ -38524,8 +37809,7 @@ function validateOperationAccess(grantFile, requestedOperation) {
38524
37809
  }
38525
37810
 
38526
37811
  // src/utils/signatureCache.ts
38527
- import { sha256 } from "@noble/hashes/sha256";
38528
- import { bytesToHex as bytesToHex3 } from "@noble/hashes/utils";
37812
+ init_crypto_utils();
38529
37813
  var SignatureCache = class {
38530
37814
  static PREFIX = "vana_sig_";
38531
37815
  static DEFAULT_TTL_HOURS = 2;
@@ -38624,12 +37908,12 @@ var SignatureCache = class {
38624
37908
  * Generate a deterministic hash of a message object for cache key generation
38625
37909
  *
38626
37910
  * @remarks
38627
- * Creates a cryptographically secure hash from complex objects including EIP-712 typed data.
38628
- * Uses SHA-256 for collision resistance and deterministic key generation.
38629
- * Handles BigInt serialization and sorts object keys for consistency.
37911
+ * Creates a consistent hash from complex objects including EIP-712 typed data.
37912
+ * Handles BigInt serialization and produces a 32-character hash that balances
37913
+ * uniqueness with key length constraints.
38630
37914
  *
38631
37915
  * @param message - The message object to hash (typically EIP-712 typed data)
38632
- * @returns A hex string hash (SHA-256) suitable for cache keys
37916
+ * @returns A 32-character hash string suitable for cache keys
38633
37917
  * @example
38634
37918
  * ```typescript
38635
37919
  * const typedData = {
@@ -38638,35 +37922,30 @@ var SignatureCache = class {
38638
37922
  * };
38639
37923
  *
38640
37924
  * const hash = SignatureCache.hashMessage(typedData);
38641
- * // Returns SHA-256 hash like: "a1b2c3d4e5f6..."
37925
+ * // Returns something like: "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"
38642
37926
  * ```
38643
37927
  */
38644
37928
  static hashMessage(message) {
38645
- const jsonString = JSON.stringify(message, this.deterministicReplacer);
38646
- const hashBytes = sha256(new TextEncoder().encode(jsonString));
38647
- return bytesToHex3(hashBytes);
37929
+ const jsonString = JSON.stringify(message, this.bigIntReplacer);
37930
+ const base64Hash = toBase64(jsonString);
37931
+ const cleaned = base64Hash.replace(/[^a-zA-Z0-9]/g, "");
37932
+ if (cleaned.length > 32) {
37933
+ return cleaned.substring(0, 16) + cleaned.substring(cleaned.length - 16);
37934
+ }
37935
+ return cleaned.substring(0, 32);
38648
37936
  }
38649
37937
  /**
38650
- * Deterministic JSON replacer that handles BigInt values and sorts object keys
38651
- * This ensures consistent cache key generation for EIP-712 typed data
37938
+ * Custom JSON replacer that converts BigInt values to strings for serialization
37939
+ * This ensures deterministic cache key generation for EIP-712 typed data
38652
37940
  *
38653
37941
  * @param _key - The object key being serialized (unused)
38654
37942
  * @param value - The value to serialize
38655
- * @returns The serialized value with sorted keys for objects
37943
+ * @returns The serialized value
38656
37944
  */
38657
- static deterministicReplacer(_key, value) {
37945
+ static bigIntReplacer(_key, value) {
38658
37946
  if (typeof value === "bigint") {
38659
37947
  return `__BIGINT__${value.toString()}`;
38660
37948
  }
38661
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
38662
- return Object.keys(value).sort().reduce(
38663
- (sorted, key) => {
38664
- sorted[key] = value[key];
38665
- return sorted;
38666
- },
38667
- {}
38668
- );
38669
- }
38670
37949
  return value;
38671
37950
  }
38672
37951
  };
@@ -42907,6 +42186,29 @@ var DataController = class {
42907
42186
  const userFiles = Array.from(fileMap.values()).sort(
42908
42187
  (a, b) => Number((b.addedAtTimestamp || 0n) - (a.addedAtTimestamp || 0n))
42909
42188
  );
42189
+ if (userFiles.length > 0) {
42190
+ try {
42191
+ const fileIds = userFiles.map((f) => f.id);
42192
+ let proofMap;
42193
+ try {
42194
+ proofMap = await this._fetchProofsFromSubgraph(fileIds, endpoint);
42195
+ } catch (subgraphError) {
42196
+ console.debug(
42197
+ "Failed to fetch proofs from subgraph, trying chain:",
42198
+ subgraphError
42199
+ );
42200
+ proofMap = await this._fetchProofsFromChain(fileIds);
42201
+ }
42202
+ for (const file of userFiles) {
42203
+ const dlpIds = proofMap.get(file.id);
42204
+ if (dlpIds && dlpIds.length > 0) {
42205
+ file.dlpIds = dlpIds;
42206
+ }
42207
+ }
42208
+ } catch (error) {
42209
+ console.warn("Failed to fetch proof data for files:", error);
42210
+ }
42211
+ }
42910
42212
  return userFiles;
42911
42213
  } catch (error) {
42912
42214
  console.error("Failed to fetch user files from subgraph:", error);
@@ -42915,6 +42217,349 @@ var DataController = class {
42915
42217
  );
42916
42218
  }
42917
42219
  }
42220
+ /**
42221
+ * Fetches proof data for multiple files from the subgraph.
42222
+ *
42223
+ * @private
42224
+ * @param fileIds - Array of file IDs to fetch proofs for
42225
+ * @param subgraphUrl - The subgraph endpoint URL
42226
+ * @returns Map of file IDs to their associated DLP IDs
42227
+ */
42228
+ async _fetchProofsFromSubgraph(fileIds, subgraphUrl) {
42229
+ const query = `
42230
+ query GetFileProofs($fileIds: [BigInt!]!) {
42231
+ dataRegistryProofs(where: { fileId_in: $fileIds }) {
42232
+ fileId
42233
+ dlp {
42234
+ id
42235
+ }
42236
+ }
42237
+ }
42238
+ `;
42239
+ const response = await fetch(subgraphUrl, {
42240
+ method: "POST",
42241
+ headers: {
42242
+ "Content-Type": "application/json"
42243
+ },
42244
+ body: JSON.stringify({
42245
+ query,
42246
+ variables: {
42247
+ fileIds: fileIds.map((id) => id.toString())
42248
+ }
42249
+ })
42250
+ });
42251
+ if (!response.ok) {
42252
+ throw new Error(
42253
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42254
+ );
42255
+ }
42256
+ const result = await response.json();
42257
+ if (result.errors) {
42258
+ throw new Error(
42259
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42260
+ );
42261
+ }
42262
+ const proofMap = /* @__PURE__ */ new Map();
42263
+ if (result.data?.dataRegistryProofs) {
42264
+ for (const proof of result.data.dataRegistryProofs) {
42265
+ if (proof.dlp?.id) {
42266
+ const fileId = parseInt(proof.fileId);
42267
+ const dlpId = parseInt(proof.dlp.id);
42268
+ if (!proofMap.has(fileId)) {
42269
+ proofMap.set(fileId, []);
42270
+ }
42271
+ const dlpIds = proofMap.get(fileId);
42272
+ if (!dlpIds.includes(dlpId)) {
42273
+ dlpIds.push(dlpId);
42274
+ }
42275
+ }
42276
+ }
42277
+ }
42278
+ return proofMap;
42279
+ }
42280
+ /**
42281
+ * Fetches proof data for multiple files from the blockchain.
42282
+ * Falls back to this when subgraph is unavailable.
42283
+ *
42284
+ * @private
42285
+ * @param fileIds - Array of file IDs to fetch proofs for
42286
+ * @returns Map of file IDs to their associated DLP IDs
42287
+ */
42288
+ async _fetchProofsFromChain(fileIds) {
42289
+ const chainId = this.context.walletClient.chain?.id;
42290
+ if (!chainId) {
42291
+ throw new Error("Chain ID not available");
42292
+ }
42293
+ const dataRegistryAddress = getContractAddress(chainId, "DataRegistry");
42294
+ const dataRegistryAbi = getAbi("DataRegistry");
42295
+ const proofMap = /* @__PURE__ */ new Map();
42296
+ for (const fileId of fileIds) {
42297
+ const dlpIds = [];
42298
+ let proofIndex = 0;
42299
+ let hasMoreProofs = true;
42300
+ while (hasMoreProofs) {
42301
+ try {
42302
+ const proof = await this.context.publicClient.readContract({
42303
+ address: dataRegistryAddress,
42304
+ abi: dataRegistryAbi,
42305
+ functionName: "fileProofs",
42306
+ args: [BigInt(fileId), BigInt(proofIndex)]
42307
+ });
42308
+ if (proof?.data?.dlpId) {
42309
+ const dlpId = Number(proof.data.dlpId);
42310
+ if (!dlpIds.includes(dlpId)) {
42311
+ dlpIds.push(dlpId);
42312
+ }
42313
+ }
42314
+ proofIndex++;
42315
+ } catch {
42316
+ hasMoreProofs = false;
42317
+ }
42318
+ }
42319
+ if (dlpIds.length > 0) {
42320
+ proofMap.set(fileId, dlpIds);
42321
+ }
42322
+ }
42323
+ return proofMap;
42324
+ }
42325
+ /**
42326
+ * Retrieves information about a specific Data Liquidity Pool (DLP).
42327
+ *
42328
+ * @remarks
42329
+ * DLPs are entities that process and verify data files in the Vana network.
42330
+ * This method fetches DLP metadata including name, status, and performance rating.
42331
+ * Uses subgraph first for efficiency, falls back to chain if unavailable.
42332
+ *
42333
+ * @param dlpId - The unique identifier of the DLP
42334
+ * @param options - Optional parameters
42335
+ * @param options.subgraphUrl - Custom subgraph URL to override default
42336
+ * @returns Promise resolving to DLP information
42337
+ * @throws {Error} When DLP cannot be found - "DLP not found: {dlpId}"
42338
+ * @throws {Error} When query fails - "Failed to fetch DLP: {error}"
42339
+ * @example
42340
+ * ```typescript
42341
+ * const dlp = await vana.data.getDLP(26);
42342
+ * console.log(`DLP ${dlp.name}: ${dlp.status}`);
42343
+ * ```
42344
+ */
42345
+ async getDLP(dlpId, options = {}) {
42346
+ const subgraphUrl = options.subgraphUrl || this.context.subgraphUrl;
42347
+ if (subgraphUrl) {
42348
+ try {
42349
+ const query = `
42350
+ query GetDLP($id: ID!) {
42351
+ dlp(id: $id) {
42352
+ id
42353
+ name
42354
+ metadata
42355
+ status
42356
+ address
42357
+ owner
42358
+ }
42359
+ }
42360
+ `;
42361
+ const response = await fetch(subgraphUrl, {
42362
+ method: "POST",
42363
+ headers: {
42364
+ "Content-Type": "application/json"
42365
+ },
42366
+ body: JSON.stringify({
42367
+ query,
42368
+ variables: {
42369
+ id: dlpId.toString()
42370
+ }
42371
+ })
42372
+ });
42373
+ if (!response.ok) {
42374
+ throw new Error(
42375
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42376
+ );
42377
+ }
42378
+ const result = await response.json();
42379
+ if (result.errors) {
42380
+ throw new Error(
42381
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42382
+ );
42383
+ }
42384
+ if (!result.data?.dlp) {
42385
+ throw new Error(`DLP not found: ${dlpId}`);
42386
+ }
42387
+ return {
42388
+ id: parseInt(result.data.dlp.id),
42389
+ name: result.data.dlp.name || "",
42390
+ metadata: result.data.dlp.metadata,
42391
+ status: result.data.dlp.status ? parseInt(result.data.dlp.status) : void 0,
42392
+ address: result.data.dlp.address,
42393
+ owner: result.data.dlp.owner
42394
+ };
42395
+ } catch (error) {
42396
+ console.debug("Subgraph query failed, falling back to chain:", error);
42397
+ }
42398
+ }
42399
+ try {
42400
+ const chainId = this.context.walletClient.chain?.id;
42401
+ if (!chainId) {
42402
+ throw new Error("Chain ID not available");
42403
+ }
42404
+ const dlpRegistryAddress = getContractAddress(chainId, "DLPRegistry");
42405
+ const dlpRegistryAbi = getAbi("DLPRegistry");
42406
+ const dlpData = await this.context.publicClient.readContract({
42407
+ address: dlpRegistryAddress,
42408
+ abi: dlpRegistryAbi,
42409
+ functionName: "dlps",
42410
+ args: [BigInt(dlpId)]
42411
+ });
42412
+ if (!dlpData || !dlpData.name) {
42413
+ throw new Error(`DLP not found: ${dlpId}`);
42414
+ }
42415
+ return {
42416
+ id: dlpId,
42417
+ name: dlpData.name,
42418
+ metadata: dlpData.metadata,
42419
+ status: dlpData.status,
42420
+ address: dlpData.dlpAddress,
42421
+ owner: dlpData.ownerAddress
42422
+ };
42423
+ } catch (error) {
42424
+ throw new Error(
42425
+ `Failed to fetch DLP: ${error instanceof Error ? error.message : "Unknown error"}`
42426
+ );
42427
+ }
42428
+ }
42429
+ /**
42430
+ * Lists all Data Liquidity Pools (DLPs) with optional pagination.
42431
+ *
42432
+ * @remarks
42433
+ * Fetches a paginated list of all DLPs registered in the network.
42434
+ * Uses subgraph for efficient querying with fallback to chain multicall.
42435
+ *
42436
+ * @param options - Optional parameters for pagination and filtering
42437
+ * @param options.limit - Maximum number of DLPs to return (default: 100)
42438
+ * @param options.offset - Number of DLPs to skip (default: 0)
42439
+ * @param options.subgraphUrl - Custom subgraph URL to override default
42440
+ * @returns Promise resolving to array of DLP information
42441
+ * @throws {Error} When query fails - "Failed to list DLPs: {error}"
42442
+ * @example
42443
+ * ```typescript
42444
+ * // Get first 10 DLPs
42445
+ * const dlps = await vana.data.listDLPs({ limit: 10 });
42446
+ * dlps.forEach(dlp => console.log(`${dlp.id}: ${dlp.name}`));
42447
+ *
42448
+ * // Get next page
42449
+ * const nextPage = await vana.data.listDLPs({ limit: 10, offset: 10 });
42450
+ * ```
42451
+ */
42452
+ async listDLPs(options = {}) {
42453
+ const { limit = 100, offset = 0 } = options;
42454
+ const subgraphUrl = options.subgraphUrl || this.context.subgraphUrl;
42455
+ if (subgraphUrl) {
42456
+ try {
42457
+ const query = `
42458
+ query ListDLPs($first: Int!, $skip: Int!) {
42459
+ dlps(first: $first, skip: $skip, orderBy: id) {
42460
+ id
42461
+ name
42462
+ metadata
42463
+ status
42464
+ address
42465
+ owner
42466
+ }
42467
+ }
42468
+ `;
42469
+ const response = await fetch(subgraphUrl, {
42470
+ method: "POST",
42471
+ headers: {
42472
+ "Content-Type": "application/json"
42473
+ },
42474
+ body: JSON.stringify({
42475
+ query,
42476
+ variables: {
42477
+ first: limit,
42478
+ skip: offset
42479
+ }
42480
+ })
42481
+ });
42482
+ if (!response.ok) {
42483
+ throw new Error(
42484
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42485
+ );
42486
+ }
42487
+ const result = await response.json();
42488
+ if (result.errors) {
42489
+ throw new Error(
42490
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42491
+ );
42492
+ }
42493
+ const dlps = result.data?.dlps || [];
42494
+ return dlps.map((dlp) => ({
42495
+ id: parseInt(dlp.id),
42496
+ name: dlp.name || "",
42497
+ metadata: dlp.metadata,
42498
+ status: dlp.status ? parseInt(dlp.status) : void 0,
42499
+ address: dlp.address,
42500
+ owner: dlp.owner
42501
+ }));
42502
+ } catch (error) {
42503
+ console.debug("Subgraph query failed, falling back to chain:", error);
42504
+ }
42505
+ }
42506
+ try {
42507
+ const chainId = this.context.walletClient.chain?.id;
42508
+ if (!chainId) {
42509
+ throw new Error("Chain ID not available");
42510
+ }
42511
+ const dlpRegistryAddress = getContractAddress(chainId, "DLPRegistry");
42512
+ const dlpRegistryAbi = getAbi("DLPRegistry");
42513
+ const dlpCount = await this.context.publicClient.readContract({
42514
+ address: dlpRegistryAddress,
42515
+ abi: dlpRegistryAbi,
42516
+ functionName: "dlpsCount",
42517
+ args: []
42518
+ });
42519
+ const totalCount = Number(dlpCount);
42520
+ const start = offset;
42521
+ const end = Math.min(start + limit, totalCount);
42522
+ if (end <= start) {
42523
+ return [];
42524
+ }
42525
+ const calls = [];
42526
+ for (let i = start + 1; i <= end; i++) {
42527
+ calls.push({
42528
+ address: dlpRegistryAddress,
42529
+ abi: dlpRegistryAbi,
42530
+ functionName: "dlps",
42531
+ args: [BigInt(i)]
42532
+ });
42533
+ }
42534
+ const results = await gasAwareMulticall(this.context.publicClient, {
42535
+ contracts: calls,
42536
+ allowFailure: true,
42537
+ batchSize: 50
42538
+ });
42539
+ const dlps = [];
42540
+ for (let i = 0; i < results.length; i++) {
42541
+ const result = results[i];
42542
+ if (result.status === "success" && result.result) {
42543
+ const dlpData = result.result;
42544
+ if (dlpData.name) {
42545
+ dlps.push({
42546
+ id: start + i + 1,
42547
+ name: dlpData.name,
42548
+ metadata: dlpData.metadata,
42549
+ status: dlpData.status,
42550
+ address: dlpData.dlpAddress,
42551
+ owner: dlpData.ownerAddress
42552
+ });
42553
+ }
42554
+ }
42555
+ }
42556
+ return dlps;
42557
+ } catch (error) {
42558
+ throw new Error(
42559
+ `Failed to list DLPs: ${error instanceof Error ? error.message : "Unknown error"}`
42560
+ );
42561
+ }
42562
+ }
42918
42563
  /**
42919
42564
  * Retrieves a list of permissions granted by a user.
42920
42565
  *
@@ -44341,10 +43986,10 @@ var DataController = class {
44341
43986
  );
44342
43987
  }
44343
43988
  /**
44344
- * Validates a data schema against the Vana meta-schema.
43989
+ * Validates a data schema definition against the Vana meta-schema.
44345
43990
  *
44346
- * @param schema - The data schema to validate
44347
- * @returns Assertion that schema is valid (throws if invalid)
43991
+ * @param schema - The data schema definition to validate
43992
+ * @returns The validated DataSchema
44348
43993
  * @throws SchemaValidationError if invalid
44349
43994
  * @example
44350
43995
  * ```typescript
@@ -44361,11 +44006,11 @@ var DataController = class {
44361
44006
  * }
44362
44007
  * };
44363
44008
  *
44364
- * vana.data.validateDataSchema(schema);
44009
+ * const validatedSchema = vana.data.validateDataSchemaAgainstMetaSchema(schema);
44365
44010
  * ```
44366
44011
  */
44367
- validateDataSchema(schema) {
44368
- return validateDataSchema(schema);
44012
+ validateDataSchemaAgainstMetaSchema(schema) {
44013
+ return validateDataSchemaAgainstMetaSchema(schema);
44369
44014
  }
44370
44015
  /**
44371
44016
  * Validates data against a JSON Schema from a data schema.
@@ -44398,9 +44043,9 @@ var DataController = class {
44398
44043
  return validateDataAgainstSchema(data, schema);
44399
44044
  }
44400
44045
  /**
44401
- * Fetches and validates a schema from a URL, then returns the parsed data schema.
44046
+ * Fetches and validates a data schema from a URL, then returns the parsed data schema.
44402
44047
  *
44403
- * @param url - The URL to fetch the schema from
44048
+ * @param url - The URL to fetch the data schema from
44404
44049
  * @returns The validated data schema
44405
44050
  * @throws SchemaValidationError if invalid or fetch fails
44406
44051
  * @example
@@ -45598,7 +45243,7 @@ var GoogleDriveStorage = class {
45598
45243
  };
45599
45244
 
45600
45245
  // src/storage/providers/ipfs.ts
45601
- init_encoding();
45246
+ init_crypto_utils();
45602
45247
  var IpfsStorage = class _IpfsStorage {
45603
45248
  constructor(config) {
45604
45249
  this.config = config;
@@ -45638,9 +45283,8 @@ var IpfsStorage = class _IpfsStorage {
45638
45283
  * ```
45639
45284
  */
45640
45285
  static forInfura(credentials) {
45641
- const encoder = new TextEncoder();
45642
45286
  const auth = toBase64(
45643
- encoder.encode(`${credentials.projectId}:${credentials.projectSecret}`)
45287
+ `${credentials.projectId}:${credentials.projectSecret}`
45644
45288
  );
45645
45289
  return new _IpfsStorage({
45646
45290
  apiEndpoint: "https://ipfs.infura.io:5001/api/v0/add",
@@ -46500,7 +46144,7 @@ var vanaMainnet2 = {
46500
46144
  url: "https://vanascan.io"
46501
46145
  }
46502
46146
  },
46503
- subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/vana/7.0.7/gn"
46147
+ subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/vana/prod/gn"
46504
46148
  };
46505
46149
  var moksha = {
46506
46150
  id: 14800,
@@ -46521,7 +46165,7 @@ var moksha = {
46521
46165
  url: "https://moksha.vanascan.io"
46522
46166
  }
46523
46167
  },
46524
- subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/moksha/7.0.7/gn"
46168
+ subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/moksha/prod/gn"
46525
46169
  };
46526
46170
  function getChainConfig(chainId) {
46527
46171
  switch (chainId) {
@@ -47550,7 +47194,7 @@ async function handleRelayerRequest(sdk, payload) {
47550
47194
 
47551
47195
  // src/index.node.ts
47552
47196
  init_transactionHandle();
47553
- init_browser2();
47197
+ init_browser();
47554
47198
 
47555
47199
  // src/platform/utils.ts
47556
47200
  function detectPlatform() {
@@ -47575,7 +47219,7 @@ async function createPlatformAdapter() {
47575
47219
  const { NodePlatformAdapter: NodePlatformAdapter2 } = await import(moduleName);
47576
47220
  return new NodePlatformAdapter2();
47577
47221
  } else {
47578
- const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser2(), browser_exports));
47222
+ const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser(), browser_exports));
47579
47223
  return new BrowserPlatformAdapter2();
47580
47224
  }
47581
47225
  } catch (error) {
@@ -47596,7 +47240,7 @@ async function createPlatformAdapterFor(platformType) {
47596
47240
  const { NodePlatformAdapter: NodePlatformAdapter2 } = await import(moduleName);
47597
47241
  return new NodePlatformAdapter2();
47598
47242
  } else {
47599
- const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser2(), browser_exports));
47243
+ const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser(), browser_exports));
47600
47244
  return new BrowserPlatformAdapter2();
47601
47245
  }
47602
47246
  } catch (error) {
@@ -47623,7 +47267,7 @@ function getPlatformCapabilities() {
47623
47267
  }
47624
47268
 
47625
47269
  // src/platform/browser-safe.ts
47626
- init_browser2();
47270
+ init_browser();
47627
47271
  async function createNodePlatformAdapter() {
47628
47272
  if (typeof window !== "undefined") {
47629
47273
  throw new Error(
@@ -48069,7 +47713,7 @@ export {
48069
47713
  storeGrantFile,
48070
47714
  summarizeGrant,
48071
47715
  validateDataAgainstSchema,
48072
- validateDataSchema,
47716
+ validateDataSchemaAgainstMetaSchema,
48073
47717
  validateGrant,
48074
47718
  validateGrantExpiry,
48075
47719
  validateGrantFile,