@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
@@ -10,6 +10,53 @@ var __export = (target, all) => {
10
10
  };
11
11
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
12
12
 
13
+ // src/platform/shared/crypto-utils.ts
14
+ function processWalletPublicKey(publicKey) {
15
+ const publicKeyHex = publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey;
16
+ const publicKeyBytes = Buffer.from(publicKeyHex, "hex");
17
+ return publicKeyBytes.length === 64 ? Buffer.concat([Buffer.from([4]), publicKeyBytes]) : publicKeyBytes;
18
+ }
19
+ function processWalletPrivateKey(privateKey) {
20
+ const privateKeyHex = privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey;
21
+ return Buffer.from(privateKeyHex, "hex");
22
+ }
23
+ function parseEncryptedDataBuffer(encryptedBuffer) {
24
+ return {
25
+ iv: encryptedBuffer.slice(0, 16),
26
+ ephemPublicKey: encryptedBuffer.slice(16, 81),
27
+ // 65 bytes for uncompressed public key
28
+ ciphertext: encryptedBuffer.slice(81, -32),
29
+ mac: encryptedBuffer.slice(-32)
30
+ };
31
+ }
32
+ function toBase64(str) {
33
+ if (typeof Buffer !== "undefined") {
34
+ return Buffer.from(str, "utf8").toString("base64");
35
+ } else if (typeof btoa !== "undefined") {
36
+ return btoa(str);
37
+ } else {
38
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
39
+ let result = "";
40
+ let i = 0;
41
+ while (i < str.length) {
42
+ const a = str.charCodeAt(i++);
43
+ const b = i < str.length ? str.charCodeAt(i++) : 0;
44
+ const c = i < str.length ? str.charCodeAt(i++) : 0;
45
+ const bitmap = a << 16 | b << 8 | c;
46
+ result += chars.charAt(bitmap >> 18 & 63);
47
+ result += chars.charAt(bitmap >> 12 & 63);
48
+ result += i - 2 < str.length ? chars.charAt(bitmap >> 6 & 63) : "=";
49
+ result += i - 1 < str.length ? chars.charAt(bitmap & 63) : "=";
50
+ }
51
+ return result;
52
+ }
53
+ }
54
+ var init_crypto_utils = __esm({
55
+ "src/platform/shared/crypto-utils.ts"() {
56
+ "use strict";
57
+ }
58
+ });
59
+
13
60
  // src/platform/shared/pgp-utils.ts
