@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
@@ -1,11 +1,5 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
- }) : x)(function(x) {
6
- if (typeof require !== "undefined") return require.apply(this, arguments);
7
- throw Error('Dynamic require of "' + x + '" is not supported');
8
- });
9
3
  var __esm = (fn, res) => function __init() {
10
4
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
5
  };
@@ -14,6 +8,53 @@ var __export = (target, all) => {
14
8
  __defProp(target, name, { get: all[name], enumerable: true });
15
9
  };
16
10
 
11
+ // src/platform/shared/crypto-utils.ts
12
+ function processWalletPublicKey(publicKey) {
13
+ const publicKeyHex = publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey;
14
+ const publicKeyBytes = Buffer.from(publicKeyHex, "hex");
15
+ return publicKeyBytes.length === 64 ? Buffer.concat([Buffer.from([4]), publicKeyBytes]) : publicKeyBytes;
16
+ }
17
+ function processWalletPrivateKey(privateKey) {
18
+ const privateKeyHex = privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey;
19
+ return Buffer.from(privateKeyHex, "hex");
20
+ }
21
+ function parseEncryptedDataBuffer(encryptedBuffer) {
22
+ return {
23
+ iv: encryptedBuffer.slice(0, 16),
24
+ ephemPublicKey: encryptedBuffer.slice(16, 81),
25
+ // 65 bytes for uncompressed public key
26
+ ciphertext: encryptedBuffer.slice(81, -32),
27
+ mac: encryptedBuffer.slice(-32)
28
+ };
29
+ }
30
+ function toBase64(str) {
31
+ if (typeof Buffer !== "undefined") {
32
+ return Buffer.from(str, "utf8").toString("base64");
33
+ } else if (typeof btoa !== "undefined") {
34
+ return btoa(str);
35
+ } else {
36
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
37
+ let result = "";
38
+ let i = 0;
39
+ while (i < str.length) {
40
+ const a = str.charCodeAt(i++);
41
+ const b = i < str.length ? str.charCodeAt(i++) : 0;
42
+ const c = i < str.length ? str.charCodeAt(i++) : 0;
43
+ const bitmap = a << 16 | b << 8 | c;
44
+ result += chars.charAt(bitmap >> 18 & 63);
45
+ result += chars.charAt(bitmap >> 12 & 63);
46
+ result += i - 2 < str.length ? chars.charAt(bitmap >> 6 & 63) : "=";
47
+ result += i - 1 < str.length ? chars.charAt(bitmap & 63) : "=";
48
+ }
49
+ return result;
50
+ }
51
+ }
52
+ var init_crypto_utils = __esm({
53
+ "src/platform/shared/crypto-utils.ts"() {
54
+ "use strict";
55
+ }
56
+ });
57
+
17
58
  // src/platform/shared/pgp-utils.ts
