@opendatalabs/vana-sdk 0.1.0-alpha.606fa2d → 0.1.0-alpha.64b26ef

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 +258 -350
  19. package/dist/index.browser.js +696 -869
  20. package/dist/index.browser.js.map +1 -1
  21. package/dist/index.node.cjs +734 -1018
  22. package/dist/index.node.cjs.map +1 -1
  23. package/dist/index.node.d.cts +262 -109
  24. package/dist/index.node.d.ts +262 -109
  25. package/dist/index.node.js +736 -1032
  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: [
@@ -3354,6 +2811,19 @@ var init_DataRegistryImplementation = __esm({
3354
2811
  name: "Upgraded",
3355
2812
  type: "event"
3356
2813
  },
2814
+ {
2815
+ inputs: [],
2816
+ name: "DATA_PORTABILITY_ROLE",
2817
+ outputs: [
2818
+ {
2819
+ internalType: "bytes32",
2820
+ name: "",
2821
+ type: "bytes32"
2822
+ }
2823
+ ],
2824
+ stateMutability: "view",
2825
+ type: "function"
2826
+ },
3357
2827
  {
3358
2828
  inputs: [],
3359
2829
  name: "DEFAULT_ADMIN_ROLE",
@@ -3448,6 +2918,41 @@ var init_DataRegistryImplementation = __esm({
3448
2918
  stateMutability: "nonpayable",
3449
2919
  type: "function"
3450
2920
  },
2921
+ {
2922
+ inputs: [
2923
+ {
2924
+ internalType: "uint256",
2925
+ name: "fileId",
2926
+ type: "uint256"
2927
+ },
2928
+ {
2929
+ components: [
2930
+ {
2931
+ internalType: "address",
2932
+ name: "account",
2933
+ type: "address"
2934
+ },
2935
+ {
2936
+ internalType: "string",
2937
+ name: "key",
2938
+ type: "string"
2939
+ }
2940
+ ],
2941
+ internalType: "struct IDataRegistry.Permission[]",
2942
+ name: "permissions",
2943
+ type: "tuple[]"
2944
+ },
2945
+ {
2946
+ internalType: "uint256",
2947
+ name: "schemaId",
2948
+ type: "uint256"
2949
+ }
2950
+ ],
2951
+ name: "addFilePermissionsAndSchema",
2952
+ outputs: [],
2953
+ stateMutability: "nonpayable",
2954
+ type: "function"
2955
+ },
3451
2956
  {
3452
2957
  inputs: [
3453
2958
  {
@@ -3662,6 +3167,19 @@ var init_DataRegistryImplementation = __esm({
3662
3167
  stateMutability: "view",
3663
3168
  type: "function"
3664
3169
  },
3170
+ {
3171
+ inputs: [],
3172
+ name: "emitLegacyEvents",
3173
+ outputs: [
3174
+ {
3175
+ internalType: "bool",
3176
+ name: "",
3177
+ type: "bool"
3178
+ }
3179
+ ],
3180
+ stateMutability: "view",
3181
+ type: "function"
3182
+ },
3665
3183
  {
3666
3184
  inputs: [
3667
3185
  {
@@ -3819,6 +3337,11 @@ var init_DataRegistryImplementation = __esm({
3819
3337
  name: "url",
3820
3338
  type: "string"
3821
3339
  },
3340
+ {
3341
+ internalType: "uint256",
3342
+ name: "schemaId",
3343
+ type: "uint256"
3344
+ },
3822
3345
  {
3823
3346
  internalType: "uint256",
3824
3347
  name: "addedAtBlock",
@@ -4102,6 +3625,19 @@ var init_DataRegistryImplementation = __esm({
4102
3625
  stateMutability: "nonpayable",
4103
3626
  type: "function"
4104
3627
  },
3628
+ {
3629
+ inputs: [
3630
+ {
3631
+ internalType: "bool",
3632
+ name: "newEmitLegacyEvents",
3633
+ type: "bool"
3634
+ }
3635
+ ],
3636
+ name: "updateEmitLegacyEvents",
3637
+ outputs: [],
3638
+ stateMutability: "nonpayable",
3639
+ type: "function"
3640
+ },
4105
3641
  {
4106
3642
  inputs: [
4107
3643
  {
@@ -36909,7 +36445,7 @@ var init_schemas = __esm({
36909
36445
  dialect,
36910
36446
  schema: schemaDefinition
36911
36447
  };
36912
- validateDataSchema(dataSchema);
36448
+ validateDataSchemaAgainstMetaSchema(dataSchema);
36913
36449
  if (!this.context.storageManager) {
36914
36450
  if (this.context.validateStorageRequired) {
36915
36451
  this.context.validateStorageRequired();
@@ -37018,7 +36554,7 @@ var init_schemas = __esm({
37018
36554
  `Invalid schema definition format for schema ${schemaId}`
37019
36555
  );
37020
36556
  }
37021
- validateDataSchema(definition);
36557
+ validateDataSchemaAgainstMetaSchema(definition);
37022
36558
  const dataSchema = definition;
37023
36559
  if (dataSchema.name !== metadata.name) {
37024
36560
  throw new Error(
@@ -37353,7 +36889,7 @@ var init_schemas = __esm({
37353
36889
  try {
37354
36890
  const definition = await fetchFromUrl(schema.definitionUrl);
37355
36891
  if (definition && typeof definition === "object") {
37356
- validateDataSchema(definition);
36892
+ validateDataSchemaAgainstMetaSchema(definition);
37357
36893
  const dataSchema = definition;
37358
36894
  schema.version = dataSchema.version;
37359
36895
  schema.description = dataSchema.description;
@@ -37372,204 +36908,123 @@ var init_schemas = __esm({
37372
36908
  }
37373
36909
  });
37374
36910
 
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
36911
  // src/platform/browser.ts
37475
36912
  var browser_exports = {};
37476
36913
  __export(browser_exports, {
37477
- BrowserPlatformAdapter: () => BrowserPlatformAdapter
36914
+ BrowserPlatformAdapter: () => BrowserPlatformAdapter,
36915
+ browserPlatformAdapter: () => browserPlatformAdapter
37478
36916
  });
37479
- var secp256k13, getOpenPGP2, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter;
37480
- var init_browser2 = __esm({
36917
+ var getOpenPGP2, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter, browserPlatformAdapter;
36918
+ var init_browser = __esm({
37481
36919
  "src/platform/browser.ts"() {
37482
36920
  "use strict";
36921
+ init_crypto_utils();
37483
36922
  init_pgp_utils();
37484
36923
  init_error_utils();
37485
36924
  init_lazy_import();
37486
- init_WalletKeyEncryptionService();
37487
- init_crypto_utils();
37488
- init_utils();
37489
- secp256k13 = __toESM(require("@noble/secp256k1"), 1);
37490
- init_browser();
37491
36925
  getOpenPGP2 = lazyImport(() => import("openpgp"));
37492
36926
  BrowserCryptoAdapter = class {
37493
- eciesProvider = new BrowserECIESUint8Provider();
37494
- walletKeyEncryptionService = new WalletKeyEncryptionService({
37495
- eciesProvider: this.eciesProvider
37496
- });
37497
36927
  async encryptWithPublicKey(data, publicKeyHex) {
37498
36928
  try {
37499
- const publicKeyBytes = hexToBytes2(publicKeyHex);
37500
- const encrypted = await this.eciesProvider.encrypt(
37501
- publicKeyBytes,
37502
- stringToBytes2(data)
36929
+ const eccrypto = await import("eccrypto-js");
36930
+ const publicKeyBuffer = Buffer.from(publicKeyHex, "hex");
36931
+ const encrypted = await eccrypto.encrypt(
36932
+ publicKeyBuffer,
36933
+ Buffer.from(data, "utf8")
37503
36934
  );
37504
- const result = concatBytes2(
36935
+ const result = Buffer.concat([
37505
36936
  encrypted.iv,
37506
36937
  encrypted.ephemPublicKey,
37507
36938
  encrypted.ciphertext,
37508
36939
  encrypted.mac
37509
- );
37510
- return bytesToHex2(result);
36940
+ ]);
36941
+ return result.toString("hex");
37511
36942
  } catch (error) {
37512
- throw wrapCryptoError("encryptWithPublicKey", error);
36943
+ throw new Error(`Encryption failed: ${error}`);
37513
36944
  }
37514
36945
  }
37515
36946
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
37516
36947
  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
36948
+ const eccrypto = await import("eccrypto-js");
36949
+ const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
36950
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
36951
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
36952
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
36953
+ const decryptedBuffer = await eccrypto.decrypt(
36954
+ privateKeyBuffer,
36955
+ encryptedObj
37523
36956
  );
37524
- return bytesToString2(decrypted);
36957
+ return decryptedBuffer.toString("utf8");
37525
36958
  } catch (error) {
37526
- throw wrapCryptoError("decryptWithPrivateKey", error);
36959
+ throw new Error(`Decryption failed: ${error}`);
37527
36960
  }
37528
36961
  }
37529
- async encryptWithWalletPublicKey(data, publicKey) {
36962
+ async generateKeyPair() {
37530
36963
  try {
37531
- return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
37532
- data,
37533
- publicKey
37534
- );
36964
+ const eccrypto = await import("eccrypto-js");
36965
+ const privateKeyBytes = new Uint8Array(32);
36966
+ crypto.getRandomValues(privateKeyBytes);
36967
+ const privateKey = Buffer.from(privateKeyBytes);
36968
+ const publicKey = eccrypto.getPublicCompressed(privateKey);
36969
+ return {
36970
+ privateKey: privateKey.toString("hex"),
36971
+ publicKey: publicKey.toString("hex")
36972
+ };
37535
36973
  } catch (error) {
37536
- throw wrapCryptoError("encryptWithWalletPublicKey", error);
36974
+ throw wrapCryptoError("key generation", error);
37537
36975
  }
37538
36976
  }
37539
- async decryptWithWalletPrivateKey(encryptedData, privateKey) {
36977
+ async encryptWithWalletPublicKey(data, publicKey) {
37540
36978
  try {
37541
- return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
37542
- encryptedData,
37543
- privateKey
36979
+ const eccrypto = await import("eccrypto-js");
36980
+ const uncompressedKey = processWalletPublicKey(publicKey);
36981
+ const encryptedBuffer = await eccrypto.encrypt(
36982
+ uncompressedKey,
36983
+ Buffer.from(data)
37544
36984
  );
36985
+ const result = Buffer.concat([
36986
+ encryptedBuffer.iv,
36987
+ encryptedBuffer.ephemPublicKey,
36988
+ encryptedBuffer.ciphertext,
36989
+ encryptedBuffer.mac
36990
+ ]);
36991
+ return result.toString("hex");
37545
36992
  } catch (error) {
37546
- throw wrapCryptoError("decryptWithWalletPrivateKey", error);
36993
+ throw wrapCryptoError("encrypt with wallet public key", error);
37547
36994
  }
37548
36995
  }
37549
- async generateKeyPair() {
36996
+ async decryptWithWalletPrivateKey(encryptedData, privateKey) {
37550
36997
  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
- };
36998
+ const eccrypto = await import("eccrypto-js");
36999
+ const privateKeyBuffer = processWalletPrivateKey(privateKey);
37000
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
37001
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
37002
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
37003
+ const decryptedBuffer = await eccrypto.decrypt(
37004
+ privateKeyBuffer,
37005
+ encryptedObj
37006
+ );
37007
+ return decryptedBuffer.toString("utf8");
37557
37008
  } catch (error) {
37558
- throw wrapCryptoError("generateKeyPair", error);
37009
+ throw wrapCryptoError("decrypt with wallet private key", error);
37559
37010
  }
37560
37011
  }
37561
37012
  async encryptWithPassword(data, password) {
37562
37013
  try {
37563
37014
  const openpgp = await getOpenPGP2();
37564
- const message = await openpgp.createMessage({ binary: data });
37015
+ const message = await openpgp.createMessage({
37016
+ binary: data
37017
+ });
37565
37018
  const encrypted = await openpgp.encrypt({
37566
37019
  message,
37567
37020
  passwords: [password],
37568
37021
  format: "binary"
37569
37022
  });
37570
- return new Uint8Array(encrypted);
37023
+ const response = new Response(encrypted);
37024
+ const arrayBuffer = await response.arrayBuffer();
37025
+ return new Uint8Array(arrayBuffer);
37571
37026
  } catch (error) {
37572
- throw wrapCryptoError("encryptWithPassword", error);
37027
+ throw new Error(`Failed to encrypt with password: ${error}`);
37573
37028
  }
37574
37029
  }
37575
37030
  async decryptWithPassword(encryptedData, password) {
@@ -37578,14 +37033,14 @@ var init_browser2 = __esm({
37578
37033
  const message = await openpgp.readMessage({
37579
37034
  binaryMessage: encryptedData
37580
37035
  });
37581
- const { data } = await openpgp.decrypt({
37036
+ const { data: decrypted } = await openpgp.decrypt({
37582
37037
  message,
37583
37038
  passwords: [password],
37584
37039
  format: "binary"
37585
37040
  });
37586
- return new Uint8Array(data);
37041
+ return new Uint8Array(decrypted);
37587
37042
  } catch (error) {
37588
- throw wrapCryptoError("decryptWithPassword", error);
37043
+ throw new Error(`Failed to decrypt with password: ${error}`);
37589
37044
  }
37590
37045
  }
37591
37046
  };
@@ -37637,6 +37092,9 @@ var init_browser2 = __esm({
37637
37092
  };
37638
37093
  BrowserHttpAdapter = class {
37639
37094
  async fetch(url, options) {
37095
+ if (typeof fetch === "undefined") {
37096
+ throw new Error("Fetch API not available in this browser environment");
37097
+ }
37640
37098
  return fetch(url, options);
37641
37099
  }
37642
37100
  };
@@ -37654,19 +37112,17 @@ var init_browser2 = __esm({
37654
37112
  }
37655
37113
  set(key, value) {
37656
37114
  try {
37657
- if (typeof sessionStorage === "undefined") {
37658
- return;
37115
+ if (typeof sessionStorage !== "undefined") {
37116
+ sessionStorage.setItem(this.prefix + key, value);
37659
37117
  }
37660
- sessionStorage.setItem(this.prefix + key, value);
37661
37118
  } catch {
37662
37119
  }
37663
37120
  }
37664
37121
  delete(key) {
37665
37122
  try {
37666
- if (typeof sessionStorage === "undefined") {
37667
- return;
37123
+ if (typeof sessionStorage !== "undefined") {
37124
+ sessionStorage.removeItem(this.prefix + key);
37668
37125
  }
37669
- sessionStorage.removeItem(this.prefix + key);
37670
37126
  } catch {
37671
37127
  }
37672
37128
  }
@@ -37675,25 +37131,30 @@ var init_browser2 = __esm({
37675
37131
  if (typeof sessionStorage === "undefined") {
37676
37132
  return;
37677
37133
  }
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);
37134
+ const keys = Object.keys(sessionStorage);
37135
+ for (const key of keys) {
37136
+ if (key.startsWith(this.prefix)) {
37137
+ sessionStorage.removeItem(key);
37683
37138
  }
37684
37139
  }
37685
- keysToRemove.forEach((key) => sessionStorage.removeItem(key));
37686
37140
  } catch {
37687
37141
  }
37688
37142
  }
37689
37143
  };
37690
37144
  BrowserPlatformAdapter = class {
37691
- crypto = new BrowserCryptoAdapter();
37692
- pgp = new BrowserPGPAdapter();
37693
- http = new BrowserHttpAdapter();
37694
- cache = new BrowserCacheAdapter();
37145
+ crypto;
37146
+ pgp;
37147
+ http;
37148
+ cache;
37695
37149
  platform = "browser";
37150
+ constructor() {
37151
+ this.crypto = new BrowserCryptoAdapter();
37152
+ this.pgp = new BrowserPGPAdapter();
37153
+ this.http = new BrowserHttpAdapter();
37154
+ this.cache = new BrowserCacheAdapter();
37155
+ }
37696
37156
  };
37157
+ browserPlatformAdapter = new BrowserPlatformAdapter();
37697
37158
  }
37698
37159
  });
37699
37160
 
@@ -37811,7 +37272,7 @@ __export(index_node_exports, {
37811
37272
  storeGrantFile: () => storeGrantFile,
37812
37273
  summarizeGrant: () => summarizeGrant,
37813
37274
  validateDataAgainstSchema: () => validateDataAgainstSchema,
37814
- validateDataSchema: () => validateDataSchema,
37275
+ validateDataSchemaAgainstMetaSchema: () => validateDataSchemaAgainstMetaSchema,
37815
37276
  validateGrant: () => validateGrant,
37816
37277
  validateGrantExpiry: () => validateGrantExpiry,
37817
37278
  validateGrantFile: () => validateGrantFile,
@@ -37823,6 +37284,7 @@ __export(index_node_exports, {
37823
37284
  module.exports = __toCommonJS(index_node_exports);
37824
37285
 
37825
37286
  // src/platform/node.ts
37287
+ init_crypto_utils();
37826
37288
  init_pgp_utils();
37827
37289
  init_error_utils();
37828
37290
 
@@ -37851,123 +37313,15 @@ async function streamToUint8Array(stream) {
37851
37313
 
37852
37314
  // src/platform/node.ts
37853
37315
  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
37316
  var getOpenPGP = lazyImport(() => import("openpgp"));
37317
+ var getEccrypto = lazyImport(() => import("eccrypto"));
37961
37318
  var NodeCryptoAdapter = class {
37962
- eciesProvider = new NodeECIESUint8Provider();
37963
- walletKeyEncryptionService = new WalletKeyEncryptionService({
37964
- eciesProvider: this.eciesProvider
37965
- });
37966
37319
  async encryptWithPublicKey(data, publicKeyHex) {
37967
37320
  try {
37321
+ const eccrypto = await getEccrypto();
37968
37322
  const publicKey = Buffer.from(publicKeyHex, "hex");
37969
37323
  const message = Buffer.from(data, "utf8");
37970
- const encrypted = await this.eciesProvider.encrypt(publicKey, message);
37324
+ const encrypted = await eccrypto.encrypt(publicKey, message);
37971
37325
  const result = Buffer.concat([
37972
37326
  encrypted.iv,
37973
37327
  encrypted.ephemPublicKey,
@@ -37976,54 +37330,27 @@ var NodeCryptoAdapter = class {
37976
37330
  ]);
37977
37331
  return result.toString("hex");
37978
37332
  } 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
- );
37333
+ throw new Error(`Encryption failed: ${error}`);
37987
37334
  }
37988
37335
  }
37989
37336
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
37990
37337
  try {
37338
+ const eccrypto = await getEccrypto();
37991
37339
  const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
37992
37340
  const encryptedBuffer = Buffer.from(encryptedData, "hex");
37993
37341
  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);
37342
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
37343
+ const decrypted = await eccrypto.decrypt(privateKeyBuffer, encryptedObj);
37344
+ return decrypted.toString("utf8");
38005
37345
  } 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
- );
37346
+ throw new Error(`Decryption failed: ${error}`);
38014
37347
  }
38015
37348
  }
38016
37349
  async generateKeyPair() {
38017
37350
  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
- );
37351
+ const eccrypto = await getEccrypto();
37352
+ const privateKey = eccrypto.generatePrivate();
37353
+ const publicKey = eccrypto.getPublicCompressed(privateKey);
38027
37354
  return {
38028
37355
  privateKey: privateKey.toString("hex"),
38029
37356
  publicKey: publicKey.toString("hex")
@@ -38034,20 +37361,35 @@ var NodeCryptoAdapter = class {
38034
37361
  }
38035
37362
  async encryptWithWalletPublicKey(data, publicKey) {
38036
37363
  try {
38037
- return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
38038
- data,
38039
- publicKey
37364
+ const eccrypto = await getEccrypto();
37365
+ const uncompressedKey = processWalletPublicKey(publicKey);
37366
+ const encrypted = await eccrypto.encrypt(
37367
+ uncompressedKey,
37368
+ Buffer.from(data)
38040
37369
  );
37370
+ const result = Buffer.concat([
37371
+ encrypted.iv,
37372
+ encrypted.ephemPublicKey,
37373
+ encrypted.ciphertext,
37374
+ encrypted.mac
37375
+ ]);
37376
+ return result.toString("hex");
38041
37377
  } catch (error) {
38042
37378
  throw wrapCryptoError("encrypt with wallet public key", error);
38043
37379
  }
38044
37380
  }
38045
37381
  async decryptWithWalletPrivateKey(encryptedData, privateKey) {
38046
37382
  try {
38047
- return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
38048
- encryptedData,
38049
- privateKey
37383
+ const eccrypto = await getEccrypto();
37384
+ const privateKeyBuffer = processWalletPrivateKey(privateKey);
37385
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
37386
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
37387
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
37388
+ const decryptedBuffer = await eccrypto.decrypt(
37389
+ privateKeyBuffer,
37390
+ encryptedObj
38050
37391
  );
37392
+ return decryptedBuffer.toString("utf8");
38051
37393
  } catch (error) {
38052
37394
  throw wrapCryptoError("decrypt with wallet private key", error);
38053
37395
  }
@@ -38219,6 +37561,9 @@ var StorageError = class extends Error {
38219
37561
  }
38220
37562
  };
38221
37563
 
37564
+ // src/types/index.ts
37565
+ init_schemaValidation();
37566
+
38222
37567
  // src/types/external-apis.ts
38223
37568
  function isReplicateAPIResponse(value) {
38224
37569
  if (typeof value !== "object" || value === null) return false;
@@ -38661,8 +38006,7 @@ function validateOperationAccess(grantFile, requestedOperation) {
38661
38006
  }
38662
38007
 
38663
38008
  // src/utils/signatureCache.ts
38664
- var import_sha256 = require("@noble/hashes/sha256");
38665
- var import_utils2 = require("@noble/hashes/utils");
38009
+ init_crypto_utils();
38666
38010
  var SignatureCache = class {
38667
38011
  static PREFIX = "vana_sig_";
38668
38012
  static DEFAULT_TTL_HOURS = 2;
@@ -38761,12 +38105,12 @@ var SignatureCache = class {
38761
38105
  * Generate a deterministic hash of a message object for cache key generation
38762
38106
  *
38763
38107
  * @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.
38108
+ * Creates a consistent hash from complex objects including EIP-712 typed data.
38109
+ * Handles BigInt serialization and produces a 32-character hash that balances
38110
+ * uniqueness with key length constraints.
38767
38111
  *
38768
38112
  * @param message - The message object to hash (typically EIP-712 typed data)
38769
- * @returns A hex string hash (SHA-256) suitable for cache keys
38113
+ * @returns A 32-character hash string suitable for cache keys
38770
38114
  * @example
38771
38115
  * ```typescript
38772
38116
  * const typedData = {
@@ -38775,35 +38119,30 @@ var SignatureCache = class {
38775
38119
  * };
38776
38120
  *
38777
38121
  * const hash = SignatureCache.hashMessage(typedData);
38778
- * // Returns SHA-256 hash like: "a1b2c3d4e5f6..."
38122
+ * // Returns something like: "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"
38779
38123
  * ```
38780
38124
  */
38781
38125
  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);
38126
+ const jsonString = JSON.stringify(message, this.bigIntReplacer);
38127
+ const base64Hash = toBase64(jsonString);
38128
+ const cleaned = base64Hash.replace(/[^a-zA-Z0-9]/g, "");
38129
+ if (cleaned.length > 32) {
38130
+ return cleaned.substring(0, 16) + cleaned.substring(cleaned.length - 16);
38131
+ }
38132
+ return cleaned.substring(0, 32);
38785
38133
  }
38786
38134
  /**
38787
- * Deterministic JSON replacer that handles BigInt values and sorts object keys
38788
- * This ensures consistent cache key generation for EIP-712 typed data
38135
+ * Custom JSON replacer that converts BigInt values to strings for serialization
38136
+ * This ensures deterministic cache key generation for EIP-712 typed data
38789
38137
  *
38790
38138
  * @param _key - The object key being serialized (unused)
38791
38139
  * @param value - The value to serialize
38792
- * @returns The serialized value with sorted keys for objects
38140
+ * @returns The serialized value
38793
38141
  */
38794
- static deterministicReplacer(_key, value) {
38142
+ static bigIntReplacer(_key, value) {
38795
38143
  if (typeof value === "bigint") {
38796
38144
  return `__BIGINT__${value.toString()}`;
38797
38145
  }
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
38146
  return value;
38808
38147
  }
38809
38148
  };
@@ -43044,6 +42383,29 @@ var DataController = class {
43044
42383
  const userFiles = Array.from(fileMap.values()).sort(
43045
42384
  (a, b) => Number((b.addedAtTimestamp || 0n) - (a.addedAtTimestamp || 0n))
43046
42385
  );
42386
+ if (userFiles.length > 0) {
42387
+ try {
42388
+ const fileIds = userFiles.map((f) => f.id);
42389
+ let proofMap;
42390
+ try {
42391
+ proofMap = await this._fetchProofsFromSubgraph(fileIds, endpoint);
42392
+ } catch (subgraphError) {
42393
+ console.debug(
42394
+ "Failed to fetch proofs from subgraph, trying chain:",
42395
+ subgraphError
42396
+ );
42397
+ proofMap = await this._fetchProofsFromChain(fileIds);
42398
+ }
42399
+ for (const file of userFiles) {
42400
+ const dlpIds = proofMap.get(file.id);
42401
+ if (dlpIds && dlpIds.length > 0) {
42402
+ file.dlpIds = dlpIds;
42403
+ }
42404
+ }
42405
+ } catch (error) {
42406
+ console.warn("Failed to fetch proof data for files:", error);
42407
+ }
42408
+ }
43047
42409
  return userFiles;
43048
42410
  } catch (error) {
43049
42411
  console.error("Failed to fetch user files from subgraph:", error);
@@ -43052,6 +42414,349 @@ var DataController = class {
43052
42414
  );
43053
42415
  }
43054
42416
  }
42417
+ /**
42418
+ * Fetches proof data for multiple files from the subgraph.
42419
+ *
42420
+ * @private
42421
+ * @param fileIds - Array of file IDs to fetch proofs for
42422
+ * @param subgraphUrl - The subgraph endpoint URL
42423
+ * @returns Map of file IDs to their associated DLP IDs
42424
+ */
42425
+ async _fetchProofsFromSubgraph(fileIds, subgraphUrl) {
42426
+ const query = `
42427
+ query GetFileProofs($fileIds: [BigInt!]!) {
42428
+ dataRegistryProofs(where: { fileId_in: $fileIds }) {
42429
+ fileId
42430
+ dlp {
42431
+ id
42432
+ }
42433
+ }
42434
+ }
42435
+ `;
42436
+ const response = await fetch(subgraphUrl, {
42437
+ method: "POST",
42438
+ headers: {
42439
+ "Content-Type": "application/json"
42440
+ },
42441
+ body: JSON.stringify({
42442
+ query,
42443
+ variables: {
42444
+ fileIds: fileIds.map((id) => id.toString())
42445
+ }
42446
+ })
42447
+ });
42448
+ if (!response.ok) {
42449
+ throw new Error(
42450
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42451
+ );
42452
+ }
42453
+ const result = await response.json();
42454
+ if (result.errors) {
42455
+ throw new Error(
42456
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42457
+ );
42458
+ }
42459
+ const proofMap = /* @__PURE__ */ new Map();
42460
+ if (result.data?.dataRegistryProofs) {
42461
+ for (const proof of result.data.dataRegistryProofs) {
42462
+ if (proof.dlp?.id) {
42463
+ const fileId = parseInt(proof.fileId);
42464
+ const dlpId = parseInt(proof.dlp.id);
42465
+ if (!proofMap.has(fileId)) {
42466
+ proofMap.set(fileId, []);
42467
+ }
42468
+ const dlpIds = proofMap.get(fileId);
42469
+ if (!dlpIds.includes(dlpId)) {
42470
+ dlpIds.push(dlpId);
42471
+ }
42472
+ }
42473
+ }
42474
+ }
42475
+ return proofMap;
42476
+ }
42477
+ /**
42478
+ * Fetches proof data for multiple files from the blockchain.
42479
+ * Falls back to this when subgraph is unavailable.
42480
+ *
42481
+ * @private
42482
+ * @param fileIds - Array of file IDs to fetch proofs for
42483
+ * @returns Map of file IDs to their associated DLP IDs
42484
+ */
42485
+ async _fetchProofsFromChain(fileIds) {
42486
+ const chainId = this.context.walletClient.chain?.id;
42487
+ if (!chainId) {
42488
+ throw new Error("Chain ID not available");
42489
+ }
42490
+ const dataRegistryAddress = getContractAddress(chainId, "DataRegistry");
42491
+ const dataRegistryAbi = getAbi("DataRegistry");
42492
+ const proofMap = /* @__PURE__ */ new Map();
42493
+ for (const fileId of fileIds) {
42494
+ const dlpIds = [];
42495
+ let proofIndex = 0;
42496
+ let hasMoreProofs = true;
42497
+ while (hasMoreProofs) {
42498
+ try {
42499
+ const proof = await this.context.publicClient.readContract({
42500
+ address: dataRegistryAddress,
42501
+ abi: dataRegistryAbi,
42502
+ functionName: "fileProofs",
42503
+ args: [BigInt(fileId), BigInt(proofIndex)]
42504
+ });
42505
+ if (proof?.data?.dlpId) {
42506
+ const dlpId = Number(proof.data.dlpId);
42507
+ if (!dlpIds.includes(dlpId)) {
42508
+ dlpIds.push(dlpId);
42509
+ }
42510
+ }
42511
+ proofIndex++;
42512
+ } catch {
42513
+ hasMoreProofs = false;
42514
+ }
42515
+ }
42516
+ if (dlpIds.length > 0) {
42517
+ proofMap.set(fileId, dlpIds);
42518
+ }
42519
+ }
42520
+ return proofMap;
42521
+ }
42522
+ /**
42523
+ * Retrieves information about a specific Data Liquidity Pool (DLP).
42524
+ *
42525
+ * @remarks
42526
+ * DLPs are entities that process and verify data files in the Vana network.
42527
+ * This method fetches DLP metadata including name, status, and performance rating.
42528
+ * Uses subgraph first for efficiency, falls back to chain if unavailable.
42529
+ *
42530
+ * @param dlpId - The unique identifier of the DLP
42531
+ * @param options - Optional parameters
42532
+ * @param options.subgraphUrl - Custom subgraph URL to override default
42533
+ * @returns Promise resolving to DLP information
42534
+ * @throws {Error} When DLP cannot be found - "DLP not found: {dlpId}"
42535
+ * @throws {Error} When query fails - "Failed to fetch DLP: {error}"
42536
+ * @example
42537
+ * ```typescript
42538
+ * const dlp = await vana.data.getDLP(26);
42539
+ * console.log(`DLP ${dlp.name}: ${dlp.status}`);
42540
+ * ```
42541
+ */
42542
+ async getDLP(dlpId, options = {}) {
42543
+ const subgraphUrl = options.subgraphUrl || this.context.subgraphUrl;
42544
+ if (subgraphUrl) {
42545
+ try {
42546
+ const query = `
42547
+ query GetDLP($id: ID!) {
42548
+ dlp(id: $id) {
42549
+ id
42550
+ name
42551
+ metadata
42552
+ status
42553
+ address
42554
+ owner
42555
+ }
42556
+ }
42557
+ `;
42558
+ const response = await fetch(subgraphUrl, {
42559
+ method: "POST",
42560
+ headers: {
42561
+ "Content-Type": "application/json"
42562
+ },
42563
+ body: JSON.stringify({
42564
+ query,
42565
+ variables: {
42566
+ id: dlpId.toString()
42567
+ }
42568
+ })
42569
+ });
42570
+ if (!response.ok) {
42571
+ throw new Error(
42572
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42573
+ );
42574
+ }
42575
+ const result = await response.json();
42576
+ if (result.errors) {
42577
+ throw new Error(
42578
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42579
+ );
42580
+ }
42581
+ if (!result.data?.dlp) {
42582
+ throw new Error(`DLP not found: ${dlpId}`);
42583
+ }
42584
+ return {
42585
+ id: parseInt(result.data.dlp.id),
42586
+ name: result.data.dlp.name || "",
42587
+ metadata: result.data.dlp.metadata,
42588
+ status: result.data.dlp.status ? parseInt(result.data.dlp.status) : void 0,
42589
+ address: result.data.dlp.address,
42590
+ owner: result.data.dlp.owner
42591
+ };
42592
+ } catch (error) {
42593
+ console.debug("Subgraph query failed, falling back to chain:", error);
42594
+ }
42595
+ }
42596
+ try {
42597
+ const chainId = this.context.walletClient.chain?.id;
42598
+ if (!chainId) {
42599
+ throw new Error("Chain ID not available");
42600
+ }
42601
+ const dlpRegistryAddress = getContractAddress(chainId, "DLPRegistry");
42602
+ const dlpRegistryAbi = getAbi("DLPRegistry");
42603
+ const dlpData = await this.context.publicClient.readContract({
42604
+ address: dlpRegistryAddress,
42605
+ abi: dlpRegistryAbi,
42606
+ functionName: "dlps",
42607
+ args: [BigInt(dlpId)]
42608
+ });
42609
+ if (!dlpData || !dlpData.name) {
42610
+ throw new Error(`DLP not found: ${dlpId}`);
42611
+ }
42612
+ return {
42613
+ id: dlpId,
42614
+ name: dlpData.name,
42615
+ metadata: dlpData.metadata,
42616
+ status: dlpData.status,
42617
+ address: dlpData.dlpAddress,
42618
+ owner: dlpData.ownerAddress
42619
+ };
42620
+ } catch (error) {
42621
+ throw new Error(
42622
+ `Failed to fetch DLP: ${error instanceof Error ? error.message : "Unknown error"}`
42623
+ );
42624
+ }
42625
+ }
42626
+ /**
42627
+ * Lists all Data Liquidity Pools (DLPs) with optional pagination.
42628
+ *
42629
+ * @remarks
42630
+ * Fetches a paginated list of all DLPs registered in the network.
42631
+ * Uses subgraph for efficient querying with fallback to chain multicall.
42632
+ *
42633
+ * @param options - Optional parameters for pagination and filtering
42634
+ * @param options.limit - Maximum number of DLPs to return (default: 100)
42635
+ * @param options.offset - Number of DLPs to skip (default: 0)
42636
+ * @param options.subgraphUrl - Custom subgraph URL to override default
42637
+ * @returns Promise resolving to array of DLP information
42638
+ * @throws {Error} When query fails - "Failed to list DLPs: {error}"
42639
+ * @example
42640
+ * ```typescript
42641
+ * // Get first 10 DLPs
42642
+ * const dlps = await vana.data.listDLPs({ limit: 10 });
42643
+ * dlps.forEach(dlp => console.log(`${dlp.id}: ${dlp.name}`));
42644
+ *
42645
+ * // Get next page
42646
+ * const nextPage = await vana.data.listDLPs({ limit: 10, offset: 10 });
42647
+ * ```
42648
+ */
42649
+ async listDLPs(options = {}) {
42650
+ const { limit = 100, offset = 0 } = options;
42651
+ const subgraphUrl = options.subgraphUrl || this.context.subgraphUrl;
42652
+ if (subgraphUrl) {
42653
+ try {
42654
+ const query = `
42655
+ query ListDLPs($first: Int!, $skip: Int!) {
42656
+ dlps(first: $first, skip: $skip, orderBy: id) {
42657
+ id
42658
+ name
42659
+ metadata
42660
+ status
42661
+ address
42662
+ owner
42663
+ }
42664
+ }
42665
+ `;
42666
+ const response = await fetch(subgraphUrl, {
42667
+ method: "POST",
42668
+ headers: {
42669
+ "Content-Type": "application/json"
42670
+ },
42671
+ body: JSON.stringify({
42672
+ query,
42673
+ variables: {
42674
+ first: limit,
42675
+ skip: offset
42676
+ }
42677
+ })
42678
+ });
42679
+ if (!response.ok) {
42680
+ throw new Error(
42681
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42682
+ );
42683
+ }
42684
+ const result = await response.json();
42685
+ if (result.errors) {
42686
+ throw new Error(
42687
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42688
+ );
42689
+ }
42690
+ const dlps = result.data?.dlps || [];
42691
+ return dlps.map((dlp) => ({
42692
+ id: parseInt(dlp.id),
42693
+ name: dlp.name || "",
42694
+ metadata: dlp.metadata,
42695
+ status: dlp.status ? parseInt(dlp.status) : void 0,
42696
+ address: dlp.address,
42697
+ owner: dlp.owner
42698
+ }));
42699
+ } catch (error) {
42700
+ console.debug("Subgraph query failed, falling back to chain:", error);
42701
+ }
42702
+ }
42703
+ try {
42704
+ const chainId = this.context.walletClient.chain?.id;
42705
+ if (!chainId) {
42706
+ throw new Error("Chain ID not available");
42707
+ }
42708
+ const dlpRegistryAddress = getContractAddress(chainId, "DLPRegistry");
42709
+ const dlpRegistryAbi = getAbi("DLPRegistry");
42710
+ const dlpCount = await this.context.publicClient.readContract({
42711
+ address: dlpRegistryAddress,
42712
+ abi: dlpRegistryAbi,
42713
+ functionName: "dlpsCount",
42714
+ args: []
42715
+ });
42716
+ const totalCount = Number(dlpCount);
42717
+ const start = offset;
42718
+ const end = Math.min(start + limit, totalCount);
42719
+ if (end <= start) {
42720
+ return [];
42721
+ }
42722
+ const calls = [];
42723
+ for (let i = start + 1; i <= end; i++) {
42724
+ calls.push({
42725
+ address: dlpRegistryAddress,
42726
+ abi: dlpRegistryAbi,
42727
+ functionName: "dlps",
42728
+ args: [BigInt(i)]
42729
+ });
42730
+ }
42731
+ const results = await gasAwareMulticall(this.context.publicClient, {
42732
+ contracts: calls,
42733
+ allowFailure: true,
42734
+ batchSize: 50
42735
+ });
42736
+ const dlps = [];
42737
+ for (let i = 0; i < results.length; i++) {
42738
+ const result = results[i];
42739
+ if (result.status === "success" && result.result) {
42740
+ const dlpData = result.result;
42741
+ if (dlpData.name) {
42742
+ dlps.push({
42743
+ id: start + i + 1,
42744
+ name: dlpData.name,
42745
+ metadata: dlpData.metadata,
42746
+ status: dlpData.status,
42747
+ address: dlpData.dlpAddress,
42748
+ owner: dlpData.ownerAddress
42749
+ });
42750
+ }
42751
+ }
42752
+ }
42753
+ return dlps;
42754
+ } catch (error) {
42755
+ throw new Error(
42756
+ `Failed to list DLPs: ${error instanceof Error ? error.message : "Unknown error"}`
42757
+ );
42758
+ }
42759
+ }
43055
42760
  /**
43056
42761
  * Retrieves a list of permissions granted by a user.
43057
42762
  *
@@ -44182,19 +43887,31 @@ var DataController = class {
44182
43887
  return await this.submitFilePermission(fileId, account, publicKey);
44183
43888
  }
44184
43889
  /**
44185
- * Submits a file permission transaction and returns the transaction hash immediately.
43890
+ * Submits a file permission transaction to the blockchain.
44186
43891
  *
44187
- * This is the lower-level method that provides maximum control over transaction timing.
43892
+ * @remarks
43893
+ * This method supports gasless transactions via relayer callbacks when configured.
43894
+ * It encrypts the user's encryption key with the recipient's public key before submission.
44188
43895
  * Use this when you want to handle transaction confirmation and event parsing separately.
44189
43896
  *
44190
- * @param fileId - The ID of the file to add permissions for
44191
- * @param account - The address of the account to grant permission to
44192
- * @param publicKey - The public key to encrypt the user's encryption key with
44193
- * @returns Promise resolving to the transaction hash
43897
+ * @param fileId - The ID of the file to grant permission for
43898
+ * @param account - The recipient's wallet address that will access the file
43899
+ * @param publicKey - The recipient's public key for encryption.
43900
+ * Obtain via `vana.server.getIdentity(account).public_key`
43901
+ * @returns Promise resolving to TransactionHandle for tracking the transaction
43902
+ * @throws {Error} When chain ID is not available
43903
+ * @throws {Error} When encryption key generation fails
43904
+ * @throws {Error} When public key encryption fails
43905
+ *
44194
43906
  * @example
44195
43907
  * ```typescript
44196
- * const txHash = await vana.data.submitFilePermission(fileId, account, publicKey);
44197
- * console.log(`Transaction submitted: ${txHash}`);
43908
+ * const tx = await vana.data.submitFilePermission(
43909
+ * fileId,
43910
+ * "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36",
43911
+ * recipientPublicKey
43912
+ * );
43913
+ * const result = await tx.waitForEvents();
43914
+ * console.log(`Permission granted with ID: ${result.permissionId}`);
44198
43915
  * ```
44199
43916
  */
44200
43917
  async submitFilePermission(fileId, account, publicKey) {
@@ -44478,10 +44195,10 @@ var DataController = class {
44478
44195
  );
44479
44196
  }
44480
44197
  /**
44481
- * Validates a data schema against the Vana meta-schema.
44198
+ * Validates a data schema definition against the Vana meta-schema.
44482
44199
  *
44483
- * @param schema - The data schema to validate
44484
- * @returns Assertion that schema is valid (throws if invalid)
44200
+ * @param schema - The data schema definition to validate
44201
+ * @returns The validated DataSchema
44485
44202
  * @throws SchemaValidationError if invalid
44486
44203
  * @example
44487
44204
  * ```typescript
@@ -44498,11 +44215,11 @@ var DataController = class {
44498
44215
  * }
44499
44216
  * };
44500
44217
  *
44501
- * vana.data.validateDataSchema(schema);
44218
+ * const validatedSchema = vana.data.validateDataSchemaAgainstMetaSchema(schema);
44502
44219
  * ```
44503
44220
  */
44504
- validateDataSchema(schema) {
44505
- return validateDataSchema(schema);
44221
+ validateDataSchemaAgainstMetaSchema(schema) {
44222
+ return validateDataSchemaAgainstMetaSchema(schema);
44506
44223
  }
44507
44224
  /**
44508
44225
  * Validates data against a JSON Schema from a data schema.
@@ -44535,9 +44252,9 @@ var DataController = class {
44535
44252
  return validateDataAgainstSchema(data, schema);
44536
44253
  }
44537
44254
  /**
44538
- * Fetches and validates a schema from a URL, then returns the parsed data schema.
44255
+ * Fetches and validates a data schema from a URL, then returns the parsed data schema.
44539
44256
  *
44540
- * @param url - The URL to fetch the schema from
44257
+ * @param url - The URL to fetch the data schema from
44541
44258
  * @returns The validated data schema
44542
44259
  * @throws SchemaValidationError if invalid or fetch fails
44543
44260
  * @example
@@ -45729,7 +45446,7 @@ var GoogleDriveStorage = class {
45729
45446
  };
45730
45447
 
45731
45448
  // src/storage/providers/ipfs.ts
45732
- init_encoding();
45449
+ init_crypto_utils();
45733
45450
  var IpfsStorage = class _IpfsStorage {
45734
45451
  constructor(config) {
45735
45452
  this.config = config;
@@ -45769,9 +45486,8 @@ var IpfsStorage = class _IpfsStorage {
45769
45486
  * ```
45770
45487
  */
45771
45488
  static forInfura(credentials) {
45772
- const encoder = new TextEncoder();
45773
45489
  const auth = toBase64(
45774
- encoder.encode(`${credentials.projectId}:${credentials.projectSecret}`)
45490
+ `${credentials.projectId}:${credentials.projectSecret}`
45775
45491
  );
45776
45492
  return new _IpfsStorage({
45777
45493
  apiEndpoint: "https://ipfs.infura.io:5001/api/v0/add",
@@ -46631,7 +46347,7 @@ var vanaMainnet2 = {
46631
46347
  url: "https://vanascan.io"
46632
46348
  }
46633
46349
  },
46634
- subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/vana/7.0.7/gn"
46350
+ subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/vana/prod/gn"
46635
46351
  };
46636
46352
  var moksha = {
46637
46353
  id: 14800,
@@ -46652,7 +46368,7 @@ var moksha = {
46652
46368
  url: "https://moksha.vanascan.io"
46653
46369
  }
46654
46370
  },
46655
- subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/moksha/7.0.7/gn"
46371
+ subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/moksha/prod/gn"
46656
46372
  };
46657
46373
  function getChainConfig(chainId) {
46658
46374
  switch (chainId) {
@@ -47681,7 +47397,7 @@ async function handleRelayerRequest(sdk, payload) {
47681
47397
 
47682
47398
  // src/index.node.ts
47683
47399
  init_transactionHandle();
47684
- init_browser2();
47400
+ init_browser();
47685
47401
 
47686
47402
  // src/platform/utils.ts
47687
47403
  function detectPlatform() {
@@ -47706,7 +47422,7 @@ async function createPlatformAdapter() {
47706
47422
  const { NodePlatformAdapter: NodePlatformAdapter2 } = await import(moduleName);
47707
47423
  return new NodePlatformAdapter2();
47708
47424
  } else {
47709
- const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser2(), browser_exports));
47425
+ const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser(), browser_exports));
47710
47426
  return new BrowserPlatformAdapter2();
47711
47427
  }
47712
47428
  } catch (error) {
@@ -47727,7 +47443,7 @@ async function createPlatformAdapterFor(platformType) {
47727
47443
  const { NodePlatformAdapter: NodePlatformAdapter2 } = await import(moduleName);
47728
47444
  return new NodePlatformAdapter2();
47729
47445
  } else {
47730
- const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser2(), browser_exports));
47446
+ const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser(), browser_exports));
47731
47447
  return new BrowserPlatformAdapter2();
47732
47448
  }
47733
47449
  } catch (error) {
@@ -47754,7 +47470,7 @@ function getPlatformCapabilities() {
47754
47470
  }
47755
47471
 
47756
47472
  // src/platform/browser-safe.ts
47757
- init_browser2();
47473
+ init_browser();
47758
47474
  async function createNodePlatformAdapter() {
47759
47475
  if (typeof window !== "undefined") {
47760
47476
  throw new Error(
@@ -48200,7 +47916,7 @@ var index_node_default = Vana;
48200
47916
  storeGrantFile,
48201
47917
  summarizeGrant,
48202
47918
  validateDataAgainstSchema,
48203
- validateDataSchema,
47919
+ validateDataSchemaAgainstMetaSchema,
48204
47920
  validateGrant,
48205
47921
  validateGrantExpiry,
48206
47922
  validateGrantFile,