14
61
  function processPGPKeyOptions(options) {
15
62
  return {
@@ -71,823 +118,118 @@ var init_lazy_import = __esm({
71
118
  }
72
119
  });
73
120
 
74
- // src/utils/encoding.ts
75
- function toBase64(data) {
76
- if (typeof Buffer !== "undefined" && Buffer.from) {
77
- return Buffer.from(data).toString("base64");
78
- }
79
- if (typeof btoa !== "undefined") {
80
- const binary = Array.from(data, (byte) => String.fromCharCode(byte)).join(
81
- ""
82
- );
83
- return btoa(binary);
84
- }
85
- throw new Error("No base64 encoding method available in this environment");
86
- }
87
- function toHex(data) {
88
- if (typeof Buffer !== "undefined" && Buffer.from) {
89
- return Buffer.from(data).toString("hex");
90
- }
91
- return Array.from(data, (byte) => byte.toString(16).padStart(2, "0")).join(
92
- ""
93
- );
94
- }
95
- function fromHex(hex) {
96
- const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
97
- if (cleanHex.length % 2 !== 0) {
98
- throw new Error("Invalid hex string: odd length");
99
- }
100
- if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {
101
- throw new Error("Invalid hex string: contains non-hex characters");
102
- }
103
- if (typeof Buffer !== "undefined" && Buffer.from) {
104
- return new Uint8Array(Buffer.from(cleanHex, "hex"));
105
- }
106
- const bytes = new Uint8Array(cleanHex.length / 2);
107
- for (let i = 0; i < cleanHex.length; i += 2) {
108
- bytes[i / 2] = parseInt(cleanHex.substr(i, 2), 16);
109
- }
110
- return bytes;
111
- }
112
- function stringToBytes(str) {
113
- if (typeof Buffer !== "undefined" && Buffer.from) {
114
- return new Uint8Array(Buffer.from(str, "utf8"));
115
- }
116
- if (typeof TextEncoder !== "undefined") {
117
- return new TextEncoder().encode(str);
118
- }
119
- const bytes = [];
120
- for (let i = 0; i < str.length; i++) {
121
- const char = str.charCodeAt(i);
122
- if (char < 128) {
123
- bytes.push(char);
124
- } else if (char < 2048) {
125
- bytes.push(192 | char >> 6, 128 | char & 63);
126
- } else if (char < 55296 || char >= 57344) {
127
- bytes.push(
128
- 224 | char >> 12,
129
- 128 | char >> 6 & 63,
130
- 128 | char & 63
131
- );
132
- } else {
133
- i++;
134
- const char2 = str.charCodeAt(i);
135
- const codePoint = 65536 + ((char & 1023) << 10 | char2 & 1023);
136
- bytes.push(
137
- 240 | codePoint >> 18,
138
- 128 | codePoint >> 12 & 63,
139
- 128 | codePoint >> 6 & 63,
140
- 128 | codePoint & 63
141
- );
142
- }
143
- }
144
- return new Uint8Array(bytes);
145
- }
146
- function bytesToString(bytes) {
147
- if (typeof Buffer !== "undefined" && Buffer.from) {
148
- return Buffer.from(bytes).toString("utf8");
149
- }
150
- if (typeof TextDecoder !== "undefined") {
151
- return new TextDecoder().decode(bytes);
152
- }
153
- let str = "";
154
- let i = 0;
155
- while (i < bytes.length) {
156
- const byte = bytes[i];
157
- if (byte < 128) {
158
- str += String.fromCharCode(byte);
159
- i++;
160
- } else if ((byte & 224) === 192) {
161
- str += String.fromCharCode((byte & 31) << 6 | bytes[i + 1] & 63);
162
- i += 2;
163
- } else if ((byte & 240) === 224) {
164
- str += String.fromCharCode(
165
- (byte & 15) << 12 | (bytes[i + 1] & 63) << 6 | bytes[i + 2] & 63
166
- );
167
- i += 3;
168
- } else {
169
- const codePoint = ((byte & 7) << 18 | (bytes[i + 1] & 63) << 12 | (bytes[i + 2] & 63) << 6 | bytes[i + 3] & 63) - 65536;
170
- str += String.fromCharCode(
171
- 55296 + (codePoint >> 10),
172
- 56320 + (codePoint & 1023)
173
- );
174
- i += 4;
175
- }
176
- }
177
- return str;
178
- }
179
- var init_encoding = __esm({
180
- "src/utils/encoding.ts"() {
181
- "use strict";
182
- }
183
- });
184
-
185
- // src/utils/crypto-utils.ts
186
- function concatBytes(...arrays) {
187
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
188
- const result = new Uint8Array(totalLength);
189
- let offset = 0;
190
- for (const arr of arrays) {
191
- result.set(arr, offset);
192
- offset += arr.length;
193
- }
194
- return result;
195
- }
196
- function hexToBytes(hex) {
197
- return fromHex(hex);
198
- }
199
- function bytesToHex(bytes) {
200
- return toHex(bytes);
201
- }
202
- function processWalletPublicKey(publicKey) {
203
- const publicKeyHex = typeof publicKey === "string" ? publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey : bytesToHex(publicKey);
204
- const publicKeyBytes = hexToBytes(publicKeyHex);
205
- return publicKeyBytes.length === 64 ? concatBytes(new Uint8Array([4]), publicKeyBytes) : publicKeyBytes;
206
- }
207
- function processWalletPrivateKey(privateKey) {
208
- const privateKeyHex = typeof privateKey === "string" ? privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey : bytesToHex(privateKey);
209
- return hexToBytes(privateKeyHex);
210
- }
211
- function parseEncryptedDataBuffer(encryptedBuffer) {
212
- return {
213
- iv: encryptedBuffer.slice(0, 16),
214
- ephemPublicKey: encryptedBuffer.slice(16, 81),
215
- // 65 bytes for uncompressed public key
216
- ciphertext: encryptedBuffer.slice(81, -32),
217
- mac: encryptedBuffer.slice(-32)
218
- };
219
- }
220
- var init_crypto_utils = __esm({
221
- "src/utils/crypto-utils.ts"() {
222
- "use strict";
223
- init_encoding();
224
- }
225
- });
226
-
227
- // src/crypto/services/WalletKeyEncryptionService.ts
228
- var WalletKeyEncryptionService;
229
- var init_WalletKeyEncryptionService = __esm({
230
- "src/crypto/services/WalletKeyEncryptionService.ts"() {
231
- "use strict";
232
- init_crypto_utils();
233
- init_encoding();
234
- WalletKeyEncryptionService = class {
235
- constructor(config) {
236
- __publicField(this, "eciesProvider");
237
- this.eciesProvider = config.eciesProvider;
238
- }
239
- /**
240
- * Encrypts data using a wallet's public key.
241
- *
242
- * @param data - The plaintext message to encrypt for the wallet owner.
243
- * @param publicKey - The recipient wallet's public key for encryption.
244
- * @returns A promise that resolves to the encrypted data as a hex string.
245
- * @throws {Error} When encryption fails due to invalid key format.
246
- *
247
- * @example
248
- * ```typescript
249
- * const encrypted = await processor.encryptWithWalletPublicKey(
250
- * "Secret message",
251
- * "0x04..." // 65-byte uncompressed public key
252
- * );
253
- * console.log(`Encrypted: ${encrypted}`);
254
- * ```
255
- */
256
- async encryptWithWalletPublicKey(data, publicKey) {
257
- const publicKeyBytes = processWalletPublicKey(publicKey);
258
- const dataBytes = stringToBytes(data);
259
- const encrypted = await this.eciesProvider.encrypt(
260
- publicKeyBytes,
261
- dataBytes
262
- );
263
- const result = concatBytes(
264
- encrypted.iv,
265
- encrypted.ephemPublicKey,
266
- encrypted.ciphertext,
267
- encrypted.mac
268
- );
269
- return bytesToHex(result);
270
- }
271
- /**
272
- * Decrypts data using a wallet's private key.
273
- *
274
- * @param encryptedData - The hex-encoded encrypted data to decrypt.
275
- * @param privateKey - The wallet's private key for decryption.
276
- * @returns A promise that resolves to the decrypted plaintext message.
277
- * @throws {Error} When decryption fails due to invalid data or key format.
278
- *
279
- * @example
280
- * ```typescript
281
- * const decrypted = await processor.decryptWithWalletPrivateKey(
282
- * encryptedHexString,
283
- * "0x..." // 32-byte private key
284
- * );
285
- * console.log(`Decrypted: ${decrypted}`);
286
- * ```
287
- */
288
- async decryptWithWalletPrivateKey(encryptedData, privateKey) {
289
- const privateKeyBytes = processWalletPrivateKey(privateKey);
290
- const encryptedBytes = hexToBytes(encryptedData);
291
- const encrypted = parseEncryptedDataBuffer(encryptedBytes);
292
- const decrypted = await this.eciesProvider.decrypt(
293
- privateKeyBytes,
294
- encrypted
295
- );
296
- return bytesToString(decrypted);
297
- }
298
- /**
299
- * Encrypts a Uint8Array with a wallet public key
300
- *
301
- * @param data - Binary data to encrypt
302
- * @param publicKey - Public key as hex string or Uint8Array
303
- * @returns Encrypted data structure
304
- */
305
- async encryptBinary(data, publicKey) {
306
- const publicKeyBytes = processWalletPublicKey(publicKey);
307
- return this.eciesProvider.encrypt(publicKeyBytes, data);
308
- }
309
- /**
310
- * Decrypts to a Uint8Array with a wallet private key
311
- *
312
- * @param encrypted - Encrypted data structure
313
- * @param privateKey - Private key as hex string or Uint8Array
314
- * @returns Decrypted binary data
315
- */
316
- async decryptBinary(encrypted, privateKey) {
317
- const privateKeyBytes = processWalletPrivateKey(privateKey);
318
- return this.eciesProvider.decrypt(privateKeyBytes, encrypted);
319
- }
320
- /**
321
- * Gets the underlying ECIES provider
322
- *
323
- * @returns The ECIES provider instance
324
- */
325
- getECIESProvider() {
326
- return this.eciesProvider;
327
- }
328
- };
329
- }
330
- });
331
-
332
- // src/crypto/ecies/utils.ts
333
- function hexToBytes2(hex) {
334
- if (hex.length % 2 !== 0) {
335
- throw new Error("Hex string must have even length");
336
- }
337
- const bytes = new Uint8Array(hex.length / 2);
338
- for (let i = 0; i < hex.length; i += 2) {
339
- bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
340
- }
341
- return bytes;
342
- }
343
- function bytesToHex2(bytes) {
344
- return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
345
- }
346
- function stringToBytes2(str) {
347
- return new TextEncoder().encode(str);
348
- }
349
- function bytesToString2(bytes) {
350
- return new TextDecoder().decode(bytes);
351
- }
352
- function concatBytes2(...arrays) {
353
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
354
- const result = new Uint8Array(totalLength);
355
- let offset = 0;
356
- for (const arr of arrays) {
357
- result.set(arr, offset);
358
- offset += arr.length;
359
- }
360
- return result;
361
- }
362
- function constantTimeEqual(a, b) {
363
- if (a.length !== b.length) return false;
364
- let result = 0;
365
- for (let i = 0; i < a.length; i++) {
366
- result |= a[i] ^ b[i];
367
- }
368
- return result === 0;
369
- }
370
- var init_utils = __esm({
371
- "src/crypto/ecies/utils.ts"() {
372
- "use strict";
373
- }
374
- });
375
-
376
- // src/crypto/ecies/constants.ts
377
- var CURVE, CIPHER, KDF, MAC, FORMAT;
378
- var init_constants = __esm({
379
- "src/crypto/ecies/constants.ts"() {
380
- "use strict";
381
- CURVE = {
382
- /** The elliptic curve used (secp256k1 - same as Bitcoin/Ethereum) */
383
- name: "secp256k1",
384
- /** Private key length in bytes */
385
- PRIVATE_KEY_LENGTH: 32,
386
- /** Compressed public key length in bytes (0x02 or 0x03 prefix + 32 bytes) */
387
- COMPRESSED_PUBLIC_KEY_LENGTH: 33,
388
- /** Uncompressed public key length in bytes (0x04 prefix + 64 bytes) */
389
- UNCOMPRESSED_PUBLIC_KEY_LENGTH: 65,
390
- /** ECDH shared secret X coordinate length */
391
- SHARED_SECRET_LENGTH: 32,
392
- /** Public key prefixes */
393
- PREFIX: {
394
- /** Uncompressed public key prefix */
395
- UNCOMPRESSED: 4,
396
- /** Compressed public key prefix for even Y */
397
- COMPRESSED_EVEN: 2,
398
- /** Compressed public key prefix for odd Y */
399
- COMPRESSED_ODD: 3
400
- },
401
- /** X coordinate starts at byte 1 (after prefix) */
402
- X_COORDINATE_OFFSET: 1,
403
- /** X coordinate ends at byte 33 (1 + 32) */
404
- X_COORDINATE_END: 33
405
- };
406
- CIPHER = {
407
- /** Cipher algorithm - must match eccrypto */
408
- algorithm: "aes-256-cbc",
409
- /** AES key length in bytes */
410
- KEY_LENGTH: 32,
411
- /** Initialization vector length in bytes */
412
- IV_LENGTH: 16,
413
- /** Block size for AES */
414
- BLOCK_SIZE: 16
415
- };
416
- KDF = {
417
- /** Hash algorithm for key derivation - must match eccrypto */
418
- algorithm: "sha512",
419
- /** Output length of SHA-512 in bytes */
420
- OUTPUT_LENGTH: 64,
421
- /** Encryption key slice (first 32 bytes of KDF output) */
422
- ENCRYPTION_KEY_OFFSET: 0,
423
- ENCRYPTION_KEY_LENGTH: 32,
424
- /** MAC key slice (last 32 bytes of KDF output) */
425
- MAC_KEY_OFFSET: 32,
426
- MAC_KEY_LENGTH: 32
427
- };
428
- MAC = {
429
- /** MAC algorithm - must match eccrypto */
430
- algorithm: "sha256",
431
- /** HMAC-SHA256 output length in bytes */
432
- LENGTH: 32
433
- };
434
- FORMAT = {
435
- /** Offsets for each component in serialized format */
436
- IV_OFFSET: 0,
437
- IV_LENGTH: CIPHER.IV_LENGTH,
438
- /** Ephemeral public key (always uncompressed in eccrypto format) */
439
- EPHEMERAL_KEY_OFFSET: CIPHER.IV_LENGTH,
440
- EPHEMERAL_KEY_LENGTH: CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
441
- /** Ciphertext starts after IV and ephemeral key */
442
- CIPHERTEXT_OFFSET: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
443
- /** MAC is always the last 32 bytes */
444
- MAC_LENGTH: MAC.LENGTH,
445
- /** Minimum size of encrypted data (IV + ephemKey + MAC, no ciphertext) */
446
- MIN_ENCRYPTED_LENGTH: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + MAC.LENGTH,
447
- /**
448
- * Helper to calculate total length of encrypted data
449
- *
450
- * @param ciphertextLength - Length of the ciphertext portion
451
- * @returns Total length including all components
452
- */
453
- getTotalLength: (ciphertextLength) => CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + ciphertextLength + MAC.LENGTH
454
- };
455
- }
456
- });
457
-
458
- // src/crypto/ecies/interface.ts
459
- function isECIESEncrypted(obj) {
460
- if (!obj || typeof obj !== "object") return false;
461
- const enc = obj;
462
- const isUint8Array = (value) => {
463
- return value instanceof Uint8Array || typeof Buffer !== "undefined" && Buffer.isBuffer(value);
464
- };
465
- return isUint8Array(enc.iv) && enc.iv.length === CIPHER.IV_LENGTH && isUint8Array(enc.ephemPublicKey) && (enc.ephemPublicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH || enc.ephemPublicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) && isUint8Array(enc.ciphertext) && enc.ciphertext.length > 0 && isUint8Array(enc.mac) && enc.mac.length === MAC.LENGTH;
466
- }
467
- var ECIESError;
468
- var init_interface = __esm({
469
- "src/crypto/ecies/interface.ts"() {
470
- "use strict";
471
- init_constants();
472
- ECIESError = class extends Error {
473
- constructor(message, code, cause) {
474
- super(message);
475
- this.code = code;
476
- this.cause = cause;
477
- this.name = "ECIESError";
478
- }
479
- };
480
- }
481
- });
482
-
483
- // src/crypto/ecies/base.ts
484
- var _BaseECIESUint8, BaseECIESUint8;
485
- var init_base = __esm({
486
- "src/crypto/ecies/base.ts"() {
487
- "use strict";
488
- init_interface();
489
- init_constants();
490
- init_utils();
491
- _BaseECIESUint8 = class _BaseECIESUint8 {
492
- /**
493
- * Normalizes a public key to uncompressed format.
494
- *
495
- * @param publicKey - Public key in any format.
496
- * @returns Uncompressed public key (65 bytes).
497
- * @throws {ECIESError} If key format is invalid.
498
- */
499
- normalizePublicKey(publicKey) {
500
- if (_BaseECIESUint8.validatedKeys.has(publicKey)) {
501
- return publicKey;
502
- }
503
- if (publicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH) {
504
- if (publicKey[0] !== CURVE.PREFIX.UNCOMPRESSED) {
505
- throw new ECIESError(
506
- "Invalid uncompressed public key prefix",
507
- "INVALID_KEY"
508
- );
509
- }
510
- if (!this.validatePublicKey(publicKey)) {
511
- throw new ECIESError("Invalid public key", "INVALID_KEY");
512
- }
513
- _BaseECIESUint8.validatedKeys.set(publicKey, true);
514
- return publicKey;
515
- }
516
- if (publicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) {
517
- const decompressed = this.decompressPublicKey(publicKey);
518
- if (!decompressed) {
519
- throw new ECIESError("Failed to decompress public key", "INVALID_KEY");
520
- }
521
- _BaseECIESUint8.validatedKeys.set(decompressed, true);
522
- return decompressed;
523
- }
524
- throw new ECIESError(
525
- `Invalid public key length: ${publicKey.length}`,
526
- "INVALID_KEY"
527
- );
528
- }
529
- /**
530
- * Encrypts data using ECIES.
531
- *
532
- * @param publicKey - The recipient's public key (compressed or uncompressed)
533
- * @param message - The data to encrypt
534
- * @returns Promise resolving to encrypted data structure
535
- */
536
- async encrypt(publicKey, message) {
537
- try {
538
- if (!(publicKey instanceof Uint8Array)) {
539
- throw new ECIESError("Public key must be a Uint8Array", "INVALID_KEY");
540
- }
541
- if (!(message instanceof Uint8Array)) {
542
- throw new ECIESError(
543
- "Message must be a Uint8Array",
544
- "ENCRYPTION_FAILED"
545
- );
546
- }
547
- if (publicKey.length === 0) {
548
- throw new ECIESError("Public key cannot be empty", "INVALID_KEY");
549
- }
550
- const pubKey = this.normalizePublicKey(publicKey);
551
- let ephemeralPrivateKey;
552
- do {
553
- ephemeralPrivateKey = this.generateRandomBytes(
554
- CURVE.PRIVATE_KEY_LENGTH
555
- );
556
- } while (!this.verifyPrivateKey(ephemeralPrivateKey));
557
- const ephemeralPublicKey = this.createPublicKey(
558
- ephemeralPrivateKey,
559
- false
560
- );
561
- if (!ephemeralPublicKey) {
562
- throw new ECIESError(
563
- "Failed to generate ephemeral public key",
564
- "ENCRYPTION_FAILED"
565
- );
566
- }
567
- const sharedSecret = this.performECDH(pubKey, ephemeralPrivateKey);
568
- const kdf = this.sha512(sharedSecret);
569
- const encryptionKey = kdf.slice(
570
- KDF.ENCRYPTION_KEY_OFFSET,
571
- KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
572
- );
573
- const macKey = kdf.slice(
574
- KDF.MAC_KEY_OFFSET,
575
- KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
576
- );
577
- const iv = this.generateRandomBytes(CIPHER.IV_LENGTH);
578
- const ciphertext = await this.aesEncrypt(encryptionKey, iv, message);
579
- const macData = concatBytes2(iv, ephemeralPublicKey, ciphertext);
580
- const mac = this.hmacSha256(macKey, macData);
581
- this.clearBuffer(ephemeralPrivateKey);
582
- this.clearBuffer(sharedSecret);
583
- this.clearBuffer(kdf);
584
- return {
585
- iv,
586
- ephemPublicKey: ephemeralPublicKey,
587
- ciphertext,
588
- mac
589
- };
590
- } catch (error) {
591
- if (error instanceof ECIESError) throw error;
592
- throw new ECIESError(
593
- `Encryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
594
- "ENCRYPTION_FAILED",
595
- error instanceof Error ? error : void 0
596
- );
597
- }
598
- }
599
- /**
600
- * Decrypts ECIES encrypted data.
601
- *
602
- * @param privateKey - The recipient's private key (32 bytes)
603
- * @param encrypted - The encrypted data structure from encrypt()
604
- * @returns Promise resolving to the original plaintext
605
- */
606
- async decrypt(privateKey, encrypted) {
607
- try {
608
- if (!(privateKey instanceof Uint8Array)) {
609
- throw new ECIESError("Private key must be a Uint8Array", "INVALID_KEY");
610
- }
611
- if (!isECIESEncrypted(encrypted)) {
612
- throw new ECIESError(
613
- "Invalid encrypted data structure",
614
- "DECRYPTION_FAILED"
615
- );
616
- }
617
- if (privateKey.length !== CURVE.PRIVATE_KEY_LENGTH) {
618
- throw new ECIESError(
619
- `Invalid private key length: ${privateKey.length}`,
620
- "INVALID_KEY"
621
- );
622
- }
623
- if (!this.verifyPrivateKey(privateKey)) {
624
- throw new ECIESError("Invalid private key", "INVALID_KEY");
625
- }
626
- const ephemeralPublicKey = this.normalizePublicKey(
627
- encrypted.ephemPublicKey
628
- );
629
- const sharedSecret = this.performECDH(ephemeralPublicKey, privateKey);
630
- const kdf = this.sha512(sharedSecret);
631
- const encryptionKey = kdf.slice(
632
- KDF.ENCRYPTION_KEY_OFFSET,
633
- KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
634
- );
635
- const macKey = kdf.slice(
636
- KDF.MAC_KEY_OFFSET,
637
- KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
638
- );
639
- const macData = concatBytes2(
640
- encrypted.iv,
641
- encrypted.ephemPublicKey,
642
- encrypted.ciphertext
643
- );
644
- const expectedMac = this.hmacSha256(macKey, macData);
645
- if (!constantTimeEqual(encrypted.mac, expectedMac)) {
646
- throw new ECIESError("MAC verification failed", "MAC_MISMATCH");
647
- }
648
- const decrypted = await this.aesDecrypt(
649
- encryptionKey,
650
- encrypted.iv,
651
- encrypted.ciphertext
652
- );
653
- this.clearBuffer(sharedSecret);
654
- this.clearBuffer(kdf);
655
- return decrypted;
656
- } catch (error) {
657
- if (error instanceof ECIESError) throw error;
658
- throw new ECIESError(
659
- `Decryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
660
- "DECRYPTION_FAILED",
661
- error instanceof Error ? error : void 0
662
- );
663
- }
664
- }
665
- /**
666
- * Clears sensitive data from memory using multi-pass overwrite.
667
- *
668
- * @remarks
669
- * Uses multiple passes with different patterns to make it harder
670
- * for JIT compilers to optimize away the operation. While not
671
- * guaranteed in JavaScript, this is a best-effort approach to
672
- * clear sensitive data from memory.
673
- *
674
- * @param buffer - The buffer to clear
675
- */
676
- clearBuffer(buffer) {
677
- if (buffer && buffer.length > 0) {
678
- buffer.fill(0);
679
- buffer.fill(255);
680
- buffer.fill(170);
681
- buffer.fill(0);
682
- for (let i = 0; i < buffer.length; i++) {
683
- buffer[i] = i & 255 ^ 90;
684
- }
685
- buffer.fill(0);
686
- }
687
- }
688
- };
689
- // Cache for validated public keys to avoid repeated validation
690
- __publicField(_BaseECIESUint8, "validatedKeys", /* @__PURE__ */ new WeakMap());
691
- BaseECIESUint8 = _BaseECIESUint8;
692
- }
693
- });
694
-
695
- // src/crypto/ecies/browser.ts
696
- import * as secp256k1 from "@noble/secp256k1";
697
- import { hmac } from "@noble/hashes/hmac";
698
- import { sha256, sha512 as nobleSha512 } from "@noble/hashes/sha2";
699
- var BrowserECIESUint8Provider;
700
- var init_browser = __esm({
701
- "src/crypto/ecies/browser.ts"() {
702
- "use strict";
703
- init_base();
704
- BrowserECIESUint8Provider = class extends BaseECIESUint8 {
705
- generateRandomBytes(length) {
706
- const bytes = new Uint8Array(length);
707
- crypto.getRandomValues(bytes);
708
- return bytes;
709
- }
710
- verifyPrivateKey(privateKey) {
711
- try {
712
- return secp256k1.utils.isValidPrivateKey(privateKey);
713
- } catch {
714
- return false;
715
- }
716
- }
717
- createPublicKey(privateKey, compressed) {
718
- try {
719
- return secp256k1.getPublicKey(privateKey, compressed);
720
- } catch {
721
- return null;
722
- }
723
- }
724
- validatePublicKey(publicKey) {
725
- try {
726
- secp256k1.Point.fromHex(publicKey);
727
- return true;
728
- } catch {
729
- return false;
730
- }
731
- }
732
- decompressPublicKey(publicKey) {
733
- try {
734
- const point = secp256k1.Point.fromHex(publicKey);
735
- return point.toRawBytes(false);
736
- } catch {
737
- return null;
738
- }
739
- }
740
- performECDH(publicKey, privateKey) {
741
- try {
742
- const sharedPoint = secp256k1.getSharedSecret(
743
- privateKey,
744
- publicKey,
745
- true
746
- );
747
- return sharedPoint.slice(1);
748
- } catch (error) {
749
- throw new Error(
750
- `ECDH failed: ${error instanceof Error ? error.message : "Unknown error"}`
751
- );
752
- }
753
- }
754
- sha512(data) {
755
- return nobleSha512(data);
756
- }
757
- hmacSha256(key, data) {
758
- return hmac(sha256, key, data);
759
- }
760
- async aesEncrypt(key, iv, plaintext) {
761
- const cryptoKey = await crypto.subtle.importKey(
762
- "raw",
763
- key,
764
- { name: "AES-CBC" },
765
- false,
766
- ["encrypt"]
767
- );
768
- const encrypted = await crypto.subtle.encrypt(
769
- { name: "AES-CBC", iv },
770
- cryptoKey,
771
- plaintext
772
- );
773
- return new Uint8Array(encrypted);
774
- }
775
- async aesDecrypt(key, iv, ciphertext) {
776
- const cryptoKey = await crypto.subtle.importKey(
777
- "raw",
778
- key,
779
- { name: "AES-CBC" },
780
- false,
781
- ["decrypt"]
782
- );
783
- const decrypted = await crypto.subtle.decrypt(
784
- { name: "AES-CBC", iv },
785
- cryptoKey,
786
- ciphertext
787
- );
788
- return new Uint8Array(decrypted);
789
- }
790
- };
791
- }
792
- });
793
-
794
121
  // src/platform/browser.ts
795
- import * as secp256k12 from "@noble/secp256k1";
796
- var getOpenPGP, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter;
797
- var init_browser2 = __esm({
122
+ var getOpenPGP, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter, browserPlatformAdapter;
123
+ var init_browser = __esm({
798
124
  "src/platform/browser.ts"() {
799
125
  "use strict";
126
+ init_crypto_utils();
800
127
  init_pgp_utils();
801
128
  init_error_utils();
802
129
  init_lazy_import();
803
- init_WalletKeyEncryptionService();
804
- init_crypto_utils();
805
- init_utils();
806
- init_browser();
807
130
  getOpenPGP = lazyImport(() => import("openpgp"));
808
131
  BrowserCryptoAdapter = class {
809
- constructor() {
810
- __publicField(this, "eciesProvider", new BrowserECIESUint8Provider());
811
- __publicField(this, "walletKeyEncryptionService", new WalletKeyEncryptionService({
812
- eciesProvider: this.eciesProvider
813
- }));
814
- }
815
132
  async encryptWithPublicKey(data, publicKeyHex) {
816
133
  try {
817
- const publicKeyBytes = hexToBytes2(publicKeyHex);
818
- const encrypted = await this.eciesProvider.encrypt(
819
- publicKeyBytes,
820
- stringToBytes2(data)
134
+ const eccrypto = await import("eccrypto-js");
135
+ const publicKeyBuffer = Buffer.from(publicKeyHex, "hex");
136
+ const encrypted = await eccrypto.encrypt(
137
+ publicKeyBuffer,
138
+ Buffer.from(data, "utf8")
821
139
  );
822
- const result = concatBytes2(
140
+ const result = Buffer.concat([
823
141
  encrypted.iv,
824
142
  encrypted.ephemPublicKey,
825
143
  encrypted.ciphertext,
826
144
  encrypted.mac
827
- );
828
- return bytesToHex2(result);
145
+ ]);
146
+ return result.toString("hex");
829
147
  } catch (error) {
830
- throw wrapCryptoError("encryptWithPublicKey", error);
148
+ throw new Error(`Encryption failed: ${error}`);
831
149
  }
832
150
  }
833
151
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
834
152
  try {
835
- const encryptedBytes = hexToBytes2(encryptedData);
836
- const privateKeyBytes = hexToBytes2(privateKeyHex);
837
- const encrypted = parseEncryptedDataBuffer(encryptedBytes);
838
- const decrypted = await this.eciesProvider.decrypt(
839
- privateKeyBytes,
840
- encrypted
153
+ const eccrypto = await import("eccrypto-js");
154
+ const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
155
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
156
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
157
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
158
+ const decryptedBuffer = await eccrypto.decrypt(
159
+ privateKeyBuffer,
160
+ encryptedObj
841
161
  );
842
- return bytesToString2(decrypted);
162
+ return decryptedBuffer.toString("utf8");
843
163
  } catch (error) {
844
- throw wrapCryptoError("decryptWithPrivateKey", error);
164
+ throw new Error(`Decryption failed: ${error}`);
845
165
  }
846
166
  }
847
- async encryptWithWalletPublicKey(data, publicKey) {
167
+ async generateKeyPair() {
848
168
  try {
849
- return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
850
- data,
851
- publicKey
852
- );
169
+ const eccrypto = await import("eccrypto-js");
170
+ const privateKeyBytes = new Uint8Array(32);
171
+ crypto.getRandomValues(privateKeyBytes);
172
+ const privateKey = Buffer.from(privateKeyBytes);
173
+ const publicKey = eccrypto.getPublicCompressed(privateKey);
174
+ return {
175
+ privateKey: privateKey.toString("hex"),
176
+ publicKey: publicKey.toString("hex")
177
+ };
853
178
  } catch (error) {
854
- throw wrapCryptoError("encryptWithWalletPublicKey", error);
179
+ throw wrapCryptoError("key generation", error);
855
180
  }
856
181
  }
857
- async decryptWithWalletPrivateKey(encryptedData, privateKey) {
182
+ async encryptWithWalletPublicKey(data, publicKey) {
858
183
  try {
859
- return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
860
- encryptedData,
861
- privateKey
184
+ const eccrypto = await import("eccrypto-js");
185
+ const uncompressedKey = processWalletPublicKey(publicKey);
186
+ const encryptedBuffer = await eccrypto.encrypt(
187
+ uncompressedKey,
188
+ Buffer.from(data)
862
189
  );
190
+ const result = Buffer.concat([
191
+ encryptedBuffer.iv,
192
+ encryptedBuffer.ephemPublicKey,
193
+ encryptedBuffer.ciphertext,
194
+ encryptedBuffer.mac
195
+ ]);
196
+ return result.toString("hex");
863
197
  } catch (error) {
864
- throw wrapCryptoError("decryptWithWalletPrivateKey", error);
198
+ throw wrapCryptoError("encrypt with wallet public key", error);
865
199
  }
866
200
  }
867
- async generateKeyPair() {
201
+ async decryptWithWalletPrivateKey(encryptedData, privateKey) {
868
202
  try {
869
- const privateKeyBytes = secp256k12.utils.randomPrivateKey();
870
- const publicKeyBytes = secp256k12.getPublicKey(privateKeyBytes, true);
871
- return {
872
- privateKey: bytesToHex2(privateKeyBytes),
873
- publicKey: bytesToHex2(publicKeyBytes)
874
- };
203
+ const eccrypto = await import("eccrypto-js");
204
+ const privateKeyBuffer = processWalletPrivateKey(privateKey);
205
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
206
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
207
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
208
+ const decryptedBuffer = await eccrypto.decrypt(
209
+ privateKeyBuffer,
210
+ encryptedObj
211
+ );
212
+ return decryptedBuffer.toString("utf8");
875
213
  } catch (error) {
876
- throw wrapCryptoError("generateKeyPair", error);
214
+ throw wrapCryptoError("decrypt with wallet private key", error);
877
215
  }
878
216
  }
879
217
  async encryptWithPassword(data, password) {
880
218
  try {
881
219
  const openpgp = await getOpenPGP();
882
- const message = await openpgp.createMessage({ binary: data });
220
+ const message = await openpgp.createMessage({
221
+ binary: data
222
+ });
883
223
  const encrypted = await openpgp.encrypt({
884
224
  message,
885
225
  passwords: [password],
886
226
  format: "binary"
887
227
  });
888
- return new Uint8Array(encrypted);
228
+ const response = new Response(encrypted);
229
+ const arrayBuffer = await response.arrayBuffer();
230
+ return new Uint8Array(arrayBuffer);
889
231
  } catch (error) {
890
- throw wrapCryptoError("encryptWithPassword", error);
232
+ throw new Error(`Failed to encrypt with password: ${error}`);
891
233
  }
892
234
  }
893
235
  async decryptWithPassword(encryptedData, password) {
@@ -896,14 +238,14 @@ var init_browser2 = __esm({
896
238
  const message = await openpgp.readMessage({
897
239
  binaryMessage: encryptedData
898
240
  });
899
- const { data } = await openpgp.decrypt({
241
+ const { data: decrypted } = await openpgp.decrypt({
900
242
  message,
901
243
  passwords: [password],
902
244
  format: "binary"
903
245
  });
904
- return new Uint8Array(data);
246
+ return new Uint8Array(decrypted);
905
247
  } catch (error) {
906
- throw wrapCryptoError("decryptWithPassword", error);
248
+ throw new Error(`Failed to decrypt with password: ${error}`);
907
249
  }
908
250
  }
909
251
  };
@@ -955,6 +297,9 @@ var init_browser2 = __esm({
955
297
  };
956
298
  BrowserHttpAdapter = class {
957
299
  async fetch(url, options) {
300
+ if (typeof fetch === "undefined") {
301
+ throw new Error("Fetch API not available in this browser environment");
302
+ }
958
303
  return fetch(url, options);
959
304
  }
960
305
  };
@@ -974,19 +319,17 @@ var init_browser2 = __esm({
974
319
  }
975
320
  set(key, value) {
976
321
  try {
977
- if (typeof sessionStorage === "undefined") {
978
- return;
322
+ if (typeof sessionStorage !== "undefined") {
323
+ sessionStorage.setItem(this.prefix + key, value);
979
324
  }
980
- sessionStorage.setItem(this.prefix + key, value);
981
325
  } catch {
982
326
  }
983
327
  }
984
328
  delete(key) {
985
329
  try {
986
- if (typeof sessionStorage === "undefined") {
987
- return;
330
+ if (typeof sessionStorage !== "undefined") {
331
+ sessionStorage.removeItem(this.prefix + key);
988
332
  }
989
- sessionStorage.removeItem(this.prefix + key);
990
333
  } catch {
991
334
  }
992
335
  }
@@ -995,27 +338,30 @@ var init_browser2 = __esm({
995
338
  if (typeof sessionStorage === "undefined") {
996
339
  return;
997
340
  }
998
- const keysToRemove = [];
999
- for (let i = 0; i < sessionStorage.length; i++) {
1000
- const key = sessionStorage.key(i);
1001
- if (key?.startsWith(this.prefix)) {
1002
- keysToRemove.push(key);
341
+ const keys = Object.keys(sessionStorage);
342
+ for (const key of keys) {
343
+ if (key.startsWith(this.prefix)) {
344
+ sessionStorage.removeItem(key);
1003
345
  }
1004
346
  }
1005
- keysToRemove.forEach((key) => sessionStorage.removeItem(key));
1006
347
  } catch {
1007
348
  }
1008
349
  }
1009
350
  };
1010
351
  BrowserPlatformAdapter = class {
1011
352
  constructor() {
1012
- __publicField(this, "crypto", new BrowserCryptoAdapter());
1013
- __publicField(this, "pgp", new BrowserPGPAdapter());
1014
- __publicField(this, "http", new BrowserHttpAdapter());
1015
- __publicField(this, "cache", new BrowserCacheAdapter());
353
+ __publicField(this, "crypto");
354
+ __publicField(this, "pgp");
355
+ __publicField(this, "http");
356
+ __publicField(this, "cache");
1016
357
  __publicField(this, "platform", "browser");
358
+ this.crypto = new BrowserCryptoAdapter();
359
+ this.pgp = new BrowserPGPAdapter();
360
+ this.http = new BrowserHttpAdapter();
361
+ this.cache = new BrowserCacheAdapter();
1017
362
  }
1018
363
  };
364
+ browserPlatformAdapter = new BrowserPlatformAdapter();
1019
365
  }
1020
366
  });
1021
367
 
@@ -1082,8 +428,10 @@ var init_dataSchema_schema = __esm({
1082
428
  // src/utils/schemaValidation.ts
1083
429
  import Ajv from "ajv";
1084
430
  import addFormats from "ajv-formats";
1085
- function validateDataSchema(schema) {
1086
- return schemaValidator.validateDataSchema(schema);
431
+ function validateDataSchemaAgainstMetaSchema(schema) {
432
+ const validator = schemaValidator;
433
+ validator.validateDataSchemaAgainstMetaSchema(schema);
434
+ return schema;
1087
435
  }
1088
436
  function validateDataAgainstSchema(data, schema) {
1089
437
  return schemaValidator.validateDataAgainstSchema(data, schema);
@@ -1116,9 +464,9 @@ var init_schemaValidation = __esm({
1116
464
  this.dataSchemaValidator = this.ajv.compile(dataSchema_schema_default);
1117
465
  }
1118
466
  /**
1119
- * Validates a data schema against the Vana meta-schema
467
+ * Validates a data schema definition against the Vana meta-schema
1120
468
  *
1121
- * @param schema - The data schema to validate
469
+ * @param schema - The data schema definition to validate
1122
470
  * @throws SchemaValidationError if invalid
1123
471
  * @example
1124
472
  * ```typescript
@@ -1137,10 +485,10 @@ var init_schemaValidation = __esm({
1137
485
  * }
1138
486
  * };
1139
487
  *
1140
- * validator.validateDataSchema(schema); // throws if invalid
488
+ * validator.validateDataSchemaAgainstMetaSchema(schema); // throws if invalid
1141
489
  * ```
1142
490
  */
1143
- validateDataSchema(schema) {
491
+ validateDataSchemaAgainstMetaSchema(schema) {
1144
492
  const isValid = this.dataSchemaValidator(schema);
1145
493
  if (!isValid) {
1146
494
  const errors = this.dataSchemaValidator.errors || [];
@@ -1160,10 +508,10 @@ var init_schemaValidation = __esm({
1160
508
  }
1161
509
  }
1162
510
  /**
1163
- * Validates data against a JSON Schema from a schema
511
+ * Validates data against a JSON Schema
1164
512
  *
1165
513
  * @param data - The data to validate
1166
- * @param schema - The schema containing the validation rules (DataSchema or Schema)
514
+ * @param schema - The schema containing the validation rules (must have been validated or fetched from chain)
1167
515
  * @throws SchemaValidationError if invalid
1168
516
  * @example
1169
517
  * ```typescript
@@ -1173,25 +521,22 @@ var init_schemaValidation = __esm({
1173
521
  * const schema = await vana.schemas.get(1);
1174
522
  * validator.validateDataAgainstSchema(userData, schema);
1175
523
  *
1176
- * // Also works with DataSchema object
1177
- * const dataSchema: DataSchema = {
524
+ * // Also works with pre-validated DataSchema object
525
+ * const dataSchema = validator.validateDataSchemaAgainstMetaSchema({
1178
526
  * name: "User Profile",
1179
527
  * version: "1.0.0",
1180
528
  * dialect: "json",
1181
529
  * schema: { type: "object", properties: { name: { type: "string" } } }
1182
- * };
530
+ * });
1183
531
  * validator.validateDataAgainstSchema(userData, dataSchema);
1184
532
  * ```
1185
533
  */
1186
534
  validateDataAgainstSchema(data, schema) {
1187
- if (!("id" in schema)) {
1188
- this.validateDataSchema(schema);
1189
- }
1190
535
  if (schema.dialect !== "json") {
1191
- throw new SchemaValidationError(
1192
- `Data validation only supported for JSON dialect, got: ${schema.dialect}`,
1193
- []
536
+ console.warn(
537
+ `[SchemaValidator] Data validation skipped: dialect '${schema.dialect}' does not support data validation. Only JSON schemas can validate data structure.`
1194
538
  );
539
+ return;
1195
540
  }
1196
541
  if (typeof schema.schema !== "object") {
1197
542
  throw new SchemaValidationError(
@@ -1257,9 +602,9 @@ var init_schemaValidation = __esm({
1257
602
  }
1258
603
  }
1259
604
  /**
1260
- * Fetches and validates a schema from a URL
605
+ * Fetches and validates a data schema from a URL
1261
606
  *
1262
- * @param url - The URL to fetch the schema from
607
+ * @param url - The URL to fetch the data schema from
1263
608
  * @returns The validated data schema
1264
609
  * @throws SchemaValidationError if invalid or fetch fails
1265
610
  * @example
@@ -1275,7 +620,7 @@ var init_schemaValidation = __esm({
1275
620
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1276
621
  }
1277
622
  const schema = await response.json();
1278
- this.validateDataSchema(schema);
623
+ this.validateDataSchemaAgainstMetaSchema(schema);
1279
624
  if (schema.dialect === "sqlite" && typeof schema.schema === "string") {
1280
625
  this.validateSQLiteDDL(schema.schema, schema.dialectVersion);
1281
626
  }
@@ -1924,19 +1269,19 @@ var init_eventMappings = __esm({
1924
1269
  // DataRegistry operations
1925
1270
  addFile: {
1926
1271
  contract: "DataRegistry",
1927
- event: "FileAdded"
1272
+ event: "FileAddedV2"
1928
1273
  },
1929
1274
  addFileWithPermissionsAndSchema: {
1930
1275
  contract: "DataRegistry",
1931
- event: "FileAdded"
1276
+ event: "FileAddedV2"
1932
1277
  },
1933
1278
  addFileWithSchema: {
1934
1279
  contract: "DataRegistry",
1935
- event: "FileAdded"
1280
+ event: "FileAddedV2"
1936
1281
  },
1937
1282
  addFileWithPermissions: {
1938
1283
  contract: "DataRegistry",
1939
- event: "FileAdded"
1284
+ event: "FileAddedV2"
1940
1285
  },
1941
1286
  addRefinement: {
1942
1287
  contract: "DataRegistry",
@@ -3423,6 +2768,37 @@ var init_DataRegistryImplementation = __esm({
3423
2768
  name: "FileAdded",
3424
2769
  type: "event"
3425
2770
  },
2771
+ {
2772
+ anonymous: false,
2773
+ inputs: [
2774
+ {
2775
+ indexed: true,
2776
+ internalType: "uint256",
2777
+ name: "fileId",
2778
+ type: "uint256"
2779
+ },
2780
+ {
2781
+ indexed: true,
2782
+ internalType: "address",
2783
+ name: "ownerAddress",
2784
+ type: "address"
2785
+ },
2786
+ {
2787
+ indexed: false,
2788
+ internalType: "string",
2789
+ name: "url",
2790
+ type: "string"
2791
+ },
2792
+ {
2793
+ indexed: false,
2794
+ internalType: "uint256",
2795
+ name: "schemaId",
2796
+ type: "uint256"
2797
+ }
2798
+ ],
2799
+ name: "FileAddedV2",
2800
+ type: "event"
2801
+ },
3426
2802
  {
3427
2803
  anonymous: false,
3428
2804
  inputs: [
@@ -3662,6 +3038,19 @@ var init_DataRegistryImplementation = __esm({
3662
3038
  name: "Upgraded",
3663
3039
  type: "event"
3664
3040
  },
3041
+ {
3042
+ inputs: [],
3043
+ name: "DATA_PORTABILITY_ROLE",
3044
+ outputs: [
3045
+ {
3046
+ internalType: "bytes32",
3047
+ name: "",
3048
+ type: "bytes32"
3049
+ }
3050
+ ],
3051
+ stateMutability: "view",
3052
+ type: "function"
3053
+ },
3665
3054
  {
3666
3055
  inputs: [],
3667
3056
  name: "DEFAULT_ADMIN_ROLE",
@@ -3756,6 +3145,41 @@ var init_DataRegistryImplementation = __esm({
3756
3145
  stateMutability: "nonpayable",
3757
3146
  type: "function"
3758
3147
  },
3148
+ {
3149
+ inputs: [
3150
+ {
3151
+ internalType: "uint256",
3152
+ name: "fileId",
3153
+ type: "uint256"
3154
+ },
3155
+ {
3156
+ components: [
3157
+ {
3158
+ internalType: "address",
3159
+ name: "account",
3160
+ type: "address"
3161
+ },
3162
+ {
3163
+ internalType: "string",
3164
+ name: "key",
3165
+ type: "string"
3166
+ }
3167
+ ],
3168
+ internalType: "struct IDataRegistry.Permission[]",
3169
+ name: "permissions",
3170
+ type: "tuple[]"
3171
+ },
3172
+ {
3173
+ internalType: "uint256",
3174
+ name: "schemaId",
3175
+ type: "uint256"
3176
+ }
3177
+ ],
3178
+ name: "addFilePermissionsAndSchema",
3179
+ outputs: [],
3180
+ stateMutability: "nonpayable",
3181
+ type: "function"
3182
+ },
3759
3183
  {
3760
3184
  inputs: [
3761
3185
  {
@@ -3970,6 +3394,19 @@ var init_DataRegistryImplementation = __esm({
3970
3394
  stateMutability: "view",
3971
3395
  type: "function"
3972
3396
  },
3397
+ {
3398
+ inputs: [],
3399
+ name: "emitLegacyEvents",
3400
+ outputs: [
3401
+ {
3402
+ internalType: "bool",
3403
+ name: "",
3404
+ type: "bool"
3405
+ }
3406
+ ],
3407
+ stateMutability: "view",
3408
+ type: "function"
3409
+ },
3973
3410
  {
3974
3411
  inputs: [
3975
3412
  {
@@ -4127,6 +3564,11 @@ var init_DataRegistryImplementation = __esm({
4127
3564
  name: "url",
4128
3565
  type: "string"
4129
3566
  },
3567
+ {
3568
+ internalType: "uint256",
3569
+ name: "schemaId",
3570
+ type: "uint256"
3571
+ },
4130
3572
  {
4131
3573
  internalType: "uint256",
4132
3574
  name: "addedAtBlock",
@@ -4410,6 +3852,19 @@ var init_DataRegistryImplementation = __esm({
4410
3852
  stateMutability: "nonpayable",
4411
3853
  type: "function"
4412
3854
  },
3855
+ {
3856
+ inputs: [
3857
+ {
3858
+ internalType: "bool",
3859
+ name: "newEmitLegacyEvents",
3860
+ type: "bool"
3861
+ }
3862
+ ],
3863
+ name: "updateEmitLegacyEvents",
3864
+ outputs: [],
3865
+ stateMutability: "nonpayable",
3866
+ type: "function"
3867
+ },
4413
3868
  {
4414
3869
  inputs: [
4415
3870
  {
@@ -37215,7 +36670,7 @@ var init_schemas = __esm({
37215
36670
  dialect,
37216
36671
  schema: schemaDefinition
37217
36672
  };
37218
- validateDataSchema(dataSchema);
36673
+ validateDataSchemaAgainstMetaSchema(dataSchema);
37219
36674
  if (!this.context.storageManager) {
37220
36675
  if (this.context.validateStorageRequired) {
37221
36676
  this.context.validateStorageRequired();
@@ -37324,7 +36779,7 @@ var init_schemas = __esm({
37324
36779
  `Invalid schema definition format for schema ${schemaId}`
37325
36780
  );
37326
36781
  }
37327
- validateDataSchema(definition);
36782
+ validateDataSchemaAgainstMetaSchema(definition);
37328
36783
  const dataSchema = definition;
37329
36784
  if (dataSchema.name !== metadata.name) {
37330
36785
  throw new Error(
@@ -37659,7 +37114,7 @@ var init_schemas = __esm({
37659
37114
  try {
37660
37115
  const definition = await fetchFromUrl(schema.definitionUrl);
37661
37116
  if (definition && typeof definition === "object") {
37662
- validateDataSchema(definition);
37117
+ validateDataSchemaAgainstMetaSchema(definition);
37663
37118
  const dataSchema = definition;
37664
37119
  schema.version = dataSchema.version;
37665
37120
  schema.description = dataSchema.description;
@@ -37679,7 +37134,7 @@ var init_schemas = __esm({
37679
37134
  });
37680
37135
 
37681
37136
  // src/index.browser.ts
37682
- init_browser2();
37137
+ init_browser();
37683
37138
 
37684
37139
  // src/types/config.ts
37685
37140
  function isWalletConfig(config) {
@@ -37710,6 +37165,9 @@ var StorageError = class extends Error {
37710
37165
  }
37711
37166
  };
37712
37167
 
37168
+ // src/types/index.ts
37169
+ init_schemaValidation();
37170
+
37713
37171
  // src/types/external-apis.ts
37714
37172
  function isReplicateAPIResponse(value) {
37715
37173
  if (typeof value !== "object" || value === null) return false;
@@ -37751,7 +37209,7 @@ init_abi();
37751
37209
 
37752
37210
  // src/utils/grantFiles.ts
37753
37211
  init_errors();
37754
- import { keccak256, toHex as toHex2 } from "viem";
37212
+ import { keccak256, toHex } from "viem";
37755
37213
  function createGrantFile(params) {
37756
37214
  const grantFile = {
37757
37215
  grantee: params.grantee,
@@ -37874,8 +37332,8 @@ function getGrantFileHash(grantFile) {
37874
37332
  sortedFile.expires = grantFile.expires;
37875
37333
  }
37876
37334
  const jsonString = JSON.stringify(sortedFile);
37877
- console.info(`Hash: ${keccak256(toHex2(jsonString))}`);
37878
- return keccak256(toHex2(jsonString));
37335
+ console.info(`Hash: ${keccak256(toHex(jsonString))}`);
37336
+ return keccak256(toHex(jsonString));
37879
37337
  } catch (error) {
37880
37338
  throw new SerializationError(
37881
37339
  `Failed to generate grant file hash: ${error instanceof Error ? error.message : "Unknown error"}`
@@ -38152,8 +37610,7 @@ function validateOperationAccess(grantFile, requestedOperation) {
38152
37610
  }
38153
37611
 
38154
37612
  // src/utils/signatureCache.ts
38155
- import { sha256 as sha2562 } from "@noble/hashes/sha256";
38156
- import { bytesToHex as bytesToHex3 } from "@noble/hashes/utils";
37613
+ init_crypto_utils();
38157
37614
  var SignatureCache = class {
38158
37615
  /**
38159
37616
  * Get a cached signature if it exists and hasn't expired
@@ -38250,12 +37707,12 @@ var SignatureCache = class {
38250
37707
  * Generate a deterministic hash of a message object for cache key generation
38251
37708
  *
38252
37709
  * @remarks
38253
- * Creates a cryptographically secure hash from complex objects including EIP-712 typed data.
38254
- * Uses SHA-256 for collision resistance and deterministic key generation.
38255
- * Handles BigInt serialization and sorts object keys for consistency.
37710
+ * Creates a consistent hash from complex objects including EIP-712 typed data.
37711
+ * Handles BigInt serialization and produces a 32-character hash that balances
37712
+ * uniqueness with key length constraints.
38256
37713
  *
38257
37714
  * @param message - The message object to hash (typically EIP-712 typed data)
38258
- * @returns A hex string hash (SHA-256) suitable for cache keys
37715
+ * @returns A 32-character hash string suitable for cache keys
38259
37716
  * @example
38260
37717
  * ```typescript
38261
37718
  * const typedData = {
@@ -38264,35 +37721,30 @@ var SignatureCache = class {
38264
37721
  * };
38265
37722
  *
38266
37723
  * const hash = SignatureCache.hashMessage(typedData);
38267
- * // Returns SHA-256 hash like: "a1b2c3d4e5f6..."
37724
+ * // Returns something like: "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"
38268
37725
  * ```
38269
37726
  */
38270
37727
  static hashMessage(message) {
38271
- const jsonString = JSON.stringify(message, this.deterministicReplacer);
38272
- const hashBytes = sha2562(new TextEncoder().encode(jsonString));
38273
- return bytesToHex3(hashBytes);
37728
+ const jsonString = JSON.stringify(message, this.bigIntReplacer);
37729
+ const base64Hash = toBase64(jsonString);
37730
+ const cleaned = base64Hash.replace(/[^a-zA-Z0-9]/g, "");
37731
+ if (cleaned.length > 32) {
37732
+ return cleaned.substring(0, 16) + cleaned.substring(cleaned.length - 16);
37733
+ }
37734
+ return cleaned.substring(0, 32);
38274
37735
  }
38275
37736
  /**
38276
- * Deterministic JSON replacer that handles BigInt values and sorts object keys
38277
- * This ensures consistent cache key generation for EIP-712 typed data
37737
+ * Custom JSON replacer that converts BigInt values to strings for serialization
37738
+ * This ensures deterministic cache key generation for EIP-712 typed data
38278
37739
  *
38279
37740
  * @param _key - The object key being serialized (unused)
38280
37741
  * @param value - The value to serialize
38281
- * @returns The serialized value with sorted keys for objects
37742
+ * @returns The serialized value
38282
37743
  */
38283
- static deterministicReplacer(_key, value) {
37744
+ static bigIntReplacer(_key, value) {
38284
37745
  if (typeof value === "bigint") {
38285
37746
  return `__BIGINT__${value.toString()}`;
38286
37747
  }
38287
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
38288
- return Object.keys(value).sort().reduce(
38289
- (sorted, key) => {
38290
- sorted[key] = value[key];
38291
- return sorted;
38292
- },
38293
- {}
38294
- );
38295
- }
38296
37748
  return value;
38297
37749
  }
38298
37750
  };
@@ -42535,6 +41987,29 @@ var DataController = class {
42535
41987
  const userFiles = Array.from(fileMap.values()).sort(
42536
41988
  (a, b) => Number((b.addedAtTimestamp || 0n) - (a.addedAtTimestamp || 0n))
42537
41989
  );
41990
+ if (userFiles.length > 0) {
41991
+ try {
41992
+ const fileIds = userFiles.map((f) => f.id);
41993
+ let proofMap;
41994
+ try {
41995
+ proofMap = await this._fetchProofsFromSubgraph(fileIds, endpoint);
41996
+ } catch (subgraphError) {
41997
+ console.debug(
41998
+ "Failed to fetch proofs from subgraph, trying chain:",
41999
+ subgraphError
42000
+ );
42001
+ proofMap = await this._fetchProofsFromChain(fileIds);
42002
+ }
42003
+ for (const file of userFiles) {
42004
+ const dlpIds = proofMap.get(file.id);
42005
+ if (dlpIds && dlpIds.length > 0) {
42006
+ file.dlpIds = dlpIds;
42007
+ }
42008
+ }
42009
+ } catch (error) {
42010
+ console.warn("Failed to fetch proof data for files:", error);
42011
+ }
42012
+ }
42538
42013
  return userFiles;
42539
42014
  } catch (error) {
42540
42015
  console.error("Failed to fetch user files from subgraph:", error);
@@ -42543,6 +42018,349 @@ var DataController = class {
42543
42018
  );
42544
42019
  }
42545
42020
  }
42021
+ /**
42022
+ * Fetches proof data for multiple files from the subgraph.
42023
+ *
42024
+ * @private
42025
+ * @param fileIds - Array of file IDs to fetch proofs for
42026
+ * @param subgraphUrl - The subgraph endpoint URL
42027
+ * @returns Map of file IDs to their associated DLP IDs
42028
+ */
42029
+ async _fetchProofsFromSubgraph(fileIds, subgraphUrl) {
42030
+ const query = `
42031
+ query GetFileProofs($fileIds: [BigInt!]!) {
42032
+ dataRegistryProofs(where: { fileId_in: $fileIds }) {
42033
+ fileId
42034
+ dlp {
42035
+ id
42036
+ }
42037
+ }
42038
+ }
42039
+ `;
42040
+ const response = await fetch(subgraphUrl, {
42041
+ method: "POST",
42042
+ headers: {
42043
+ "Content-Type": "application/json"
42044
+ },
42045
+ body: JSON.stringify({
42046
+ query,
42047
+ variables: {
42048
+ fileIds: fileIds.map((id) => id.toString())
42049
+ }
42050
+ })
42051
+ });
42052
+ if (!response.ok) {
42053
+ throw new Error(
42054
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42055
+ );
42056
+ }
42057
+ const result = await response.json();
42058
+ if (result.errors) {
42059
+ throw new Error(
42060
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42061
+ );
42062
+ }
42063
+ const proofMap = /* @__PURE__ */ new Map();
42064
+ if (result.data?.dataRegistryProofs) {
42065
+ for (const proof of result.data.dataRegistryProofs) {
42066
+ if (proof.dlp?.id) {
42067
+ const fileId = parseInt(proof.fileId);
42068
+ const dlpId = parseInt(proof.dlp.id);
42069
+ if (!proofMap.has(fileId)) {
42070
+ proofMap.set(fileId, []);
42071
+ }
42072
+ const dlpIds = proofMap.get(fileId);
42073
+ if (!dlpIds.includes(dlpId)) {
42074
+ dlpIds.push(dlpId);
42075
+ }
42076
+ }
42077
+ }
42078
+ }
42079
+ return proofMap;
42080
+ }
42081
+ /**
42082
+ * Fetches proof data for multiple files from the blockchain.
42083
+ * Falls back to this when subgraph is unavailable.
42084
+ *
42085
+ * @private
42086
+ * @param fileIds - Array of file IDs to fetch proofs for
42087
+ * @returns Map of file IDs to their associated DLP IDs
42088
+ */
42089
+ async _fetchProofsFromChain(fileIds) {
42090
+ const chainId = this.context.walletClient.chain?.id;
42091
+ if (!chainId) {
42092
+ throw new Error("Chain ID not available");
42093
+ }
42094
+ const dataRegistryAddress = getContractAddress(chainId, "DataRegistry");
42095
+ const dataRegistryAbi = getAbi("DataRegistry");
42096
+ const proofMap = /* @__PURE__ */ new Map();
42097
+ for (const fileId of fileIds) {
42098
+ const dlpIds = [];
42099
+ let proofIndex = 0;
42100
+ let hasMoreProofs = true;
42101
+ while (hasMoreProofs) {
42102
+ try {
42103
+ const proof = await this.context.publicClient.readContract({
42104
+ address: dataRegistryAddress,
42105
+ abi: dataRegistryAbi,
42106
+ functionName: "fileProofs",
42107
+ args: [BigInt(fileId), BigInt(proofIndex)]
42108
+ });
42109
+ if (proof?.data?.dlpId) {
42110
+ const dlpId = Number(proof.data.dlpId);
42111
+ if (!dlpIds.includes(dlpId)) {
42112
+ dlpIds.push(dlpId);
42113
+ }
42114
+ }
42115
+ proofIndex++;
42116
+ } catch {
42117
+ hasMoreProofs = false;
42118
+ }
42119
+ }
42120
+ if (dlpIds.length > 0) {
42121
+ proofMap.set(fileId, dlpIds);
42122
+ }
42123
+ }
42124
+ return proofMap;
42125
+ }
42126
+ /**
42127
+ * Retrieves information about a specific Data Liquidity Pool (DLP).
42128
+ *
42129
+ * @remarks
42130
+ * DLPs are entities that process and verify data files in the Vana network.
42131
+ * This method fetches DLP metadata including name, status, and performance rating.
42132
+ * Uses subgraph first for efficiency, falls back to chain if unavailable.
42133
+ *
42134
+ * @param dlpId - The unique identifier of the DLP
42135
+ * @param options - Optional parameters
42136
+ * @param options.subgraphUrl - Custom subgraph URL to override default
42137
+ * @returns Promise resolving to DLP information
42138
+ * @throws {Error} When DLP cannot be found - "DLP not found: {dlpId}"
42139
+ * @throws {Error} When query fails - "Failed to fetch DLP: {error}"
42140
+ * @example
42141
+ * ```typescript
42142
+ * const dlp = await vana.data.getDLP(26);
42143
+ * console.log(`DLP ${dlp.name}: ${dlp.status}`);
42144
+ * ```
42145
+ */
42146
+ async getDLP(dlpId, options = {}) {
42147
+ const subgraphUrl = options.subgraphUrl || this.context.subgraphUrl;
42148
+ if (subgraphUrl) {
42149
+ try {
42150
+ const query = `
42151
+ query GetDLP($id: ID!) {
42152
+ dlp(id: $id) {
42153
+ id
42154
+ name
42155
+ metadata
42156
+ status
42157
+ address
42158
+ owner
42159
+ }
42160
+ }
42161
+ `;
42162
+ const response = await fetch(subgraphUrl, {
42163
+ method: "POST",
42164
+ headers: {
42165
+ "Content-Type": "application/json"
42166
+ },
42167
+ body: JSON.stringify({
42168
+ query,
42169
+ variables: {
42170
+ id: dlpId.toString()
42171
+ }
42172
+ })
42173
+ });
42174
+ if (!response.ok) {
42175
+ throw new Error(
42176
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42177
+ );
42178
+ }
42179
+ const result = await response.json();
42180
+ if (result.errors) {
42181
+ throw new Error(
42182
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42183
+ );
42184
+ }
42185
+ if (!result.data?.dlp) {
42186
+ throw new Error(`DLP not found: ${dlpId}`);
42187
+ }
42188
+ return {
42189
+ id: parseInt(result.data.dlp.id),
42190
+ name: result.data.dlp.name || "",
42191
+ metadata: result.data.dlp.metadata,
42192
+ status: result.data.dlp.status ? parseInt(result.data.dlp.status) : void 0,
42193
+ address: result.data.dlp.address,
42194
+ owner: result.data.dlp.owner
42195
+ };
42196
+ } catch (error) {
42197
+ console.debug("Subgraph query failed, falling back to chain:", error);
42198
+ }
42199
+ }
42200
+ try {
42201
+ const chainId = this.context.walletClient.chain?.id;
42202
+ if (!chainId) {
42203
+ throw new Error("Chain ID not available");
42204
+ }
42205
+ const dlpRegistryAddress = getContractAddress(chainId, "DLPRegistry");
42206
+ const dlpRegistryAbi = getAbi("DLPRegistry");
42207
+ const dlpData = await this.context.publicClient.readContract({
42208
+ address: dlpRegistryAddress,
42209
+ abi: dlpRegistryAbi,
42210
+ functionName: "dlps",
42211
+ args: [BigInt(dlpId)]
42212
+ });
42213
+ if (!dlpData || !dlpData.name) {
42214
+ throw new Error(`DLP not found: ${dlpId}`);
42215
+ }
42216
+ return {
42217
+ id: dlpId,
42218
+ name: dlpData.name,
42219
+ metadata: dlpData.metadata,
42220
+ status: dlpData.status,
42221
+ address: dlpData.dlpAddress,
42222
+ owner: dlpData.ownerAddress
42223
+ };
42224
+ } catch (error) {
42225
+ throw new Error(
42226
+ `Failed to fetch DLP: ${error instanceof Error ? error.message : "Unknown error"}`
42227
+ );
42228
+ }
42229
+ }
42230
+ /**
42231
+ * Lists all Data Liquidity Pools (DLPs) with optional pagination.
42232
+ *
42233
+ * @remarks
42234
+ * Fetches a paginated list of all DLPs registered in the network.
42235
+ * Uses subgraph for efficient querying with fallback to chain multicall.
42236
+ *
42237
+ * @param options - Optional parameters for pagination and filtering
42238
+ * @param options.limit - Maximum number of DLPs to return (default: 100)
42239
+ * @param options.offset - Number of DLPs to skip (default: 0)
42240
+ * @param options.subgraphUrl - Custom subgraph URL to override default
42241
+ * @returns Promise resolving to array of DLP information
42242
+ * @throws {Error} When query fails - "Failed to list DLPs: {error}"
42243
+ * @example
42244
+ * ```typescript
42245
+ * // Get first 10 DLPs
42246
+ * const dlps = await vana.data.listDLPs({ limit: 10 });
42247
+ * dlps.forEach(dlp => console.log(`${dlp.id}: ${dlp.name}`));
42248
+ *
42249
+ * // Get next page
42250
+ * const nextPage = await vana.data.listDLPs({ limit: 10, offset: 10 });
42251
+ * ```
42252
+ */
42253
+ async listDLPs(options = {}) {
42254
+ const { limit = 100, offset = 0 } = options;
42255
+ const subgraphUrl = options.subgraphUrl || this.context.subgraphUrl;
42256
+ if (subgraphUrl) {
42257
+ try {
42258
+ const query = `
42259
+ query ListDLPs($first: Int!, $skip: Int!) {
42260
+ dlps(first: $first, skip: $skip, orderBy: id) {
42261
+ id
42262
+ name
42263
+ metadata
42264
+ status
42265
+ address
42266
+ owner
42267
+ }
42268
+ }
42269
+ `;
42270
+ const response = await fetch(subgraphUrl, {
42271
+ method: "POST",
42272
+ headers: {
42273
+ "Content-Type": "application/json"
42274
+ },
42275
+ body: JSON.stringify({
42276
+ query,
42277
+ variables: {
42278
+ first: limit,
42279
+ skip: offset
42280
+ }
42281
+ })
42282
+ });
42283
+ if (!response.ok) {
42284
+ throw new Error(
42285
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42286
+ );
42287
+ }
42288
+ const result = await response.json();
42289
+ if (result.errors) {
42290
+ throw new Error(
42291
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42292
+ );
42293
+ }
42294
+ const dlps = result.data?.dlps || [];
42295
+ return dlps.map((dlp) => ({
42296
+ id: parseInt(dlp.id),
42297
+ name: dlp.name || "",
42298
+ metadata: dlp.metadata,
42299
+ status: dlp.status ? parseInt(dlp.status) : void 0,
42300
+ address: dlp.address,
42301
+ owner: dlp.owner
42302
+ }));
42303
+ } catch (error) {
42304
+ console.debug("Subgraph query failed, falling back to chain:", error);
42305
+ }
42306
+ }
42307
+ try {
42308
+ const chainId = this.context.walletClient.chain?.id;
42309
+ if (!chainId) {
42310
+ throw new Error("Chain ID not available");
42311
+ }
42312
+ const dlpRegistryAddress = getContractAddress(chainId, "DLPRegistry");
42313
+ const dlpRegistryAbi = getAbi("DLPRegistry");
42314
+ const dlpCount = await this.context.publicClient.readContract({
42315
+ address: dlpRegistryAddress,
42316
+ abi: dlpRegistryAbi,
42317
+ functionName: "dlpsCount",
42318
+ args: []
42319
+ });
42320
+ const totalCount = Number(dlpCount);
42321
+ const start = offset;
42322
+ const end = Math.min(start + limit, totalCount);
42323
+ if (end <= start) {
42324
+ return [];
42325
+ }
42326
+ const calls = [];
42327
+ for (let i = start + 1; i <= end; i++) {
42328
+ calls.push({
42329
+ address: dlpRegistryAddress,
42330
+ abi: dlpRegistryAbi,
42331
+ functionName: "dlps",
42332
+ args: [BigInt(i)]
42333
+ });
42334
+ }
42335
+ const results = await gasAwareMulticall(this.context.publicClient, {
42336
+ contracts: calls,
42337
+ allowFailure: true,
42338
+ batchSize: 50
42339
+ });
42340
+ const dlps = [];
42341
+ for (let i = 0; i < results.length; i++) {
42342
+ const result = results[i];
42343
+ if (result.status === "success" && result.result) {
42344
+ const dlpData = result.result;
42345
+ if (dlpData.name) {
42346
+ dlps.push({
42347
+ id: start + i + 1,
42348
+ name: dlpData.name,
42349
+ metadata: dlpData.metadata,
42350
+ status: dlpData.status,
42351
+ address: dlpData.dlpAddress,
42352
+ owner: dlpData.ownerAddress
42353
+ });
42354
+ }
42355
+ }
42356
+ }
42357
+ return dlps;
42358
+ } catch (error) {
42359
+ throw new Error(
42360
+ `Failed to list DLPs: ${error instanceof Error ? error.message : "Unknown error"}`
42361
+ );
42362
+ }
42363
+ }
42546
42364
  /**
42547
42365
  * Retrieves a list of permissions granted by a user.
42548
42366
  *
@@ -43673,19 +43491,31 @@ var DataController = class {
43673
43491
  return await this.submitFilePermission(fileId, account, publicKey);
43674
43492
  }
43675
43493
  /**
43676
- * Submits a file permission transaction and returns the transaction hash immediately.
43494
+ * Submits a file permission transaction to the blockchain.
43677
43495
  *
43678
- * This is the lower-level method that provides maximum control over transaction timing.
43496
+ * @remarks
43497
+ * This method supports gasless transactions via relayer callbacks when configured.
43498
+ * It encrypts the user's encryption key with the recipient's public key before submission.
43679
43499
  * Use this when you want to handle transaction confirmation and event parsing separately.
43680
43500
  *
43681
- * @param fileId - The ID of the file to add permissions for
43682
- * @param account - The address of the account to grant permission to
43683
- * @param publicKey - The public key to encrypt the user's encryption key with
43684
- * @returns Promise resolving to the transaction hash
43501
+ * @param fileId - The ID of the file to grant permission for
43502
+ * @param account - The recipient's wallet address that will access the file
43503
+ * @param publicKey - The recipient's public key for encryption.
43504
+ * Obtain via `vana.server.getIdentity(account).public_key`
43505
+ * @returns Promise resolving to TransactionHandle for tracking the transaction
43506
+ * @throws {Error} When chain ID is not available
43507
+ * @throws {Error} When encryption key generation fails
43508
+ * @throws {Error} When public key encryption fails
43509
+ *
43685
43510
  * @example
43686
43511
  * ```typescript
43687
- * const txHash = await vana.data.submitFilePermission(fileId, account, publicKey);
43688
- * console.log(`Transaction submitted: ${txHash}`);
43512
+ * const tx = await vana.data.submitFilePermission(
43513
+ * fileId,
43514
+ * "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36",
43515
+ * recipientPublicKey
43516
+ * );
43517
+ * const result = await tx.waitForEvents();
43518
+ * console.log(`Permission granted with ID: ${result.permissionId}`);
43689
43519
  * ```
43690
43520
  */
43691
43521
  async submitFilePermission(fileId, account, publicKey) {
@@ -43969,10 +43799,10 @@ var DataController = class {
43969
43799
  );
43970
43800
  }
43971
43801
  /**
43972
- * Validates a data schema against the Vana meta-schema.
43802
+ * Validates a data schema definition against the Vana meta-schema.
43973
43803
  *
43974
- * @param schema - The data schema to validate
43975
- * @returns Assertion that schema is valid (throws if invalid)
43804
+ * @param schema - The data schema definition to validate
43805
+ * @returns The validated DataSchema
43976
43806
  * @throws SchemaValidationError if invalid
43977
43807
  * @example
43978
43808
  * ```typescript
@@ -43989,11 +43819,11 @@ var DataController = class {
43989
43819
  * }
43990
43820
  * };
43991
43821
  *
43992
- * vana.data.validateDataSchema(schema);
43822
+ * const validatedSchema = vana.data.validateDataSchemaAgainstMetaSchema(schema);
43993
43823
  * ```
43994
43824
  */
43995
- validateDataSchema(schema) {
43996
- return validateDataSchema(schema);
43825
+ validateDataSchemaAgainstMetaSchema(schema) {
43826
+ return validateDataSchemaAgainstMetaSchema(schema);
43997
43827
  }
43998
43828
  /**
43999
43829
  * Validates data against a JSON Schema from a data schema.
@@ -44026,9 +43856,9 @@ var DataController = class {
44026
43856
  return validateDataAgainstSchema(data, schema);
44027
43857
  }
44028
43858
  /**
44029
- * Fetches and validates a schema from a URL, then returns the parsed data schema.
43859
+ * Fetches and validates a data schema from a URL, then returns the parsed data schema.
44030
43860
  *
44031
- * @param url - The URL to fetch the schema from
43861
+ * @param url - The URL to fetch the data schema from
44032
43862
  * @returns The validated data schema
44033
43863
  * @throws SchemaValidationError if invalid or fetch fails
44034
43864
  * @example
@@ -45226,7 +45056,7 @@ var GoogleDriveStorage = class {
45226
45056
  };
45227
45057
 
45228
45058
  // src/storage/providers/ipfs.ts
45229
- init_encoding();
45059
+ init_crypto_utils();
45230
45060
  var IpfsStorage = class _IpfsStorage {
45231
45061
  constructor(config) {
45232
45062
  this.config = config;
@@ -45266,9 +45096,8 @@ var IpfsStorage = class _IpfsStorage {
45266
45096
  * ```
45267
45097
  */
45268
45098
  static forInfura(credentials) {
45269
- const encoder = new TextEncoder();
45270
45099
  const auth = toBase64(
45271
- encoder.encode(`${credentials.projectId}:${credentials.projectSecret}`)
45100
+ `${credentials.projectId}:${credentials.projectSecret}`
45272
45101
  );
45273
45102
  return new _IpfsStorage({
45274
45103
  apiEndpoint: "https://ipfs.infura.io:5001/api/v0/add",
@@ -46130,7 +45959,7 @@ var vanaMainnet2 = {
46130
45959
  url: "https://vanascan.io"
46131
45960
  }
46132
45961
  },
46133
- subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/vana/7.0.7/gn"
45962
+ subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/vana/prod/gn"
46134
45963
  };
46135
45964
  var moksha = {
46136
45965
  id: 14800,
@@ -46151,7 +45980,7 @@ var moksha = {
46151
45980
  url: "https://moksha.vanascan.io"
46152
45981
  }
46153
45982
  },
46154
- subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/moksha/7.0.7/gn"
45983
+ subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/moksha/prod/gn"
46155
45984
  };
46156
45985
  function getChainConfig(chainId) {
46157
45986
  switch (chainId) {
@@ -47111,11 +46940,10 @@ var CircuitBreaker = class {
47111
46940
  };
47112
46941
 
47113
46942
  // src/index.browser.ts
47114
- init_browser2();
47115
46943
  init_browser();
47116
46944
 
47117
46945
  // src/platform/browser-only.ts
47118
- init_browser2();
46946
+ init_browser();
47119
46947
  function createBrowserPlatformAdapter() {
47120
46948
  return new BrowserPlatformAdapter();
47121
46949
  }
@@ -47463,7 +47291,6 @@ export {
47463
47291
  AsyncQueue,
47464
47292
  BaseController,
47465
47293
  BlockchainError,
47466
- BrowserECIESUint8Provider as BrowserECIESProvider,
47467
47294
  BrowserPlatformAdapter,
47468
47295
  CallbackStorage,
47469
47296
  CircuitBreaker,
@@ -47565,7 +47392,7 @@ export {
47565
47392
  storeGrantFile,
47566
47393
  summarizeGrant,
47567
47394
  validateDataAgainstSchema,
47568
- validateDataSchema,
47395
+ validateDataSchemaAgainstMetaSchema,
47569
47396
  validateGrant,
47570
47397
  validateGrantExpiry,
47571
47398
  validateGrantFile,