18
59
  function processPGPKeyOptions(options) {
19
60
  return {
@@ -75,626 +116,6 @@ var init_lazy_import = __esm({
75
116
  }
76
117
  });
77
118
 
78
- // src/utils/encoding.ts
79
- function toBase64(data) {
80
- if (typeof Buffer !== "undefined" && Buffer.from) {
81
- return Buffer.from(data).toString("base64");
82
- }
83
- if (typeof btoa !== "undefined") {
84
- const binary = Array.from(data, (byte) => String.fromCharCode(byte)).join(
85
- ""
86
- );
87
- return btoa(binary);
88
- }
89
- throw new Error("No base64 encoding method available in this environment");
90
- }
91
- function toHex(data) {
92
- if (typeof Buffer !== "undefined" && Buffer.from) {
93
- return Buffer.from(data).toString("hex");
94
- }
95
- return Array.from(data, (byte) => byte.toString(16).padStart(2, "0")).join(
96
- ""
97
- );
98
- }
99
- function fromHex(hex) {
100
- const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
101
- if (cleanHex.length % 2 !== 0) {
102
- throw new Error("Invalid hex string: odd length");
103
- }
104
- if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {
105
- throw new Error("Invalid hex string: contains non-hex characters");
106
- }
107
- if (typeof Buffer !== "undefined" && Buffer.from) {
108
- return new Uint8Array(Buffer.from(cleanHex, "hex"));
109
- }
110
- const bytes = new Uint8Array(cleanHex.length / 2);
111
- for (let i = 0; i < cleanHex.length; i += 2) {
112
- bytes[i / 2] = parseInt(cleanHex.substr(i, 2), 16);
113
- }
114
- return bytes;
115
- }
116
- function stringToBytes(str) {
117
- if (typeof Buffer !== "undefined" && Buffer.from) {
118
- return new Uint8Array(Buffer.from(str, "utf8"));
119
- }
120
- if (typeof TextEncoder !== "undefined") {
121
- return new TextEncoder().encode(str);
122
- }
123
- const bytes = [];
124
- for (let i = 0; i < str.length; i++) {
125
- const char = str.charCodeAt(i);
126
- if (char < 128) {
127
- bytes.push(char);
128
- } else if (char < 2048) {
129
- bytes.push(192 | char >> 6, 128 | char & 63);
130
- } else if (char < 55296 || char >= 57344) {
131
- bytes.push(
132
- 224 | char >> 12,
133
- 128 | char >> 6 & 63,
134
- 128 | char & 63
135
- );
136
- } else {
137
- i++;
138
- const char2 = str.charCodeAt(i);
139
- const codePoint = 65536 + ((char & 1023) << 10 | char2 & 1023);
140
- bytes.push(
141
- 240 | codePoint >> 18,
142
- 128 | codePoint >> 12 & 63,
143
- 128 | codePoint >> 6 & 63,
144
- 128 | codePoint & 63
145
- );
146
- }
147
- }
148
- return new Uint8Array(bytes);
149
- }
150
- function bytesToString(bytes) {
151
- if (typeof Buffer !== "undefined" && Buffer.from) {
152
- return Buffer.from(bytes).toString("utf8");
153
- }
154
- if (typeof TextDecoder !== "undefined") {
155
- return new TextDecoder().decode(bytes);
156
- }
157
- let str = "";
158
- let i = 0;
159
- while (i < bytes.length) {
160
- const byte = bytes[i];
161
- if (byte < 128) {
162
- str += String.fromCharCode(byte);
163
- i++;
164
- } else if ((byte & 224) === 192) {
165
- str += String.fromCharCode((byte & 31) << 6 | bytes[i + 1] & 63);
166
- i += 2;
167
- } else if ((byte & 240) === 224) {
168
- str += String.fromCharCode(
169
- (byte & 15) << 12 | (bytes[i + 1] & 63) << 6 | bytes[i + 2] & 63
170
- );
171
- i += 3;
172
- } else {
173
- const codePoint = ((byte & 7) << 18 | (bytes[i + 1] & 63) << 12 | (bytes[i + 2] & 63) << 6 | bytes[i + 3] & 63) - 65536;
174
- str += String.fromCharCode(
175
- 55296 + (codePoint >> 10),
176
- 56320 + (codePoint & 1023)
177
- );
178
- i += 4;
179
- }
180
- }
181
- return str;
182
- }
183
- var init_encoding = __esm({
184
- "src/utils/encoding.ts"() {
185
- "use strict";
186
- }
187
- });
188
-
189
- // src/utils/crypto-utils.ts
190
- function concatBytes(...arrays) {
191
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
192
- const result = new Uint8Array(totalLength);
193
- let offset = 0;
194
- for (const arr of arrays) {
195
- result.set(arr, offset);
196
- offset += arr.length;
197
- }
198
- return result;
199
- }
200
- function hexToBytes(hex) {
201
- return fromHex(hex);
202
- }
203
- function bytesToHex(bytes) {
204
- return toHex(bytes);
205
- }
206
- function processWalletPublicKey(publicKey) {
207
- const publicKeyHex = typeof publicKey === "string" ? publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey : bytesToHex(publicKey);
208
- const publicKeyBytes = hexToBytes(publicKeyHex);
209
- return publicKeyBytes.length === 64 ? concatBytes(new Uint8Array([4]), publicKeyBytes) : publicKeyBytes;
210
- }
211
- function processWalletPrivateKey(privateKey) {
212
- const privateKeyHex = typeof privateKey === "string" ? privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey : bytesToHex(privateKey);
213
- return hexToBytes(privateKeyHex);
214
- }
215
- function parseEncryptedDataBuffer(encryptedBuffer) {
216
- return {
217
- iv: encryptedBuffer.slice(0, 16),
218
- ephemPublicKey: encryptedBuffer.slice(16, 81),
219
- // 65 bytes for uncompressed public key
220
- ciphertext: encryptedBuffer.slice(81, -32),
221
- mac: encryptedBuffer.slice(-32)
222
- };
223
- }
224
- var init_crypto_utils = __esm({
225
- "src/utils/crypto-utils.ts"() {
226
- "use strict";
227
- init_encoding();
228
- }
229
- });
230
-
231
- // src/crypto/services/WalletKeyEncryptionService.ts
232
- var WalletKeyEncryptionService;
233
- var init_WalletKeyEncryptionService = __esm({
234
- "src/crypto/services/WalletKeyEncryptionService.ts"() {
235
- "use strict";
236
- init_crypto_utils();
237
- init_encoding();
238
- WalletKeyEncryptionService = class {
239
- eciesProvider;
240
- constructor(config) {
241
- this.eciesProvider = config.eciesProvider;
242
- }
243
- /**
244
- * Encrypts data using a wallet's public key.
245
- *
246
- * @param data - The plaintext message to encrypt for the wallet owner.
247
- * @param publicKey - The recipient wallet's public key for encryption.
248
- * @returns A promise that resolves to the encrypted data as a hex string.
249
- * @throws {Error} When encryption fails due to invalid key format.
250
- *
251
- * @example
252
- * ```typescript
253
- * const encrypted = await processor.encryptWithWalletPublicKey(
254
- * "Secret message",
255
- * "0x04..." // 65-byte uncompressed public key
256
- * );
257
- * console.log(`Encrypted: ${encrypted}`);
258
- * ```
259
- */
260
- async encryptWithWalletPublicKey(data, publicKey) {
261
- const publicKeyBytes = processWalletPublicKey(publicKey);
262
- const dataBytes = stringToBytes(data);
263
- const encrypted = await this.eciesProvider.encrypt(
264
- publicKeyBytes,
265
- dataBytes
266
- );
267
- const result = concatBytes(
268
- encrypted.iv,
269
- encrypted.ephemPublicKey,
270
- encrypted.ciphertext,
271
- encrypted.mac
272
- );
273
- return bytesToHex(result);
274
- }
275
- /**
276
- * Decrypts data using a wallet's private key.
277
- *
278
- * @param encryptedData - The hex-encoded encrypted data to decrypt.
279
- * @param privateKey - The wallet's private key for decryption.
280
- * @returns A promise that resolves to the decrypted plaintext message.
281
- * @throws {Error} When decryption fails due to invalid data or key format.
282
- *
283
- * @example
284
- * ```typescript
285
- * const decrypted = await processor.decryptWithWalletPrivateKey(
286
- * encryptedHexString,
287
- * "0x..." // 32-byte private key
288
- * );
289
- * console.log(`Decrypted: ${decrypted}`);
290
- * ```
291
- */
292
- async decryptWithWalletPrivateKey(encryptedData, privateKey) {
293
- const privateKeyBytes = processWalletPrivateKey(privateKey);
294
- const encryptedBytes = hexToBytes(encryptedData);
295
- const encrypted = parseEncryptedDataBuffer(encryptedBytes);
296
- const decrypted = await this.eciesProvider.decrypt(
297
- privateKeyBytes,
298
- encrypted
299
- );
300
- return bytesToString(decrypted);
301
- }
302
- /**
303
- * Encrypts a Uint8Array with a wallet public key
304
- *
305
- * @param data - Binary data to encrypt
306
- * @param publicKey - Public key as hex string or Uint8Array
307
- * @returns Encrypted data structure
308
- */
309
- async encryptBinary(data, publicKey) {
310
- const publicKeyBytes = processWalletPublicKey(publicKey);
311
- return this.eciesProvider.encrypt(publicKeyBytes, data);
312
- }
313
- /**
314
- * Decrypts to a Uint8Array with a wallet private key
315
- *
316
- * @param encrypted - Encrypted data structure
317
- * @param privateKey - Private key as hex string or Uint8Array
318
- * @returns Decrypted binary data
319
- */
320
- async decryptBinary(encrypted, privateKey) {
321
- const privateKeyBytes = processWalletPrivateKey(privateKey);
322
- return this.eciesProvider.decrypt(privateKeyBytes, encrypted);
323
- }
324
- /**
325
- * Gets the underlying ECIES provider
326
- *
327
- * @returns The ECIES provider instance
328
- */
329
- getECIESProvider() {
330
- return this.eciesProvider;
331
- }
332
- };
333
- }
334
- });
335
-
336
- // src/crypto/ecies/constants.ts
337
- var CURVE, CIPHER, KDF, MAC, FORMAT;
338
- var init_constants = __esm({
339
- "src/crypto/ecies/constants.ts"() {
340
- "use strict";
341
- CURVE = {
342
- /** The elliptic curve used (secp256k1 - same as Bitcoin/Ethereum) */
343
- name: "secp256k1",
344
- /** Private key length in bytes */
345
- PRIVATE_KEY_LENGTH: 32,
346
- /** Compressed public key length in bytes (0x02 or 0x03 prefix + 32 bytes) */
347
- COMPRESSED_PUBLIC_KEY_LENGTH: 33,
348
- /** Uncompressed public key length in bytes (0x04 prefix + 64 bytes) */
349
- UNCOMPRESSED_PUBLIC_KEY_LENGTH: 65,
350
- /** ECDH shared secret X coordinate length */
351
- SHARED_SECRET_LENGTH: 32,
352
- /** Public key prefixes */
353
- PREFIX: {
354
- /** Uncompressed public key prefix */
355
- UNCOMPRESSED: 4,
356
- /** Compressed public key prefix for even Y */
357
- COMPRESSED_EVEN: 2,
358
- /** Compressed public key prefix for odd Y */
359
- COMPRESSED_ODD: 3
360
- },
361
- /** X coordinate starts at byte 1 (after prefix) */
362
- X_COORDINATE_OFFSET: 1,
363
- /** X coordinate ends at byte 33 (1 + 32) */
364
- X_COORDINATE_END: 33
365
- };
366
- CIPHER = {
367
- /** Cipher algorithm - must match eccrypto */
368
- algorithm: "aes-256-cbc",
369
- /** AES key length in bytes */
370
- KEY_LENGTH: 32,
371
- /** Initialization vector length in bytes */
372
- IV_LENGTH: 16,
373
- /** Block size for AES */
374
- BLOCK_SIZE: 16
375
- };
376
- KDF = {
377
- /** Hash algorithm for key derivation - must match eccrypto */
378
- algorithm: "sha512",
379
- /** Output length of SHA-512 in bytes */
380
- OUTPUT_LENGTH: 64,
381
- /** Encryption key slice (first 32 bytes of KDF output) */
382
- ENCRYPTION_KEY_OFFSET: 0,
383
- ENCRYPTION_KEY_LENGTH: 32,
384
- /** MAC key slice (last 32 bytes of KDF output) */
385
- MAC_KEY_OFFSET: 32,
386
- MAC_KEY_LENGTH: 32
387
- };
388
- MAC = {
389
- /** MAC algorithm - must match eccrypto */
390
- algorithm: "sha256",
391
- /** HMAC-SHA256 output length in bytes */
392
- LENGTH: 32
393
- };
394
- FORMAT = {
395
- /** Offsets for each component in serialized format */
396
- IV_OFFSET: 0,
397
- IV_LENGTH: CIPHER.IV_LENGTH,
398
- /** Ephemeral public key (always uncompressed in eccrypto format) */
399
- EPHEMERAL_KEY_OFFSET: CIPHER.IV_LENGTH,
400
- EPHEMERAL_KEY_LENGTH: CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
401
- /** Ciphertext starts after IV and ephemeral key */
402
- CIPHERTEXT_OFFSET: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
403
- /** MAC is always the last 32 bytes */
404
- MAC_LENGTH: MAC.LENGTH,
405
- /** Minimum size of encrypted data (IV + ephemKey + MAC, no ciphertext) */
406
- MIN_ENCRYPTED_LENGTH: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + MAC.LENGTH,
407
- /**
408
- * Helper to calculate total length of encrypted data
409
- *
410
- * @param ciphertextLength - Length of the ciphertext portion
411
- * @returns Total length including all components
412
- */
413
- getTotalLength: (ciphertextLength) => CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + ciphertextLength + MAC.LENGTH
414
- };
415
- }
416
- });
417
-
418
- // src/crypto/ecies/interface.ts
419
- function isECIESEncrypted(obj) {
420
- if (!obj || typeof obj !== "object") return false;
421
- const enc = obj;
422
- const isUint8Array = (value) => {
423
- return value instanceof Uint8Array || typeof Buffer !== "undefined" && Buffer.isBuffer(value);
424
- };
425
- return isUint8Array(enc.iv) && enc.iv.length === CIPHER.IV_LENGTH && isUint8Array(enc.ephemPublicKey) && (enc.ephemPublicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH || enc.ephemPublicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) && isUint8Array(enc.ciphertext) && enc.ciphertext.length > 0 && isUint8Array(enc.mac) && enc.mac.length === MAC.LENGTH;
426
- }
427
- var ECIESError;
428
- var init_interface = __esm({
429
- "src/crypto/ecies/interface.ts"() {
430
- "use strict";
431
- init_constants();
432
- ECIESError = class extends Error {
433
- constructor(message, code, cause) {
434
- super(message);
435
- this.code = code;
436
- this.cause = cause;
437
- this.name = "ECIESError";
438
- }
439
- };
440
- }
441
- });
442
-
443
- // src/crypto/ecies/utils.ts
444
- function hexToBytes2(hex) {
445
- if (hex.length % 2 !== 0) {
446
- throw new Error("Hex string must have even length");
447
- }
448
- const bytes = new Uint8Array(hex.length / 2);
449
- for (let i = 0; i < hex.length; i += 2) {
450
- bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
451
- }
452
- return bytes;
453
- }
454
- function bytesToHex2(bytes) {
455
- return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
456
- }
457
- function stringToBytes2(str) {
458
- return new TextEncoder().encode(str);
459
- }
460
- function bytesToString2(bytes) {
461
- return new TextDecoder().decode(bytes);
462
- }
463
- function concatBytes2(...arrays) {
464
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
465
- const result = new Uint8Array(totalLength);
466
- let offset = 0;
467
- for (const arr of arrays) {
468
- result.set(arr, offset);
469
- offset += arr.length;
470
- }
471
- return result;
472
- }
473
- function constantTimeEqual(a, b) {
474
- if (a.length !== b.length) return false;
475
- let result = 0;
476
- for (let i = 0; i < a.length; i++) {
477
- result |= a[i] ^ b[i];
478
- }
479
- return result === 0;
480
- }
481
- var init_utils = __esm({
482
- "src/crypto/ecies/utils.ts"() {
483
- "use strict";
484
- }
485
- });
486
-
487
- // src/crypto/ecies/base.ts
488
- var BaseECIESUint8;
489
- var init_base = __esm({
490
- "src/crypto/ecies/base.ts"() {
491
- "use strict";
492
- init_interface();
493
- init_constants();
494
- init_utils();
495
- BaseECIESUint8 = class _BaseECIESUint8 {
496
- // Cache for validated public keys to avoid repeated validation
497
- static validatedKeys = /* @__PURE__ */ new WeakMap();
498
- /**
499
- * Normalizes a public key to uncompressed format.
500
- *
501
- * @param publicKey - Public key in any format.
502
- * @returns Uncompressed public key (65 bytes).
503
- * @throws {ECIESError} If key format is invalid.
504
- */
505
- normalizePublicKey(publicKey) {
506
- if (_BaseECIESUint8.validatedKeys.has(publicKey)) {
507
- return publicKey;
508
- }
509
- if (publicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH) {
510
- if (publicKey[0] !== CURVE.PREFIX.UNCOMPRESSED) {
511
- throw new ECIESError(
512
- "Invalid uncompressed public key prefix",
513
- "INVALID_KEY"
514
- );
515
- }
516
- if (!this.validatePublicKey(publicKey)) {
517
- throw new ECIESError("Invalid public key", "INVALID_KEY");
518
- }
519
- _BaseECIESUint8.validatedKeys.set(publicKey, true);
520
- return publicKey;
521
- }
522
- if (publicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) {
523
- const decompressed = this.decompressPublicKey(publicKey);
524
- if (!decompressed) {
525
- throw new ECIESError("Failed to decompress public key", "INVALID_KEY");
526
- }
527
- _BaseECIESUint8.validatedKeys.set(decompressed, true);
528
- return decompressed;
529
- }
530
- throw new ECIESError(
531
- `Invalid public key length: ${publicKey.length}`,
532
- "INVALID_KEY"
533
- );
534
- }
535
- /**
536
- * Encrypts data using ECIES.
537
- *
538
- * @param publicKey - The recipient's public key (compressed or uncompressed)
539
- * @param message - The data to encrypt
540
- * @returns Promise resolving to encrypted data structure
541
- */
542
- async encrypt(publicKey, message) {
543
- try {
544
- if (!(publicKey instanceof Uint8Array)) {
545
- throw new ECIESError("Public key must be a Uint8Array", "INVALID_KEY");
546
- }
547
- if (!(message instanceof Uint8Array)) {
548
- throw new ECIESError(
549
- "Message must be a Uint8Array",
550
- "ENCRYPTION_FAILED"
551
- );
552
- }
553
- if (publicKey.length === 0) {
554
- throw new ECIESError("Public key cannot be empty", "INVALID_KEY");
555
- }
556
- const pubKey = this.normalizePublicKey(publicKey);
557
- let ephemeralPrivateKey;
558
- do {
559
- ephemeralPrivateKey = this.generateRandomBytes(
560
- CURVE.PRIVATE_KEY_LENGTH
561
- );
562
- } while (!this.verifyPrivateKey(ephemeralPrivateKey));
563
- const ephemeralPublicKey = this.createPublicKey(
564
- ephemeralPrivateKey,
565
- false
566
- );
567
- if (!ephemeralPublicKey) {
568
- throw new ECIESError(
569
- "Failed to generate ephemeral public key",
570
- "ENCRYPTION_FAILED"
571
- );
572
- }
573
- const sharedSecret = this.performECDH(pubKey, ephemeralPrivateKey);
574
- const kdf = this.sha512(sharedSecret);
575
- const encryptionKey = kdf.slice(
576
- KDF.ENCRYPTION_KEY_OFFSET,
577
- KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
578
- );
579
- const macKey = kdf.slice(
580
- KDF.MAC_KEY_OFFSET,
581
- KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
582
- );
583
- const iv = this.generateRandomBytes(CIPHER.IV_LENGTH);
584
- const ciphertext = await this.aesEncrypt(encryptionKey, iv, message);
585
- const macData = concatBytes2(iv, ephemeralPublicKey, ciphertext);
586
- const mac = this.hmacSha256(macKey, macData);
587
- this.clearBuffer(ephemeralPrivateKey);
588
- this.clearBuffer(sharedSecret);
589
- this.clearBuffer(kdf);
590
- return {
591
- iv,
592
- ephemPublicKey: ephemeralPublicKey,
593
- ciphertext,
594
- mac
595
- };
596
- } catch (error) {
597
- if (error instanceof ECIESError) throw error;
598
- throw new ECIESError(
599
- `Encryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
600
- "ENCRYPTION_FAILED",
601
- error instanceof Error ? error : void 0
602
- );
603
- }
604
- }
605
- /**
606
- * Decrypts ECIES encrypted data.
607
- *
608
- * @param privateKey - The recipient's private key (32 bytes)
609
- * @param encrypted - The encrypted data structure from encrypt()
610
- * @returns Promise resolving to the original plaintext
611
- */
612
- async decrypt(privateKey, encrypted) {
613
- try {
614
- if (!(privateKey instanceof Uint8Array)) {
615
- throw new ECIESError("Private key must be a Uint8Array", "INVALID_KEY");
616
- }
617
- if (!isECIESEncrypted(encrypted)) {
618
- throw new ECIESError(
619
- "Invalid encrypted data structure",
620
- "DECRYPTION_FAILED"
621
- );
622
- }
623
- if (privateKey.length !== CURVE.PRIVATE_KEY_LENGTH) {
624
- throw new ECIESError(
625
- `Invalid private key length: ${privateKey.length}`,
626
- "INVALID_KEY"
627
- );
628
- }
629
- if (!this.verifyPrivateKey(privateKey)) {
630
- throw new ECIESError("Invalid private key", "INVALID_KEY");
631
- }
632
- const ephemeralPublicKey = this.normalizePublicKey(
633
- encrypted.ephemPublicKey
634
- );
635
- const sharedSecret = this.performECDH(ephemeralPublicKey, privateKey);
636
- const kdf = this.sha512(sharedSecret);
637
- const encryptionKey = kdf.slice(
638
- KDF.ENCRYPTION_KEY_OFFSET,
639
- KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
640
- );
641
- const macKey = kdf.slice(
642
- KDF.MAC_KEY_OFFSET,
643
- KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
644
- );
645
- const macData = concatBytes2(
646
- encrypted.iv,
647
- encrypted.ephemPublicKey,
648
- encrypted.ciphertext
649
- );
650
- const expectedMac = this.hmacSha256(macKey, macData);
651
- if (!constantTimeEqual(encrypted.mac, expectedMac)) {
652
- throw new ECIESError("MAC verification failed", "MAC_MISMATCH");
653
- }
654
- const decrypted = await this.aesDecrypt(
655
- encryptionKey,
656
- encrypted.iv,
657
- encrypted.ciphertext
658
- );
659
- this.clearBuffer(sharedSecret);
660
- this.clearBuffer(kdf);
661
- return decrypted;
662
- } catch (error) {
663
- if (error instanceof ECIESError) throw error;
664
- throw new ECIESError(
665
- `Decryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
666
- "DECRYPTION_FAILED",
667
- error instanceof Error ? error : void 0
668
- );
669
- }
670
- }
671
- /**
672
- * Clears sensitive data from memory using multi-pass overwrite.
673
- *
674
- * @remarks
675
- * Uses multiple passes with different patterns to make it harder
676
- * for JIT compilers to optimize away the operation. While not
677
- * guaranteed in JavaScript, this is a best-effort approach to
678
- * clear sensitive data from memory.
679
- *
680
- * @param buffer - The buffer to clear
681
- */
682
- clearBuffer(buffer) {
683
- if (buffer && buffer.length > 0) {
684
- buffer.fill(0);
685
- buffer.fill(255);
686
- buffer.fill(170);
687
- buffer.fill(0);
688
- for (let i = 0; i < buffer.length; i++) {
689
- buffer[i] = i & 255 ^ 90;
690
- }
691
- buffer.fill(0);
692
- }
693
- }
694
- };
695
- }
696
- });
697
-
698
119
  // src/schemas/dataSchema.schema.json
699
120
  var dataSchema_schema_default;
700
121
  var init_dataSchema_schema = __esm({
@@ -758,8 +179,10 @@ var init_dataSchema_schema = __esm({
758
179
  // src/utils/schemaValidation.ts
759
180
  import Ajv from "ajv";
760
181
  import addFormats from "ajv-formats";
761
- function validateDataSchema(schema) {
762
- return schemaValidator.validateDataSchema(schema);
182
+ function validateDataSchemaAgainstMetaSchema(schema) {
183
+ const validator = schemaValidator;
184
+ validator.validateDataSchemaAgainstMetaSchema(schema);
185
+ return schema;
763
186
  }
764
187
  function validateDataAgainstSchema(data, schema) {
765
188
  return schemaValidator.validateDataAgainstSchema(data, schema);
@@ -792,9 +215,9 @@ var init_schemaValidation = __esm({
792
215
  this.dataSchemaValidator = this.ajv.compile(dataSchema_schema_default);
793
216
  }
794
217
  /**
795
- * Validates a data schema against the Vana meta-schema
218
+ * Validates a data schema definition against the Vana meta-schema
796
219
  *
797
- * @param schema - The data schema to validate
220
+ * @param schema - The data schema definition to validate
798
221
  * @throws SchemaValidationError if invalid
799
222
  * @example
800
223
  * ```typescript
@@ -813,10 +236,10 @@ var init_schemaValidation = __esm({
813
236
  * }
814
237
  * };
815
238
  *
816
- * validator.validateDataSchema(schema); // throws if invalid
239
+ * validator.validateDataSchemaAgainstMetaSchema(schema); // throws if invalid
817
240
  * ```
818
241
  */
819
- validateDataSchema(schema) {
242
+ validateDataSchemaAgainstMetaSchema(schema) {
820
243
  const isValid = this.dataSchemaValidator(schema);
821
244
  if (!isValid) {
822
245
  const errors = this.dataSchemaValidator.errors || [];
@@ -836,10 +259,10 @@ var init_schemaValidation = __esm({
836
259
  }
837
260
  }
838
261
  /**
839
- * Validates data against a JSON Schema from a schema
262
+ * Validates data against a JSON Schema
840
263
  *
841
264
  * @param data - The data to validate
842
- * @param schema - The schema containing the validation rules (DataSchema or Schema)
265
+ * @param schema - The schema containing the validation rules (must have been validated or fetched from chain)
843
266
  * @throws SchemaValidationError if invalid
844
267
  * @example
845
268
  * ```typescript
@@ -849,25 +272,22 @@ var init_schemaValidation = __esm({
849
272
  * const schema = await vana.schemas.get(1);
850
273
  * validator.validateDataAgainstSchema(userData, schema);
851
274
  *
852
- * // Also works with DataSchema object
853
- * const dataSchema: DataSchema = {
275
+ * // Also works with pre-validated DataSchema object
276
+ * const dataSchema = validator.validateDataSchemaAgainstMetaSchema({
854
277
  * name: "User Profile",
855
278
  * version: "1.0.0",
856
279
  * dialect: "json",
857
280
  * schema: { type: "object", properties: { name: { type: "string" } } }
858
- * };
281
+ * });
859
282
  * validator.validateDataAgainstSchema(userData, dataSchema);
860
283
  * ```
861
284
  */
862
285
  validateDataAgainstSchema(data, schema) {
863
- if (!("id" in schema)) {
864
- this.validateDataSchema(schema);
865
- }
866
286
  if (schema.dialect !== "json") {
867
- throw new SchemaValidationError(
868
- `Data validation only supported for JSON dialect, got: ${schema.dialect}`,
869
- []
287
+ console.warn(
288
+ `[SchemaValidator] Data validation skipped: dialect '${schema.dialect}' does not support data validation. Only JSON schemas can validate data structure.`
870
289
  );
290
+ return;
871
291
  }
872
292
  if (typeof schema.schema !== "object") {
873
293
  throw new SchemaValidationError(
@@ -933,9 +353,9 @@ var init_schemaValidation = __esm({
933
353
  }
934
354
  }
935
355
  /**
936
- * Fetches and validates a schema from a URL
356
+ * Fetches and validates a data schema from a URL
937
357
  *
938
- * @param url - The URL to fetch the schema from
358
+ * @param url - The URL to fetch the data schema from
939
359
  * @returns The validated data schema
940
360
  * @throws SchemaValidationError if invalid or fetch fails
941
361
  * @example
@@ -951,7 +371,7 @@ var init_schemaValidation = __esm({
951
371
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
952
372
  }
953
373
  const schema = await response.json();
954
- this.validateDataSchema(schema);
374
+ this.validateDataSchemaAgainstMetaSchema(schema);
955
375
  if (schema.dialect === "sqlite" && typeof schema.schema === "string") {
956
376
  this.validateSQLiteDDL(schema.schema, schema.dialectVersion);
957
377
  }
@@ -1600,19 +1020,19 @@ var init_eventMappings = __esm({
1600
1020
  // DataRegistry operations
1601
1021
  addFile: {
1602
1022
  contract: "DataRegistry",
1603
- event: "FileAdded"
1023
+ event: "FileAddedV2"
1604
1024
  },
1605
1025
  addFileWithPermissionsAndSchema: {
1606
1026
  contract: "DataRegistry",
1607
- event: "FileAdded"
1027
+ event: "FileAddedV2"
1608
1028
  },
1609
1029
  addFileWithSchema: {
1610
1030
  contract: "DataRegistry",
1611
- event: "FileAdded"
1031
+ event: "FileAddedV2"
1612
1032
  },
1613
1033
  addFileWithPermissions: {
1614
1034
  contract: "DataRegistry",
1615
- event: "FileAdded"
1035
+ event: "FileAddedV2"
1616
1036
  },
1617
1037
  addRefinement: {
1618
1038
  contract: "DataRegistry",
@@ -3099,6 +2519,37 @@ var init_DataRegistryImplementation = __esm({
3099
2519
  name: "FileAdded",
3100
2520
  type: "event"
3101
2521
  },
2522
+ {
2523
+ anonymous: false,
2524
+ inputs: [
2525
+ {
2526
+ indexed: true,
2527
+ internalType: "uint256",
2528
+ name: "fileId",
2529
+ type: "uint256"
2530
+ },
2531
+ {
2532
+ indexed: true,
2533
+ internalType: "address",
2534
+ name: "ownerAddress",
2535
+ type: "address"
2536
+ },
2537
+ {
2538
+ indexed: false,
2539
+ internalType: "string",
2540
+ name: "url",
2541
+ type: "string"
2542
+ },
2543
+ {
2544
+ indexed: false,
2545
+ internalType: "uint256",
2546
+ name: "schemaId",
2547
+ type: "uint256"
2548
+ }
2549
+ ],
2550
+ name: "FileAddedV2",
2551
+ type: "event"
2552
+ },
3102
2553
  {
3103
2554
  anonymous: false,
3104
2555
  inputs: [
@@ -3338,6 +2789,19 @@ var init_DataRegistryImplementation = __esm({
3338
2789
  name: "Upgraded",
3339
2790
  type: "event"
3340
2791
  },
2792
+ {
2793
+ inputs: [],
2794
+ name: "DATA_PORTABILITY_ROLE",
2795
+ outputs: [
2796
+ {
2797
+ internalType: "bytes32",
2798
+ name: "",
2799
+ type: "bytes32"
2800
+ }
2801
+ ],
2802
+ stateMutability: "view",
2803
+ type: "function"
2804
+ },
3341
2805
  {
3342
2806
  inputs: [],
3343
2807
  name: "DEFAULT_ADMIN_ROLE",
@@ -3432,6 +2896,41 @@ var init_DataRegistryImplementation = __esm({
3432
2896
  stateMutability: "nonpayable",
3433
2897
  type: "function"
3434
2898
  },
2899
+ {
2900
+ inputs: [
2901
+ {
2902
+ internalType: "uint256",
2903
+ name: "fileId",
2904
+ type: "uint256"
2905
+ },
2906
+ {
2907
+ components: [
2908
+ {
2909
+ internalType: "address",
2910
+ name: "account",
2911
+ type: "address"
2912
+ },
2913
+ {
2914
+ internalType: "string",
2915
+ name: "key",
2916
+ type: "string"
2917
+ }
2918
+ ],
2919
+ internalType: "struct IDataRegistry.Permission[]",
2920
+ name: "permissions",
2921
+ type: "tuple[]"
2922
+ },
2923
+ {
2924
+ internalType: "uint256",
2925
+ name: "schemaId",
2926
+ type: "uint256"
2927
+ }
2928
+ ],
2929
+ name: "addFilePermissionsAndSchema",
2930
+ outputs: [],
2931
+ stateMutability: "nonpayable",
2932
+ type: "function"
2933
+ },
3435
2934
  {
3436
2935
  inputs: [
3437
2936
  {
@@ -3646,6 +3145,19 @@ var init_DataRegistryImplementation = __esm({
3646
3145
  stateMutability: "view",
3647
3146
  type: "function"
3648
3147
  },
3148
+ {
3149
+ inputs: [],
3150
+ name: "emitLegacyEvents",
3151
+ outputs: [
3152
+ {
3153
+ internalType: "bool",
3154
+ name: "",
3155
+ type: "bool"
3156
+ }
3157
+ ],
3158
+ stateMutability: "view",
3159
+ type: "function"
3160
+ },
3649
3161
  {
3650
3162
  inputs: [
3651
3163
  {
@@ -3803,6 +3315,11 @@ var init_DataRegistryImplementation = __esm({
3803
3315
  name: "url",
3804
3316
  type: "string"
3805
3317
  },
3318
+ {
3319
+ internalType: "uint256",
3320
+ name: "schemaId",
3321
+ type: "uint256"
3322
+ },
3806
3323
  {
3807
3324
  internalType: "uint256",
3808
3325
  name: "addedAtBlock",
@@ -4086,6 +3603,19 @@ var init_DataRegistryImplementation = __esm({
4086
3603
  stateMutability: "nonpayable",
4087
3604
  type: "function"
4088
3605
  },
3606
+ {
3607
+ inputs: [
3608
+ {
3609
+ internalType: "bool",
3610
+ name: "newEmitLegacyEvents",
3611
+ type: "bool"
3612
+ }
3613
+ ],
3614
+ name: "updateEmitLegacyEvents",
3615
+ outputs: [],
3616
+ stateMutability: "nonpayable",
3617
+ type: "function"
3618
+ },
4089
3619
  {
4090
3620
  inputs: [
4091
3621
  {
@@ -36891,7 +36421,7 @@ var init_schemas = __esm({
36891
36421
  dialect,
36892
36422
  schema: schemaDefinition
36893
36423
  };
36894
- validateDataSchema(dataSchema);
36424
+ validateDataSchemaAgainstMetaSchema(dataSchema);
36895
36425
  if (!this.context.storageManager) {
36896
36426
  if (this.context.validateStorageRequired) {
36897
36427
  this.context.validateStorageRequired();
@@ -37000,7 +36530,7 @@ var init_schemas = __esm({
37000
36530
  `Invalid schema definition format for schema ${schemaId}`
37001
36531
  );
37002
36532
  }
37003
- validateDataSchema(definition);
36533
+ validateDataSchemaAgainstMetaSchema(definition);
37004
36534
  const dataSchema = definition;
37005
36535
  if (dataSchema.name !== metadata.name) {
37006
36536
  throw new Error(
@@ -37335,7 +36865,7 @@ var init_schemas = __esm({
37335
36865
  try {
37336
36866
  const definition = await fetchFromUrl(schema.definitionUrl);
37337
36867
  if (definition && typeof definition === "object") {
37338
- validateDataSchema(definition);
36868
+ validateDataSchemaAgainstMetaSchema(definition);
37339
36869
  const dataSchema = definition;
37340
36870
  schema.version = dataSchema.version;
37341
36871
  schema.description = dataSchema.description;
@@ -37354,204 +36884,123 @@ var init_schemas = __esm({
37354
36884
  }
37355
36885
  });
37356
36886
 
37357
- // src/crypto/ecies/browser.ts
37358
- import * as secp256k12 from "@noble/secp256k1";
37359
- import { hmac } from "@noble/hashes/hmac";
37360
- import { sha256 as sha2562, sha512 as nobleSha512 } from "@noble/hashes/sha2";
37361
- var BrowserECIESUint8Provider;
37362
- var init_browser = __esm({
37363
- "src/crypto/ecies/browser.ts"() {
37364
- "use strict";
37365
- init_base();
37366
- BrowserECIESUint8Provider = class extends BaseECIESUint8 {
37367
- generateRandomBytes(length) {
37368
- const bytes = new Uint8Array(length);
37369
- crypto.getRandomValues(bytes);
37370
- return bytes;
37371
- }
37372
- verifyPrivateKey(privateKey) {
37373
- try {
37374
- return secp256k12.utils.isValidPrivateKey(privateKey);
37375
- } catch {
37376
- return false;
37377
- }
37378
- }
37379
- createPublicKey(privateKey, compressed) {
37380
- try {
37381
- return secp256k12.getPublicKey(privateKey, compressed);
37382
- } catch {
37383
- return null;
37384
- }
37385
- }
37386
- validatePublicKey(publicKey) {
37387
- try {
37388
- secp256k12.Point.fromHex(publicKey);
37389
- return true;
37390
- } catch {
37391
- return false;
37392
- }
37393
- }
37394
- decompressPublicKey(publicKey) {
37395
- try {
37396
- const point = secp256k12.Point.fromHex(publicKey);
37397
- return point.toRawBytes(false);
37398
- } catch {
37399
- return null;
37400
- }
37401
- }
37402
- performECDH(publicKey, privateKey) {
37403
- try {
37404
- const sharedPoint = secp256k12.getSharedSecret(
37405
- privateKey,
37406
- publicKey,
37407
- true
37408
- );
37409
- return sharedPoint.slice(1);
37410
- } catch (error) {
37411
- throw new Error(
37412
- `ECDH failed: ${error instanceof Error ? error.message : "Unknown error"}`
37413
- );
37414
- }
37415
- }
37416
- sha512(data) {
37417
- return nobleSha512(data);
37418
- }
37419
- hmacSha256(key, data) {
37420
- return hmac(sha2562, key, data);
37421
- }
37422
- async aesEncrypt(key, iv, plaintext) {
37423
- const cryptoKey = await crypto.subtle.importKey(
37424
- "raw",
37425
- key,
37426
- { name: "AES-CBC" },
37427
- false,
37428
- ["encrypt"]
37429
- );
37430
- const encrypted = await crypto.subtle.encrypt(
37431
- { name: "AES-CBC", iv },
37432
- cryptoKey,
37433
- plaintext
37434
- );
37435
- return new Uint8Array(encrypted);
37436
- }
37437
- async aesDecrypt(key, iv, ciphertext) {
37438
- const cryptoKey = await crypto.subtle.importKey(
37439
- "raw",
37440
- key,
37441
- { name: "AES-CBC" },
37442
- false,
37443
- ["decrypt"]
37444
- );
37445
- const decrypted = await crypto.subtle.decrypt(
37446
- { name: "AES-CBC", iv },
37447
- cryptoKey,
37448
- ciphertext
37449
- );
37450
- return new Uint8Array(decrypted);
37451
- }
37452
- };
37453
- }
37454
- });
37455
-
37456
36887
  // src/platform/browser.ts
37457
36888
  var browser_exports = {};
37458
36889
  __export(browser_exports, {
37459
- BrowserPlatformAdapter: () => BrowserPlatformAdapter
36890
+ BrowserPlatformAdapter: () => BrowserPlatformAdapter,
36891
+ browserPlatformAdapter: () => browserPlatformAdapter
37460
36892
  });
37461
- import * as secp256k13 from "@noble/secp256k1";
37462
- var getOpenPGP2, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter;
37463
- var init_browser2 = __esm({
36893
+ var getOpenPGP2, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter, browserPlatformAdapter;
36894
+ var init_browser = __esm({
37464
36895
  "src/platform/browser.ts"() {
37465
36896
  "use strict";
36897
+ init_crypto_utils();
37466
36898
  init_pgp_utils();
37467
36899
  init_error_utils();
37468
36900
  init_lazy_import();
37469
- init_WalletKeyEncryptionService();
37470
- init_crypto_utils();
37471
- init_utils();
37472
- init_browser();
37473
36901
  getOpenPGP2 = lazyImport(() => import("openpgp"));
37474
36902
  BrowserCryptoAdapter = class {
37475
- eciesProvider = new BrowserECIESUint8Provider();
37476
- walletKeyEncryptionService = new WalletKeyEncryptionService({
37477
- eciesProvider: this.eciesProvider
37478
- });
37479
36903
  async encryptWithPublicKey(data, publicKeyHex) {
37480
36904
  try {
37481
- const publicKeyBytes = hexToBytes2(publicKeyHex);
37482
- const encrypted = await this.eciesProvider.encrypt(
37483
- publicKeyBytes,
37484
- stringToBytes2(data)
36905
+ const eccrypto = await import("eccrypto-js");
36906
+ const publicKeyBuffer = Buffer.from(publicKeyHex, "hex");
36907
+ const encrypted = await eccrypto.encrypt(
36908
+ publicKeyBuffer,
36909
+ Buffer.from(data, "utf8")
37485
36910
  );
37486
- const result = concatBytes2(
36911
+ const result = Buffer.concat([
37487
36912
  encrypted.iv,
37488
36913
  encrypted.ephemPublicKey,
37489
36914
  encrypted.ciphertext,
37490
36915
  encrypted.mac
37491
- );
37492
- return bytesToHex2(result);
36916
+ ]);
36917
+ return result.toString("hex");
37493
36918
  } catch (error) {
37494
- throw wrapCryptoError("encryptWithPublicKey", error);
36919
+ throw new Error(`Encryption failed: ${error}`);
37495
36920
  }
37496
36921
  }
37497
36922
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
37498
36923
  try {
37499
- const encryptedBytes = hexToBytes2(encryptedData);
37500
- const privateKeyBytes = hexToBytes2(privateKeyHex);
37501
- const encrypted = parseEncryptedDataBuffer(encryptedBytes);
37502
- const decrypted = await this.eciesProvider.decrypt(
37503
- privateKeyBytes,
37504
- encrypted
36924
+ const eccrypto = await import("eccrypto-js");
36925
+ const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
36926
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
36927
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
36928
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
36929
+ const decryptedBuffer = await eccrypto.decrypt(
36930
+ privateKeyBuffer,
36931
+ encryptedObj
37505
36932
  );
37506
- return bytesToString2(decrypted);
36933
+ return decryptedBuffer.toString("utf8");
37507
36934
  } catch (error) {
37508
- throw wrapCryptoError("decryptWithPrivateKey", error);
36935
+ throw new Error(`Decryption failed: ${error}`);
37509
36936
  }
37510
36937
  }
37511
- async encryptWithWalletPublicKey(data, publicKey) {
36938
+ async generateKeyPair() {
37512
36939
  try {
37513
- return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
37514
- data,
37515
- publicKey
37516
- );
36940
+ const eccrypto = await import("eccrypto-js");
36941
+ const privateKeyBytes = new Uint8Array(32);
36942
+ crypto.getRandomValues(privateKeyBytes);
36943
+ const privateKey = Buffer.from(privateKeyBytes);
36944
+ const publicKey = eccrypto.getPublicCompressed(privateKey);
36945
+ return {
36946
+ privateKey: privateKey.toString("hex"),
36947
+ publicKey: publicKey.toString("hex")
36948
+ };
37517
36949
  } catch (error) {
37518
- throw wrapCryptoError("encryptWithWalletPublicKey", error);
36950
+ throw wrapCryptoError("key generation", error);
37519
36951
  }
37520
36952
  }
37521
- async decryptWithWalletPrivateKey(encryptedData, privateKey) {
36953
+ async encryptWithWalletPublicKey(data, publicKey) {
37522
36954
  try {
37523
- return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
37524
- encryptedData,
37525
- privateKey
36955
+ const eccrypto = await import("eccrypto-js");
36956
+ const uncompressedKey = processWalletPublicKey(publicKey);
36957
+ const encryptedBuffer = await eccrypto.encrypt(
36958
+ uncompressedKey,
36959
+ Buffer.from(data)
37526
36960
  );
36961
+ const result = Buffer.concat([
36962
+ encryptedBuffer.iv,
36963
+ encryptedBuffer.ephemPublicKey,
36964
+ encryptedBuffer.ciphertext,
36965
+ encryptedBuffer.mac
36966
+ ]);
36967
+ return result.toString("hex");
37527
36968
  } catch (error) {
37528
- throw wrapCryptoError("decryptWithWalletPrivateKey", error);
36969
+ throw wrapCryptoError("encrypt with wallet public key", error);
37529
36970
  }
37530
36971
  }
37531
- async generateKeyPair() {
36972
+ async decryptWithWalletPrivateKey(encryptedData, privateKey) {
37532
36973
  try {
37533
- const privateKeyBytes = secp256k13.utils.randomPrivateKey();
37534
- const publicKeyBytes = secp256k13.getPublicKey(privateKeyBytes, true);
37535
- return {
37536
- privateKey: bytesToHex2(privateKeyBytes),
37537
- publicKey: bytesToHex2(publicKeyBytes)
37538
- };
36974
+ const eccrypto = await import("eccrypto-js");
36975
+ const privateKeyBuffer = processWalletPrivateKey(privateKey);
36976
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
36977
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
36978
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
36979
+ const decryptedBuffer = await eccrypto.decrypt(
36980
+ privateKeyBuffer,
36981
+ encryptedObj
36982
+ );
36983
+ return decryptedBuffer.toString("utf8");
37539
36984
  } catch (error) {
37540
- throw wrapCryptoError("generateKeyPair", error);
36985
+ throw wrapCryptoError("decrypt with wallet private key", error);
37541
36986
  }
37542
36987
  }
37543
36988
  async encryptWithPassword(data, password) {
37544
36989
  try {
37545
36990
  const openpgp = await getOpenPGP2();
37546
- const message = await openpgp.createMessage({ binary: data });
36991
+ const message = await openpgp.createMessage({
36992
+ binary: data
36993
+ });
37547
36994
  const encrypted = await openpgp.encrypt({
37548
36995
  message,
37549
36996
  passwords: [password],
37550
36997
  format: "binary"
37551
36998
  });
37552
- return new Uint8Array(encrypted);
36999
+ const response = new Response(encrypted);
37000
+ const arrayBuffer = await response.arrayBuffer();
37001
+ return new Uint8Array(arrayBuffer);
37553
37002
  } catch (error) {
37554
- throw wrapCryptoError("encryptWithPassword", error);
37003
+ throw new Error(`Failed to encrypt with password: ${error}`);
37555
37004
  }
37556
37005
  }
37557
37006
  async decryptWithPassword(encryptedData, password) {
@@ -37560,14 +37009,14 @@ var init_browser2 = __esm({
37560
37009
  const message = await openpgp.readMessage({
37561
37010
  binaryMessage: encryptedData
37562
37011
  });
37563
- const { data } = await openpgp.decrypt({
37012
+ const { data: decrypted } = await openpgp.decrypt({
37564
37013
  message,
37565
37014
  passwords: [password],
37566
37015
  format: "binary"
37567
37016
  });
37568
- return new Uint8Array(data);
37017
+ return new Uint8Array(decrypted);
37569
37018
  } catch (error) {
37570
- throw wrapCryptoError("decryptWithPassword", error);
37019
+ throw new Error(`Failed to decrypt with password: ${error}`);
37571
37020
  }
37572
37021
  }
37573
37022
  };
@@ -37619,6 +37068,9 @@ var init_browser2 = __esm({
37619
37068
  };
37620
37069
  BrowserHttpAdapter = class {
37621
37070
  async fetch(url, options) {
37071
+ if (typeof fetch === "undefined") {
37072
+ throw new Error("Fetch API not available in this browser environment");
37073
+ }
37622
37074
  return fetch(url, options);
37623
37075
  }
37624
37076
  };
@@ -37636,19 +37088,17 @@ var init_browser2 = __esm({
37636
37088
  }
37637
37089
  set(key, value) {
37638
37090
  try {
37639
- if (typeof sessionStorage === "undefined") {
37640
- return;
37091
+ if (typeof sessionStorage !== "undefined") {
37092
+ sessionStorage.setItem(this.prefix + key, value);
37641
37093
  }
37642
- sessionStorage.setItem(this.prefix + key, value);
37643
37094
  } catch {
37644
37095
  }
37645
37096
  }
37646
37097
  delete(key) {
37647
37098
  try {
37648
- if (typeof sessionStorage === "undefined") {
37649
- return;
37099
+ if (typeof sessionStorage !== "undefined") {
37100
+ sessionStorage.removeItem(this.prefix + key);
37650
37101
  }
37651
- sessionStorage.removeItem(this.prefix + key);
37652
37102
  } catch {
37653
37103
  }
37654
37104
  }
@@ -37657,29 +37107,35 @@ var init_browser2 = __esm({
37657
37107
  if (typeof sessionStorage === "undefined") {
37658
37108
  return;
37659
37109
  }
37660
- const keysToRemove = [];
37661
- for (let i = 0; i < sessionStorage.length; i++) {
37662
- const key = sessionStorage.key(i);
37663
- if (key?.startsWith(this.prefix)) {
37664
- keysToRemove.push(key);
37110
+ const keys = Object.keys(sessionStorage);
37111
+ for (const key of keys) {
37112
+ if (key.startsWith(this.prefix)) {
37113
+ sessionStorage.removeItem(key);
37665
37114
  }
37666
37115
  }
37667
- keysToRemove.forEach((key) => sessionStorage.removeItem(key));
37668
37116
  } catch {
37669
37117
  }
37670
37118
  }
37671
37119
  };
37672
37120
  BrowserPlatformAdapter = class {
37673
- crypto = new BrowserCryptoAdapter();
37674
- pgp = new BrowserPGPAdapter();
37675
- http = new BrowserHttpAdapter();
37676
- cache = new BrowserCacheAdapter();
37121
+ crypto;
37122
+ pgp;
37123
+ http;
37124
+ cache;
37677
37125
  platform = "browser";
37126
+ constructor() {
37127
+ this.crypto = new BrowserCryptoAdapter();
37128
+ this.pgp = new BrowserPGPAdapter();
37129
+ this.http = new BrowserHttpAdapter();
37130
+ this.cache = new BrowserCacheAdapter();
37131
+ }
37678
37132
  };
37133
+ browserPlatformAdapter = new BrowserPlatformAdapter();
37679
37134
  }
37680
37135
  });
37681
37136
 
37682
37137
  // src/platform/node.ts
37138
+ init_crypto_utils();
37683
37139
  init_pgp_utils();
37684
37140
  init_error_utils();
37685
37141
 
@@ -37708,129 +37164,15 @@ async function streamToUint8Array(stream) {
37708
37164
 
37709
37165
  // src/platform/node.ts
37710
37166
  init_lazy_import();
37711
- init_WalletKeyEncryptionService();
37712
- init_crypto_utils();
37713
-
37714
- // src/crypto/ecies/node.ts
37715
- init_base();
37716
- import {
37717
- randomBytes,
37718
- createHash,
37719
- createHmac,
37720
- createCipheriv,
37721
- createDecipheriv
37722
- } from "crypto";
37723
- var secp256k1;
37724
- try {
37725
- secp256k1 = __require("secp256k1");
37726
- } catch {
37727
- throw new Error(
37728
- "Native secp256k1 module not found. Please install with: npm install secp256k1\nThis is required for optimal performance in Node.js environments."
37729
- );
37730
- }
37731
- var NodeECIESUint8Provider = class extends BaseECIESUint8 {
37732
- // Identity hash function for ECDH - returns raw X coordinate
37733
- // CRITICAL: Must handle (x, y, output) signature correctly
37734
- identityHashFn = (x, y, output) => {
37735
- if (output && output.length >= 32) {
37736
- output.set(x);
37737
- return output;
37738
- }
37739
- return x;
37740
- };
37741
- generateRandomBytes(length) {
37742
- return new Uint8Array(randomBytes(length));
37743
- }
37744
- verifyPrivateKey(privateKey) {
37745
- return secp256k1.privateKeyVerify(Buffer.from(privateKey)) === true;
37746
- }
37747
- createPublicKey(privateKey, compressed) {
37748
- try {
37749
- return new Uint8Array(
37750
- secp256k1.publicKeyCreate(Buffer.from(privateKey), compressed)
37751
- );
37752
- } catch {
37753
- return null;
37754
- }
37755
- }
37756
- validatePublicKey(publicKey) {
37757
- return secp256k1.publicKeyVerify(Buffer.from(publicKey)) === true;
37758
- }
37759
- decompressPublicKey(publicKey) {
37760
- try {
37761
- return new Uint8Array(
37762
- secp256k1.publicKeyConvert(Buffer.from(publicKey), false)
37763
- );
37764
- } catch {
37765
- return null;
37766
- }
37767
- }
37768
- performECDH(publicKey, privateKey) {
37769
- try {
37770
- const output = Buffer.alloc(32);
37771
- secp256k1.ecdh(
37772
- Buffer.from(publicKey),
37773
- Buffer.from(privateKey),
37774
- { hashfn: this.identityHashFn },
37775
- output
37776
- );
37777
- return new Uint8Array(output);
37778
- } catch (error) {
37779
- throw new Error(
37780
- `ECDH failed: ${error instanceof Error ? error.message : "Unknown error"}`
37781
- );
37782
- }
37783
- }
37784
- sha512(data) {
37785
- return new Uint8Array(
37786
- createHash("sha512").update(Buffer.from(data)).digest()
37787
- );
37788
- }
37789
- hmacSha256(key, data) {
37790
- return new Uint8Array(
37791
- createHmac("sha256", Buffer.from(key)).update(Buffer.from(data)).digest()
37792
- );
37793
- }
37794
- async aesEncrypt(key, iv, plaintext) {
37795
- const cipher = createCipheriv(
37796
- "aes-256-cbc",
37797
- Buffer.from(key),
37798
- Buffer.from(iv)
37799
- );
37800
- const encrypted = Buffer.concat([
37801
- cipher.update(Buffer.from(plaintext)),
37802
- cipher.final()
37803
- ]);
37804
- return new Uint8Array(encrypted);
37805
- }
37806
- async aesDecrypt(key, iv, ciphertext) {
37807
- const decipher = createDecipheriv(
37808
- "aes-256-cbc",
37809
- Buffer.from(key),
37810
- Buffer.from(iv)
37811
- );
37812
- const decrypted = Buffer.concat([
37813
- decipher.update(Buffer.from(ciphertext)),
37814
- decipher.final()
37815
- ]);
37816
- return new Uint8Array(decrypted);
37817
- }
37818
- // No Buffer compatibility methods - Uint8Array only public API
37819
- };
37820
-
37821
- // src/platform/node.ts
37822
- init_interface();
37823
37167
  var getOpenPGP = lazyImport(() => import("openpgp"));
37168
+ var getEccrypto = lazyImport(() => import("eccrypto"));
37824
37169
  var NodeCryptoAdapter = class {
37825
- eciesProvider = new NodeECIESUint8Provider();
37826
- walletKeyEncryptionService = new WalletKeyEncryptionService({
37827
- eciesProvider: this.eciesProvider
37828
- });
37829
37170
  async encryptWithPublicKey(data, publicKeyHex) {
37830
37171
  try {
37172
+ const eccrypto = await getEccrypto();
37831
37173
  const publicKey = Buffer.from(publicKeyHex, "hex");
37832
37174
  const message = Buffer.from(data, "utf8");
37833
- const encrypted = await this.eciesProvider.encrypt(publicKey, message);
37175
+ const encrypted = await eccrypto.encrypt(publicKey, message);
37834
37176
  const result = Buffer.concat([
37835
37177
  encrypted.iv,
37836
37178
  encrypted.ephemPublicKey,
@@ -37839,54 +37181,27 @@ var NodeCryptoAdapter = class {
37839
37181
  ]);
37840
37182
  return result.toString("hex");
37841
37183
  } catch (error) {
37842
- if (error instanceof ECIESError) {
37843
- throw error;
37844
- }
37845
- throw new ECIESError(
37846
- `Encryption failed: ${error instanceof Error ? error.message : String(error)}`,
37847
- "ENCRYPTION_FAILED",
37848
- error instanceof Error ? error : void 0
37849
- );
37184
+ throw new Error(`Encryption failed: ${error}`);
37850
37185
  }
37851
37186
  }
37852
37187
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
37853
37188
  try {
37189
+ const eccrypto = await getEccrypto();
37854
37190
  const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
37855
37191
  const encryptedBuffer = Buffer.from(encryptedData, "hex");
37856
37192
  const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
37857
- const encryptedObj = {
37858
- iv,
37859
- ephemPublicKey,
37860
- ciphertext,
37861
- mac
37862
- };
37863
- const decrypted = await this.eciesProvider.decrypt(
37864
- privateKeyBuffer,
37865
- encryptedObj
37866
- );
37867
- return new TextDecoder().decode(decrypted);
37193
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
37194
+ const decrypted = await eccrypto.decrypt(privateKeyBuffer, encryptedObj);
37195
+ return decrypted.toString("utf8");
37868
37196
  } catch (error) {
37869
- if (error instanceof ECIESError) {
37870
- throw error;
37871
- }
37872
- throw new ECIESError(
37873
- `Decryption failed: ${error instanceof Error ? error.message : String(error)}`,
37874
- "DECRYPTION_FAILED",
37875
- error instanceof Error ? error : void 0
37876
- );
37197
+ throw new Error(`Decryption failed: ${error}`);
37877
37198
  }
37878
37199
  }
37879
37200
  async generateKeyPair() {
37880
37201
  try {
37881
- const { randomBytes: randomBytes2 } = await import("crypto");
37882
- const secp256k14 = await import("secp256k1");
37883
- let privateKey;
37884
- do {
37885
- privateKey = randomBytes2(32);
37886
- } while (!secp256k14.privateKeyVerify(privateKey));
37887
- const publicKey = Buffer.from(
37888
- secp256k14.publicKeyCreate(privateKey, true)
37889
- );
37202
+ const eccrypto = await getEccrypto();
37203
+ const privateKey = eccrypto.generatePrivate();
37204
+ const publicKey = eccrypto.getPublicCompressed(privateKey);
37890
37205
  return {
37891
37206
  privateKey: privateKey.toString("hex"),
37892
37207
  publicKey: publicKey.toString("hex")
@@ -37897,20 +37212,35 @@ var NodeCryptoAdapter = class {
37897
37212
  }
37898
37213
  async encryptWithWalletPublicKey(data, publicKey) {
37899
37214
  try {
37900
- return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
37901
- data,
37902
- publicKey
37215
+ const eccrypto = await getEccrypto();
37216
+ const uncompressedKey = processWalletPublicKey(publicKey);
37217
+ const encrypted = await eccrypto.encrypt(
37218
+ uncompressedKey,
37219
+ Buffer.from(data)
37903
37220
  );
37221
+ const result = Buffer.concat([
37222
+ encrypted.iv,
37223
+ encrypted.ephemPublicKey,
37224
+ encrypted.ciphertext,
37225
+ encrypted.mac
37226
+ ]);
37227
+ return result.toString("hex");
37904
37228
  } catch (error) {
37905
37229
  throw wrapCryptoError("encrypt with wallet public key", error);
37906
37230
  }
37907
37231
  }
37908
37232
  async decryptWithWalletPrivateKey(encryptedData, privateKey) {
37909
37233
  try {
37910
- return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
37911
- encryptedData,
37912
- privateKey
37234
+ const eccrypto = await getEccrypto();
37235
+ const privateKeyBuffer = processWalletPrivateKey(privateKey);
37236
+ const encryptedBuffer = Buffer.from(encryptedData, "hex");
37237
+ const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
37238
+ const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
37239
+ const decryptedBuffer = await eccrypto.decrypt(
37240
+ privateKeyBuffer,
37241
+ encryptedObj
37913
37242
  );
37243
+ return decryptedBuffer.toString("utf8");
37914
37244
  } catch (error) {
37915
37245
  throw wrapCryptoError("decrypt with wallet private key", error);
37916
37246
  }
@@ -38082,6 +37412,9 @@ var StorageError = class extends Error {
38082
37412
  }
38083
37413
  };
38084
37414
 
37415
+ // src/types/index.ts
37416
+ init_schemaValidation();
37417
+
38085
37418
  // src/types/external-apis.ts
38086
37419
  function isReplicateAPIResponse(value) {
38087
37420
  if (typeof value !== "object" || value === null) return false;
@@ -38123,7 +37456,7 @@ init_abi();
38123
37456
 
38124
37457
  // src/utils/grantFiles.ts
38125
37458
  init_errors();
38126
- import { keccak256, toHex as toHex2 } from "viem";
37459
+ import { keccak256, toHex } from "viem";
38127
37460
  function createGrantFile(params) {
38128
37461
  const grantFile = {
38129
37462
  grantee: params.grantee,
@@ -38246,8 +37579,8 @@ function getGrantFileHash(grantFile) {
38246
37579
  sortedFile.expires = grantFile.expires;
38247
37580
  }
38248
37581
  const jsonString = JSON.stringify(sortedFile);
38249
- console.info(`Hash: ${keccak256(toHex2(jsonString))}`);
38250
- return keccak256(toHex2(jsonString));
37582
+ console.info(`Hash: ${keccak256(toHex(jsonString))}`);
37583
+ return keccak256(toHex(jsonString));
38251
37584
  } catch (error) {
38252
37585
  throw new SerializationError(
38253
37586
  `Failed to generate grant file hash: ${error instanceof Error ? error.message : "Unknown error"}`
@@ -38524,8 +37857,7 @@ function validateOperationAccess(grantFile, requestedOperation) {
38524
37857
  }
38525
37858
 
38526
37859
  // src/utils/signatureCache.ts
38527
- import { sha256 } from "@noble/hashes/sha256";
38528
- import { bytesToHex as bytesToHex3 } from "@noble/hashes/utils";
37860
+ init_crypto_utils();
38529
37861
  var SignatureCache = class {
38530
37862
  static PREFIX = "vana_sig_";
38531
37863
  static DEFAULT_TTL_HOURS = 2;
@@ -38624,12 +37956,12 @@ var SignatureCache = class {
38624
37956
  * Generate a deterministic hash of a message object for cache key generation
38625
37957
  *
38626
37958
  * @remarks
38627
- * Creates a cryptographically secure hash from complex objects including EIP-712 typed data.
38628
- * Uses SHA-256 for collision resistance and deterministic key generation.
38629
- * Handles BigInt serialization and sorts object keys for consistency.
37959
+ * Creates a consistent hash from complex objects including EIP-712 typed data.
37960
+ * Handles BigInt serialization and produces a 32-character hash that balances
37961
+ * uniqueness with key length constraints.
38630
37962
  *
38631
37963
  * @param message - The message object to hash (typically EIP-712 typed data)
38632
- * @returns A hex string hash (SHA-256) suitable for cache keys
37964
+ * @returns A 32-character hash string suitable for cache keys
38633
37965
  * @example
38634
37966
  * ```typescript
38635
37967
  * const typedData = {
@@ -38638,35 +37970,30 @@ var SignatureCache = class {
38638
37970
  * };
38639
37971
  *
38640
37972
  * const hash = SignatureCache.hashMessage(typedData);
38641
- * // Returns SHA-256 hash like: "a1b2c3d4e5f6..."
37973
+ * // Returns something like: "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"
38642
37974
  * ```
38643
37975
  */
38644
37976
  static hashMessage(message) {
38645
- const jsonString = JSON.stringify(message, this.deterministicReplacer);
38646
- const hashBytes = sha256(new TextEncoder().encode(jsonString));
38647
- return bytesToHex3(hashBytes);
37977
+ const jsonString = JSON.stringify(message, this.bigIntReplacer);
37978
+ const base64Hash = toBase64(jsonString);
37979
+ const cleaned = base64Hash.replace(/[^a-zA-Z0-9]/g, "");
37980
+ if (cleaned.length > 32) {
37981
+ return cleaned.substring(0, 16) + cleaned.substring(cleaned.length - 16);
37982
+ }
37983
+ return cleaned.substring(0, 32);
38648
37984
  }
38649
37985
  /**
38650
- * Deterministic JSON replacer that handles BigInt values and sorts object keys
38651
- * This ensures consistent cache key generation for EIP-712 typed data
37986
+ * Custom JSON replacer that converts BigInt values to strings for serialization
37987
+ * This ensures deterministic cache key generation for EIP-712 typed data
38652
37988
  *
38653
37989
  * @param _key - The object key being serialized (unused)
38654
37990
  * @param value - The value to serialize
38655
- * @returns The serialized value with sorted keys for objects
37991
+ * @returns The serialized value
38656
37992
  */
38657
- static deterministicReplacer(_key, value) {
37993
+ static bigIntReplacer(_key, value) {
38658
37994
  if (typeof value === "bigint") {
38659
37995
  return `__BIGINT__${value.toString()}`;
38660
37996
  }
38661
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
38662
- return Object.keys(value).sort().reduce(
38663
- (sorted, key) => {
38664
- sorted[key] = value[key];
38665
- return sorted;
38666
- },
38667
- {}
38668
- );
38669
- }
38670
37997
  return value;
38671
37998
  }
38672
37999
  };
@@ -42907,6 +42234,29 @@ var DataController = class {
42907
42234
  const userFiles = Array.from(fileMap.values()).sort(
42908
42235
  (a, b) => Number((b.addedAtTimestamp || 0n) - (a.addedAtTimestamp || 0n))
42909
42236
  );
42237
+ if (userFiles.length > 0) {
42238
+ try {
42239
+ const fileIds = userFiles.map((f) => f.id);
42240
+ let proofMap;
42241
+ try {
42242
+ proofMap = await this._fetchProofsFromSubgraph(fileIds, endpoint);
42243
+ } catch (subgraphError) {
42244
+ console.debug(
42245
+ "Failed to fetch proofs from subgraph, trying chain:",
42246
+ subgraphError
42247
+ );
42248
+ proofMap = await this._fetchProofsFromChain(fileIds);
42249
+ }
42250
+ for (const file of userFiles) {
42251
+ const dlpIds = proofMap.get(file.id);
42252
+ if (dlpIds && dlpIds.length > 0) {
42253
+ file.dlpIds = dlpIds;
42254
+ }
42255
+ }
42256
+ } catch (error) {
42257
+ console.warn("Failed to fetch proof data for files:", error);
42258
+ }
42259
+ }
42910
42260
  return userFiles;
42911
42261
  } catch (error) {
42912
42262
  console.error("Failed to fetch user files from subgraph:", error);
@@ -42915,6 +42265,349 @@ var DataController = class {
42915
42265
  );
42916
42266
  }
42917
42267
  }
42268
+ /**
42269
+ * Fetches proof data for multiple files from the subgraph.
42270
+ *
42271
+ * @private
42272
+ * @param fileIds - Array of file IDs to fetch proofs for
42273
+ * @param subgraphUrl - The subgraph endpoint URL
42274
+ * @returns Map of file IDs to their associated DLP IDs
42275
+ */
42276
+ async _fetchProofsFromSubgraph(fileIds, subgraphUrl) {
42277
+ const query = `
42278
+ query GetFileProofs($fileIds: [BigInt!]!) {
42279
+ dataRegistryProofs(where: { fileId_in: $fileIds }) {
42280
+ fileId
42281
+ dlp {
42282
+ id
42283
+ }
42284
+ }
42285
+ }
42286
+ `;
42287
+ const response = await fetch(subgraphUrl, {
42288
+ method: "POST",
42289
+ headers: {
42290
+ "Content-Type": "application/json"
42291
+ },
42292
+ body: JSON.stringify({
42293
+ query,
42294
+ variables: {
42295
+ fileIds: fileIds.map((id) => id.toString())
42296
+ }
42297
+ })
42298
+ });
42299
+ if (!response.ok) {
42300
+ throw new Error(
42301
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42302
+ );
42303
+ }
42304
+ const result = await response.json();
42305
+ if (result.errors) {
42306
+ throw new Error(
42307
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42308
+ );
42309
+ }
42310
+ const proofMap = /* @__PURE__ */ new Map();
42311
+ if (result.data?.dataRegistryProofs) {
42312
+ for (const proof of result.data.dataRegistryProofs) {
42313
+ if (proof.dlp?.id) {
42314
+ const fileId = parseInt(proof.fileId);
42315
+ const dlpId = parseInt(proof.dlp.id);
42316
+ if (!proofMap.has(fileId)) {
42317
+ proofMap.set(fileId, []);
42318
+ }
42319
+ const dlpIds = proofMap.get(fileId);
42320
+ if (!dlpIds.includes(dlpId)) {
42321
+ dlpIds.push(dlpId);
42322
+ }
42323
+ }
42324
+ }
42325
+ }
42326
+ return proofMap;
42327
+ }
42328
+ /**
42329
+ * Fetches proof data for multiple files from the blockchain.
42330
+ * Falls back to this when subgraph is unavailable.
42331
+ *
42332
+ * @private
42333
+ * @param fileIds - Array of file IDs to fetch proofs for
42334
+ * @returns Map of file IDs to their associated DLP IDs
42335
+ */
42336
+ async _fetchProofsFromChain(fileIds) {
42337
+ const chainId = this.context.walletClient.chain?.id;
42338
+ if (!chainId) {
42339
+ throw new Error("Chain ID not available");
42340
+ }
42341
+ const dataRegistryAddress = getContractAddress(chainId, "DataRegistry");
42342
+ const dataRegistryAbi = getAbi("DataRegistry");
42343
+ const proofMap = /* @__PURE__ */ new Map();
42344
+ for (const fileId of fileIds) {
42345
+ const dlpIds = [];
42346
+ let proofIndex = 0;
42347
+ let hasMoreProofs = true;
42348
+ while (hasMoreProofs) {
42349
+ try {
42350
+ const proof = await this.context.publicClient.readContract({
42351
+ address: dataRegistryAddress,
42352
+ abi: dataRegistryAbi,
42353
+ functionName: "fileProofs",
42354
+ args: [BigInt(fileId), BigInt(proofIndex)]
42355
+ });
42356
+ if (proof?.data?.dlpId) {
42357
+ const dlpId = Number(proof.data.dlpId);
42358
+ if (!dlpIds.includes(dlpId)) {
42359
+ dlpIds.push(dlpId);
42360
+ }
42361
+ }
42362
+ proofIndex++;
42363
+ } catch {
42364
+ hasMoreProofs = false;
42365
+ }
42366
+ }
42367
+ if (dlpIds.length > 0) {
42368
+ proofMap.set(fileId, dlpIds);
42369
+ }
42370
+ }
42371
+ return proofMap;
42372
+ }
42373
+ /**
42374
+ * Retrieves information about a specific Data Liquidity Pool (DLP).
42375
+ *
42376
+ * @remarks
42377
+ * DLPs are entities that process and verify data files in the Vana network.
42378
+ * This method fetches DLP metadata including name, status, and performance rating.
42379
+ * Uses subgraph first for efficiency, falls back to chain if unavailable.
42380
+ *
42381
+ * @param dlpId - The unique identifier of the DLP
42382
+ * @param options - Optional parameters
42383
+ * @param options.subgraphUrl - Custom subgraph URL to override default
42384
+ * @returns Promise resolving to DLP information
42385
+ * @throws {Error} When DLP cannot be found - "DLP not found: {dlpId}"
42386
+ * @throws {Error} When query fails - "Failed to fetch DLP: {error}"
42387
+ * @example
42388
+ * ```typescript
42389
+ * const dlp = await vana.data.getDLP(26);
42390
+ * console.log(`DLP ${dlp.name}: ${dlp.status}`);
42391
+ * ```
42392
+ */
42393
+ async getDLP(dlpId, options = {}) {
42394
+ const subgraphUrl = options.subgraphUrl || this.context.subgraphUrl;
42395
+ if (subgraphUrl) {
42396
+ try {
42397
+ const query = `
42398
+ query GetDLP($id: ID!) {
42399
+ dlp(id: $id) {
42400
+ id
42401
+ name
42402
+ metadata
42403
+ status
42404
+ address
42405
+ owner
42406
+ }
42407
+ }
42408
+ `;
42409
+ const response = await fetch(subgraphUrl, {
42410
+ method: "POST",
42411
+ headers: {
42412
+ "Content-Type": "application/json"
42413
+ },
42414
+ body: JSON.stringify({
42415
+ query,
42416
+ variables: {
42417
+ id: dlpId.toString()
42418
+ }
42419
+ })
42420
+ });
42421
+ if (!response.ok) {
42422
+ throw new Error(
42423
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42424
+ );
42425
+ }
42426
+ const result = await response.json();
42427
+ if (result.errors) {
42428
+ throw new Error(
42429
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42430
+ );
42431
+ }
42432
+ if (!result.data?.dlp) {
42433
+ throw new Error(`DLP not found: ${dlpId}`);
42434
+ }
42435
+ return {
42436
+ id: parseInt(result.data.dlp.id),
42437
+ name: result.data.dlp.name || "",
42438
+ metadata: result.data.dlp.metadata,
42439
+ status: result.data.dlp.status ? parseInt(result.data.dlp.status) : void 0,
42440
+ address: result.data.dlp.address,
42441
+ owner: result.data.dlp.owner
42442
+ };
42443
+ } catch (error) {
42444
+ console.debug("Subgraph query failed, falling back to chain:", error);
42445
+ }
42446
+ }
42447
+ try {
42448
+ const chainId = this.context.walletClient.chain?.id;
42449
+ if (!chainId) {
42450
+ throw new Error("Chain ID not available");
42451
+ }
42452
+ const dlpRegistryAddress = getContractAddress(chainId, "DLPRegistry");
42453
+ const dlpRegistryAbi = getAbi("DLPRegistry");
42454
+ const dlpData = await this.context.publicClient.readContract({
42455
+ address: dlpRegistryAddress,
42456
+ abi: dlpRegistryAbi,
42457
+ functionName: "dlps",
42458
+ args: [BigInt(dlpId)]
42459
+ });
42460
+ if (!dlpData || !dlpData.name) {
42461
+ throw new Error(`DLP not found: ${dlpId}`);
42462
+ }
42463
+ return {
42464
+ id: dlpId,
42465
+ name: dlpData.name,
42466
+ metadata: dlpData.metadata,
42467
+ status: dlpData.status,
42468
+ address: dlpData.dlpAddress,
42469
+ owner: dlpData.ownerAddress
42470
+ };
42471
+ } catch (error) {
42472
+ throw new Error(
42473
+ `Failed to fetch DLP: ${error instanceof Error ? error.message : "Unknown error"}`
42474
+ );
42475
+ }
42476
+ }
42477
+ /**
42478
+ * Lists all Data Liquidity Pools (DLPs) with optional pagination.
42479
+ *
42480
+ * @remarks
42481
+ * Fetches a paginated list of all DLPs registered in the network.
42482
+ * Uses subgraph for efficient querying with fallback to chain multicall.
42483
+ *
42484
+ * @param options - Optional parameters for pagination and filtering
42485
+ * @param options.limit - Maximum number of DLPs to return (default: 100)
42486
+ * @param options.offset - Number of DLPs to skip (default: 0)
42487
+ * @param options.subgraphUrl - Custom subgraph URL to override default
42488
+ * @returns Promise resolving to array of DLP information
42489
+ * @throws {Error} When query fails - "Failed to list DLPs: {error}"
42490
+ * @example
42491
+ * ```typescript
42492
+ * // Get first 10 DLPs
42493
+ * const dlps = await vana.data.listDLPs({ limit: 10 });
42494
+ * dlps.forEach(dlp => console.log(`${dlp.id}: ${dlp.name}`));
42495
+ *
42496
+ * // Get next page
42497
+ * const nextPage = await vana.data.listDLPs({ limit: 10, offset: 10 });
42498
+ * ```
42499
+ */
42500
+ async listDLPs(options = {}) {
42501
+ const { limit = 100, offset = 0 } = options;
42502
+ const subgraphUrl = options.subgraphUrl || this.context.subgraphUrl;
42503
+ if (subgraphUrl) {
42504
+ try {
42505
+ const query = `
42506
+ query ListDLPs($first: Int!, $skip: Int!) {
42507
+ dlps(first: $first, skip: $skip, orderBy: id) {
42508
+ id
42509
+ name
42510
+ metadata
42511
+ status
42512
+ address
42513
+ owner
42514
+ }
42515
+ }
42516
+ `;
42517
+ const response = await fetch(subgraphUrl, {
42518
+ method: "POST",
42519
+ headers: {
42520
+ "Content-Type": "application/json"
42521
+ },
42522
+ body: JSON.stringify({
42523
+ query,
42524
+ variables: {
42525
+ first: limit,
42526
+ skip: offset
42527
+ }
42528
+ })
42529
+ });
42530
+ if (!response.ok) {
42531
+ throw new Error(
42532
+ `Subgraph request failed: ${response.status} ${response.statusText}`
42533
+ );
42534
+ }
42535
+ const result = await response.json();
42536
+ if (result.errors) {
42537
+ throw new Error(
42538
+ `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
42539
+ );
42540
+ }
42541
+ const dlps = result.data?.dlps || [];
42542
+ return dlps.map((dlp) => ({
42543
+ id: parseInt(dlp.id),
42544
+ name: dlp.name || "",
42545
+ metadata: dlp.metadata,
42546
+ status: dlp.status ? parseInt(dlp.status) : void 0,
42547
+ address: dlp.address,
42548
+ owner: dlp.owner
42549
+ }));
42550
+ } catch (error) {
42551
+ console.debug("Subgraph query failed, falling back to chain:", error);
42552
+ }
42553
+ }
42554
+ try {
42555
+ const chainId = this.context.walletClient.chain?.id;
42556
+ if (!chainId) {
42557
+ throw new Error("Chain ID not available");
42558
+ }
42559
+ const dlpRegistryAddress = getContractAddress(chainId, "DLPRegistry");
42560
+ const dlpRegistryAbi = getAbi("DLPRegistry");
42561
+ const dlpCount = await this.context.publicClient.readContract({
42562
+ address: dlpRegistryAddress,
42563
+ abi: dlpRegistryAbi,
42564
+ functionName: "dlpsCount",
42565
+ args: []
42566
+ });
42567
+ const totalCount = Number(dlpCount);
42568
+ const start = offset;
42569
+ const end = Math.min(start + limit, totalCount);
42570
+ if (end <= start) {
42571
+ return [];
42572
+ }
42573
+ const calls = [];
42574
+ for (let i = start + 1; i <= end; i++) {
42575
+ calls.push({
42576
+ address: dlpRegistryAddress,
42577
+ abi: dlpRegistryAbi,
42578
+ functionName: "dlps",
42579
+ args: [BigInt(i)]
42580
+ });
42581
+ }
42582
+ const results = await gasAwareMulticall(this.context.publicClient, {
42583
+ contracts: calls,
42584
+ allowFailure: true,
42585
+ batchSize: 50
42586
+ });
42587
+ const dlps = [];
42588
+ for (let i = 0; i < results.length; i++) {
42589
+ const result = results[i];
42590
+ if (result.status === "success" && result.result) {
42591
+ const dlpData = result.result;
42592
+ if (dlpData.name) {
42593
+ dlps.push({
42594
+ id: start + i + 1,
42595
+ name: dlpData.name,
42596
+ metadata: dlpData.metadata,
42597
+ status: dlpData.status,
42598
+ address: dlpData.dlpAddress,
42599
+ owner: dlpData.ownerAddress
42600
+ });
42601
+ }
42602
+ }
42603
+ }
42604
+ return dlps;
42605
+ } catch (error) {
42606
+ throw new Error(
42607
+ `Failed to list DLPs: ${error instanceof Error ? error.message : "Unknown error"}`
42608
+ );
42609
+ }
42610
+ }
42918
42611
  /**
42919
42612
  * Retrieves a list of permissions granted by a user.
42920
42613
  *
@@ -44045,19 +43738,31 @@ var DataController = class {
44045
43738
  return await this.submitFilePermission(fileId, account, publicKey);
44046
43739
  }
44047
43740
  /**
44048
- * Submits a file permission transaction and returns the transaction hash immediately.
43741
+ * Submits a file permission transaction to the blockchain.
44049
43742
  *
44050
- * This is the lower-level method that provides maximum control over transaction timing.
43743
+ * @remarks
43744
+ * This method supports gasless transactions via relayer callbacks when configured.
43745
+ * It encrypts the user's encryption key with the recipient's public key before submission.
44051
43746
  * Use this when you want to handle transaction confirmation and event parsing separately.
44052
43747
  *
44053
- * @param fileId - The ID of the file to add permissions for
44054
- * @param account - The address of the account to grant permission to
44055
- * @param publicKey - The public key to encrypt the user's encryption key with
44056
- * @returns Promise resolving to the transaction hash
43748
+ * @param fileId - The ID of the file to grant permission for
43749
+ * @param account - The recipient's wallet address that will access the file
43750
+ * @param publicKey - The recipient's public key for encryption.
43751
+ * Obtain via `vana.server.getIdentity(account).public_key`
43752
+ * @returns Promise resolving to TransactionHandle for tracking the transaction
43753
+ * @throws {Error} When chain ID is not available
43754
+ * @throws {Error} When encryption key generation fails
43755
+ * @throws {Error} When public key encryption fails
43756
+ *
44057
43757
  * @example
44058
43758
  * ```typescript
44059
- * const txHash = await vana.data.submitFilePermission(fileId, account, publicKey);
44060
- * console.log(`Transaction submitted: ${txHash}`);
43759
+ * const tx = await vana.data.submitFilePermission(
43760
+ * fileId,
43761
+ * "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36",
43762
+ * recipientPublicKey
43763
+ * );
43764
+ * const result = await tx.waitForEvents();
43765
+ * console.log(`Permission granted with ID: ${result.permissionId}`);
44061
43766
  * ```
44062
43767
  */
44063
43768
  async submitFilePermission(fileId, account, publicKey) {
@@ -44341,10 +44046,10 @@ var DataController = class {
44341
44046
  );
44342
44047
  }
44343
44048
  /**
44344
- * Validates a data schema against the Vana meta-schema.
44049
+ * Validates a data schema definition against the Vana meta-schema.
44345
44050
  *
44346
- * @param schema - The data schema to validate
44347
- * @returns Assertion that schema is valid (throws if invalid)
44051
+ * @param schema - The data schema definition to validate
44052
+ * @returns The validated DataSchema
44348
44053
  * @throws SchemaValidationError if invalid
44349
44054
  * @example
44350
44055
  * ```typescript
@@ -44361,11 +44066,11 @@ var DataController = class {
44361
44066
  * }
44362
44067
  * };
44363
44068
  *
44364
- * vana.data.validateDataSchema(schema);
44069
+ * const validatedSchema = vana.data.validateDataSchemaAgainstMetaSchema(schema);
44365
44070
  * ```
44366
44071
  */
44367
- validateDataSchema(schema) {
44368
- return validateDataSchema(schema);
44072
+ validateDataSchemaAgainstMetaSchema(schema) {
44073
+ return validateDataSchemaAgainstMetaSchema(schema);
44369
44074
  }
44370
44075
  /**
44371
44076
  * Validates data against a JSON Schema from a data schema.
@@ -44398,9 +44103,9 @@ var DataController = class {
44398
44103
  return validateDataAgainstSchema(data, schema);
44399
44104
  }
44400
44105
  /**
44401
- * Fetches and validates a schema from a URL, then returns the parsed data schema.
44106
+ * Fetches and validates a data schema from a URL, then returns the parsed data schema.
44402
44107
  *
44403
- * @param url - The URL to fetch the schema from
44108
+ * @param url - The URL to fetch the data schema from
44404
44109
  * @returns The validated data schema
44405
44110
  * @throws SchemaValidationError if invalid or fetch fails
44406
44111
  * @example
@@ -45598,7 +45303,7 @@ var GoogleDriveStorage = class {
45598
45303
  };
45599
45304
 
45600
45305
  // src/storage/providers/ipfs.ts
45601
- init_encoding();
45306
+ init_crypto_utils();
45602
45307
  var IpfsStorage = class _IpfsStorage {
45603
45308
  constructor(config) {
45604
45309
  this.config = config;
@@ -45638,9 +45343,8 @@ var IpfsStorage = class _IpfsStorage {
45638
45343
  * ```
45639
45344
  */
45640
45345
  static forInfura(credentials) {
45641
- const encoder = new TextEncoder();
45642
45346
  const auth = toBase64(
45643
- encoder.encode(`${credentials.projectId}:${credentials.projectSecret}`)
45347
+ `${credentials.projectId}:${credentials.projectSecret}`
45644
45348
  );
45645
45349
  return new _IpfsStorage({
45646
45350
  apiEndpoint: "https://ipfs.infura.io:5001/api/v0/add",
@@ -46500,7 +46204,7 @@ var vanaMainnet2 = {
46500
46204
  url: "https://vanascan.io"
46501
46205
  }
46502
46206
  },
46503
- subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/vana/7.0.7/gn"
46207
+ subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/vana/prod/gn"
46504
46208
  };
46505
46209
  var moksha = {
46506
46210
  id: 14800,
@@ -46521,7 +46225,7 @@ var moksha = {
46521
46225
  url: "https://moksha.vanascan.io"
46522
46226
  }
46523
46227
  },
46524
- subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/moksha/7.0.7/gn"
46228
+ subgraphUrl: "https://api.goldsky.com/api/public/project_cm168cz887zva010j39il7a6p/subgraphs/moksha/prod/gn"
46525
46229
  };
46526
46230
  function getChainConfig(chainId) {
46527
46231
  switch (chainId) {
@@ -47550,7 +47254,7 @@ async function handleRelayerRequest(sdk, payload) {
47550
47254
 
47551
47255
  // src/index.node.ts
47552
47256
  init_transactionHandle();
47553
- init_browser2();
47257
+ init_browser();
47554
47258
 
47555
47259
  // src/platform/utils.ts
47556
47260
  function detectPlatform() {
@@ -47575,7 +47279,7 @@ async function createPlatformAdapter() {
47575
47279
  const { NodePlatformAdapter: NodePlatformAdapter2 } = await import(moduleName);
47576
47280
  return new NodePlatformAdapter2();
47577
47281
  } else {
47578
- const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser2(), browser_exports));
47282
+ const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser(), browser_exports));
47579
47283
  return new BrowserPlatformAdapter2();
47580
47284
  }
47581
47285
  } catch (error) {
@@ -47596,7 +47300,7 @@ async function createPlatformAdapterFor(platformType) {
47596
47300
  const { NodePlatformAdapter: NodePlatformAdapter2 } = await import(moduleName);
47597
47301
  return new NodePlatformAdapter2();
47598
47302
  } else {
47599
- const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser2(), browser_exports));
47303
+ const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser(), browser_exports));
47600
47304
  return new BrowserPlatformAdapter2();
47601
47305
  }
47602
47306
  } catch (error) {
@@ -47623,7 +47327,7 @@ function getPlatformCapabilities() {
47623
47327
  }
47624
47328
 
47625
47329
  // src/platform/browser-safe.ts
47626
- init_browser2();
47330
+ init_browser();
47627
47331
  async function createNodePlatformAdapter() {
47628
47332
  if (typeof window !== "undefined") {
47629
47333
  throw new Error(
@@ -48069,7 +47773,7 @@ export {
48069
47773
  storeGrantFile,
48070
47774
  summarizeGrant,
48071
47775
  validateDataAgainstSchema,
48072
- validateDataSchema,
47776
+ validateDataSchemaAgainstMetaSchema,
48073
47777
  validateGrant,
48074
47778
  validateGrantExpiry,
48075
47779
  validateGrantFile,