@invisi-labs/primitives 1.3.4 → 1.3.5

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.
package/dist/index.js CHANGED
@@ -1,1366 +1,5 @@
1
- import {
2
- computeNoteNullifier
3
- } from "./chunk-PNJ3LCJE.js";
4
- import {
5
- CREDIT_POLICY_FIELDS,
6
- CREDIT_USAGE_FIELDS,
7
- D_CNULL,
8
- D_CREDIT,
9
- D_CREDIT_KEY_HASH,
10
- D_CREDIT_RECOVERY,
11
- D_CREDIT_STATE_NONCE,
12
- D_IDENT,
13
- D_NOTE,
14
- D_NULL,
15
- DeliveryAuthenticationError,
16
- FIELD_MODULUS,
17
- MAX_CIPHERTEXT_BYTES,
18
- TREE_DEPTH,
19
- applyCreditDrawUsage,
20
- computeCreditCommitment,
21
- computeCreditNullifier,
22
- computeCreditRecoveryPad,
23
- computeCreditSharedKeyHash,
24
- computeNoteCommitment,
25
- computeNoteIdentity,
26
- creditCommitment,
27
- creditPeriods,
28
- decodeDeliveryHeader,
29
- decryptCreditPayload,
30
- decryptCreditState,
31
- decryptNotePayload,
32
- decryptPrivateTransferNote,
33
- deliveryCodec,
34
- deliveryHeader,
35
- deriveCreditState,
36
- deriveCreditStateNonce,
37
- deriveCreditUpdate,
38
- encryptCreditState,
39
- encryptPrivateTransferNote,
40
- exportPayloadKey,
41
- generateCreditGrantId,
42
- generateCreditSharedKey,
43
- generateNonce,
44
- normalizeCreditDeliveryState,
45
- normalizeCreditGrantId,
46
- normalizeCreditPolicy,
47
- normalizeCreditState,
48
- normalizeCreditUsage,
49
- noteCommitment,
50
- poseidonHash,
51
- recoverCreditState,
52
- validateContext,
53
- validateDeliveryCiphertext,
54
- viewingPublicKey
55
- } from "./chunk-JQJPQGFX.js";
56
- import {
57
- MissingCapabilityError,
58
- ReceivingAddress,
59
- decodeAddress,
60
- encodeLongAddress
61
- } from "./chunk-5KF55DN7.js";
62
- import {
63
- createClue,
64
- createClueFromSeed,
65
- deriveClueKey,
66
- validateClueKey
67
- } from "./chunk-VXBZSY4Y.js";
68
-
69
- // src/disclosure/disclosure.ts
70
- import { bytesToHex } from "@noble/hashes/utils";
71
- var NOTE_FIELDS = ["ownerAddress", "amount", "nonce"];
72
- var CREDIT_FIELDS = [
73
- "spenderWalletIdentity",
74
- "ownerWalletIdentity",
75
- "grantId",
76
- "nonce",
77
- "expiry",
78
- "creditSharedKeyHash",
79
- "singleLimit",
80
- "dailyLimit",
81
- "monthlyLimit",
82
- "availableCredit",
83
- "unlimited",
84
- "lastDay",
85
- "dailySpent",
86
- "lastMonth",
87
- "monthlySpent",
88
- "totalSpent"
89
- ];
90
- function record(value, fields) {
91
- if (!value || typeof value !== "object" || Array.isArray(value))
92
- throw new Error("invalid disclosure object");
93
- const keys = Object.keys(value);
94
- if (keys.length !== fields.length || keys.some((key) => !fields.includes(key)))
95
- throw new Error("unexpected disclosure fields");
96
- return value;
97
- }
98
- function number(value, bits, label) {
99
- if (typeof value !== "bigint" || value < 0n || value >= 1n << BigInt(bits))
100
- throw new Error(`invalid disclosure ${label}`);
101
- return value;
102
- }
103
- function decimal(value, bits, label) {
104
- if (typeof value !== "string" || !/^(0|[1-9][0-9]*)$/.test(value) || value.length > 78)
105
- throw new Error(`invalid disclosure ${label}`);
106
- return number(BigInt(value), bits, label);
107
- }
108
- function hash(value, label, field = true) {
109
- if (typeof value !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(value))
110
- throw new Error(`invalid disclosure ${label}`);
111
- if (field && BigInt(value) >= FIELD_MODULUS) throw new Error(`invalid disclosure ${label}`);
112
- return value.toLowerCase();
113
- }
114
- function owner(value, label) {
115
- if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value) || BigInt(value) === 0n)
116
- throw new Error(`invalid disclosure ${label}`);
117
- return value.toLowerCase();
118
- }
119
- function nonce(value) {
120
- if (value < 0n || value >= FIELD_MODULUS) throw new Error("invalid disclosure nonce");
121
- return value;
122
- }
123
- function context(value) {
124
- const result = {
125
- chainId: number(value.chainId, 64, "chainId"),
126
- protocolAddress: number(value.protocolAddress, 160, "protocolAddress"),
127
- tokenAddress: number(value.tokenAddress, 160, "tokenAddress")
128
- };
129
- if (result.protocolAddress === 0n || result.tokenAddress === 0n)
130
- throw new Error("disclosure addresses must be nonzero");
131
- return result;
132
- }
133
- function encode(values) {
134
- return Object.fromEntries(
135
- Object.entries(values).map(([key, value]) => [key, value.toString()])
136
- );
137
- }
138
- async function creditOpening(note) {
139
- const copied = { ...note };
140
- return {
141
- ...context(copied),
142
- ...normalizeCreditPolicy(copied),
143
- ...normalizeCreditUsage(copied),
144
- availableCredit: number(copied.availableCredit, 128, "availableCredit"),
145
- unlimited: copied.unlimited,
146
- spenderWalletIdentity: owner(copied.spenderWalletIdentity, "spender identity"),
147
- ownerWalletIdentity: owner(copied.ownerWalletIdentity, "owner identity"),
148
- grantId: normalizeCreditGrantId(copied.grantId),
149
- nonce: nonce(copied.nonce),
150
- expiry: number(copied.expiry, 64, "expiry"),
151
- creditSharedKeyHash: await computeCreditSharedKeyHash(copied.creditSharedKey)
152
- };
153
- }
154
- async function commitment(note) {
155
- if ("creditSharedKeyHash" in note) {
156
- return computeCreditCommitment({ ...note, creditSharedKey: 0n }, note.creditSharedKeyHash);
157
- }
158
- return computeNoteCommitment(
159
- note.chainId,
160
- BigInt(note.protocolAddress),
161
- await computeNoteIdentity(BigInt(note.ownerAddress), note.nonce),
162
- note.tokenAddress,
163
- note.amount
164
- );
165
- }
166
- var Disclosure = class _Disclosure {
167
- #material;
168
- constructor(material) {
169
- this.#material = {
170
- ...material,
171
- context: Object.freeze({ ...material.context }),
172
- data: Object.freeze({ ...material.data })
173
- };
174
- Object.freeze(this.#material);
175
- Object.freeze(this);
176
- }
177
- static async fromNote(value) {
178
- const copied = { ...value };
179
- const note = {
180
- ...context(copied),
181
- ownerAddress: owner(copied.ownerAddress, "owner address"),
182
- amount: number(copied.amount, 128, "amount"),
183
- nonce: nonce(copied.nonce)
184
- };
185
- return new _Disclosure({
186
- version: 1,
187
- kind: "note",
188
- method: "opening",
189
- context: {
190
- ...encode(context(note)),
191
- outputCommitment: await commitment(note)
192
- },
193
- data: encode({
194
- ownerAddress: note.ownerAddress,
195
- amount: note.amount,
196
- nonce: note.nonce
197
- })
198
- });
199
- }
200
- static async fromCredit(value) {
201
- const note = await creditOpening(value);
202
- const data = Object.fromEntries(
203
- CREDIT_FIELDS.map((key) => [
204
- key,
205
- key === "unlimited" ? note.unlimited ? "1" : "0" : note[key].toString()
206
- ])
207
- );
208
- return new _Disclosure({
209
- version: 1,
210
- kind: "credit",
211
- method: "opening",
212
- context: {
213
- ...encode(context(note)),
214
- outputCommitment: await commitment(note)
215
- },
216
- data
217
- });
218
- }
219
- /** Low-level factory; normally use wallet.getViewer().discloseNote(). */
220
- static async fromEncryptedNote(key, envelope, value) {
221
- const scoped = { ...value };
222
- const copied = typeof envelope === "string" ? envelope : Uint8Array.from(envelope);
223
- const localKey = typeof key === "string" ? key : Uint8Array.from(key);
224
- try {
225
- await decryptPrivateTransferNote(localKey, copied, scoped);
226
- return await _Disclosure.fromEnvelope(localKey, copied, scoped, "funds");
227
- } finally {
228
- if (localKey instanceof Uint8Array) localKey.fill(0);
229
- }
230
- }
231
- /** Exposes the full selected Credit envelope, including its shared key and receiving snapshots. */
232
- static async fromEncryptedCredit(key, envelope, value) {
233
- const scoped = { ...value };
234
- const copied = typeof envelope === "string" ? envelope : Uint8Array.from(envelope);
235
- const localKey = typeof key === "string" ? key : Uint8Array.from(key);
236
- try {
237
- await decryptCreditState(localKey, copied, scoped);
238
- return await _Disclosure.fromEnvelope(localKey, copied, scoped, scoped.role);
239
- } finally {
240
- if (localKey instanceof Uint8Array) localKey.fill(0);
241
- }
242
- }
243
- static async fromEnvelope(key, envelope, scoped, role) {
244
- const payloadKey = await exportPayloadKey(key, envelope, role !== "funds");
245
- try {
246
- return new _Disclosure({
247
- version: 1,
248
- kind: role === "funds" ? "note" : "credit",
249
- method: "payload-key",
250
- context: {
251
- ...encode(context(scoped)),
252
- outputCommitment: hash(scoped.outputCommitment, "commitment")
253
- },
254
- data: {
255
- payloadKey: `0x${bytesToHex(payloadKey)}`,
256
- ownerAddress: owner(scoped.ownerAddress, "owner address"),
257
- role
258
- }
259
- });
260
- } finally {
261
- payloadKey.fill(0);
262
- }
263
- }
264
- /** Parse untrusted JSON material; verification against an independent output is still required. */
265
- static async fromExport(value) {
266
- const root = record(value, ["version", "kind", "method", "context", "data"]);
267
- if (root.version !== 1 || root.kind !== "note" && root.kind !== "credit" || root.method !== "opening" && root.method !== "payload-key")
268
- throw new Error("unsupported disclosure format");
269
- const rawContext = record(root.context, [
270
- "chainId",
271
- "protocolAddress",
272
- "tokenAddress",
273
- "outputCommitment"
274
- ]);
275
- const scoped = context({
276
- chainId: decimal(rawContext.chainId, 64, "chainId"),
277
- protocolAddress: decimal(rawContext.protocolAddress, 160, "protocolAddress"),
278
- tokenAddress: decimal(rawContext.tokenAddress, 160, "tokenAddress")
279
- });
280
- const outputCommitment = hash(rawContext.outputCommitment, "commitment");
281
- const fields = root.method === "payload-key" ? ["payloadKey", "ownerAddress", "role"] : root.kind === "note" ? NOTE_FIELDS : CREDIT_FIELDS;
282
- const raw = record(root.data, fields);
283
- const data = {};
284
- for (const key of fields) {
285
- if (key === "role") {
286
- if (root.kind === "note" ? raw[key] !== "funds" : raw[key] !== "owner" && raw[key] !== "spender")
287
- throw new Error("invalid disclosure role");
288
- data[key] = raw[key];
289
- } else if (key === "payloadKey" || key.endsWith("Identity") || key === "ownerAddress" || key === "creditSharedKeyHash") {
290
- data[key] = key.endsWith("Identity") || key === "ownerAddress" ? owner(raw[key], key) : hash(raw[key], key, key !== "payloadKey");
291
- } else if (key === "unlimited") {
292
- if (raw[key] !== "0" && raw[key] !== "1")
293
- throw Error("invalid disclosure unlimited");
294
- data[key] = raw[key];
295
- } else {
296
- const bits = key === "availableCredit" || key === "grantId" ? 128 : key.endsWith("Payout") ? 160 : key === "expiry" ? 64 : key === "amount" ? root.kind === "note" ? 128 : 126 : 254;
297
- const parsed = decimal(raw[key], bits, key);
298
- if (key === "nonce") nonce(parsed);
299
- data[key] = parsed.toString();
300
- }
301
- }
302
- const material = {
303
- version: 1,
304
- kind: root.kind,
305
- method: root.method,
306
- context: { ...encode(scoped), outputCommitment },
307
- data
308
- };
309
- const result = new _Disclosure(material);
310
- if (material.method === "opening")
311
- await result.verify({
312
- ...scoped,
313
- outputCommitment,
314
- role: material.kind === "note" ? "funds" : "owner"
315
- });
316
- return result;
317
- }
318
- getScope() {
319
- const { version, kind, method } = this.#material;
320
- return {
321
- version,
322
- kind,
323
- method,
324
- permitsOwnerSweep: kind === "note",
325
- revealsNoteConsumption: kind === "note",
326
- revealsCreditSharedKey: kind === "credit" && method === "payload-key",
327
- revealsReceivingKeys: kind === "credit" && method === "payload-key",
328
- revealsMemo: method === "payload-key",
329
- revealsPayload: method === "payload-key"
330
- };
331
- }
332
- /** Explicitly export sensitive, JSON-compatible material for a chosen recipient. */
333
- export() {
334
- return {
335
- ...this.#material,
336
- context: { ...this.#material.context },
337
- data: { ...this.#material.data }
338
- };
339
- }
340
- async verify(value) {
341
- const output = {
342
- ...value,
343
- ciphertext: value.ciphertext instanceof Uint8Array ? Uint8Array.from(value.ciphertext) : value.ciphertext
344
- };
345
- const scoped = context(output);
346
- const material = this.#material;
347
- for (const field of ["chainId", "protocolAddress", "tokenAddress"]) {
348
- if (scoped[field].toString() !== material.context[field])
349
- throw new Error("disclosure deployment context mismatch");
350
- }
351
- if (hash(output.outputCommitment, "commitment") !== material.context.outputCommitment)
352
- throw new Error("disclosure output commitment mismatch");
353
- if (material.kind === "note" ? output.role !== "funds" : output.role !== "owner" && output.role !== "spender")
354
- throw new Error("disclosure output role mismatch");
355
- const data = material.data;
356
- if (material.method === "payload-key") {
357
- if (output.role !== data.role || output.ciphertext === void 0)
358
- throw new Error("disclosure requires the selected role envelope");
359
- const decryption = {
360
- ...scoped,
361
- outputCommitment: output.outputCommitment,
362
- ownerAddress: data.ownerAddress
363
- };
364
- if (material.kind === "note")
365
- return {
366
- kind: "note",
367
- note: Object.freeze(
368
- await decryptNotePayload(
369
- data.payloadKey,
370
- output.ciphertext,
371
- decryption
372
- )
373
- )
374
- };
375
- const state = await decryptCreditPayload(
376
- data.payloadKey,
377
- output.ciphertext,
378
- { ...decryption, role: output.role }
379
- );
380
- return {
381
- kind: "credit",
382
- note: Object.freeze({
383
- ...await creditOpening(state.note),
384
- ...state.note.payload === void 0 ? {} : { payload: structuredClone(state.note.payload) }
385
- })
386
- };
387
- }
388
- if (material.kind === "note") {
389
- const note2 = {
390
- ...scoped,
391
- ownerAddress: data.ownerAddress,
392
- amount: BigInt(data.amount),
393
- nonce: BigInt(data.nonce)
394
- };
395
- if (await commitment(note2) !== material.context.outputCommitment)
396
- throw new Error("disclosure opening commitment mismatch");
397
- return { kind: "note", note: Object.freeze(note2) };
398
- }
399
- const note = {
400
- ...scoped,
401
- spenderWalletIdentity: data.spenderWalletIdentity,
402
- ownerWalletIdentity: data.ownerWalletIdentity,
403
- grantId: normalizeCreditGrantId(data.grantId),
404
- nonce: BigInt(data.nonce),
405
- expiry: BigInt(data.expiry),
406
- ...normalizeCreditPolicy(
407
- Object.fromEntries(
408
- ["singleLimit", "dailyLimit", "monthlyLimit"].map((k) => [k, BigInt(data[k])])
409
- )
410
- ),
411
- ...normalizeCreditUsage(
412
- Object.fromEntries(
413
- ["lastDay", "dailySpent", "lastMonth", "monthlySpent", "totalSpent"].map(
414
- (k) => [k, BigInt(data[k])]
415
- )
416
- )
417
- ),
418
- availableCredit: BigInt(data.availableCredit),
419
- unlimited: data.unlimited === "1",
420
- creditSharedKeyHash: data.creditSharedKeyHash
421
- };
422
- if (await commitment(note) !== material.context.outputCommitment)
423
- throw new Error("disclosure opening commitment mismatch");
424
- return { kind: "credit", note: Object.freeze(note) };
425
- }
426
- toJSON() {
427
- return { capability: "disclosure", ...this.getScope() };
428
- }
429
- [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
430
- return this.toJSON();
431
- }
432
- };
433
-
434
- // src/wallet/capabilities.ts
435
- import { secp256k1 as secp256k12 } from "@noble/curves/secp256k1";
436
- import { bytesToHex as bytesToHex3, hexToBytes as hexToBytes2 } from "@noble/hashes/utils";
437
-
438
- // src/wallet/wallet.ts
439
- import { secp256k1 } from "@noble/curves/secp256k1";
440
- import { hkdf } from "@noble/hashes/hkdf";
441
- import { sha256 } from "@noble/hashes/sha256";
442
- import { keccak_256 } from "@noble/hashes/sha3";
443
- import { bytesToHex as bytesToHex2, concatBytes, hexToBytes, utf8ToBytes } from "@noble/hashes/utils";
444
- var OPERATIONS = {
445
- transact: "Transact",
446
- "create-credit": "CreateCredit",
447
- "create-credit-initial-payment": "CreateCreditInitialPayment",
448
- "credit-draw": "CreditDraw",
449
- "update-credit": "UpdateCredit"
450
- };
451
- var WALLET_AUTHORIZATION_TYPES = {
452
- WalletAuthorization: [
453
- { name: "operation", type: "bytes32" },
454
- { name: "statementHash", type: "bytes32" }
455
- ]
456
- };
457
- var hex = (value) => `0x${bytesToHex2(value)}`;
458
- function bytes(value, length) {
459
- if (typeof value === "string" && !/^0x(?:[0-9a-fA-F]{2})*$/.test(value))
460
- throw new Error("invalid hexadecimal bytes");
461
- if (typeof value !== "string" && !(value instanceof Uint8Array))
462
- throw new TypeError("expected bytes");
463
- const result = typeof value === "string" ? hexToBytes(value.slice(2)) : Uint8Array.from(value);
464
- if (length !== void 0 && result.length !== length)
465
- throw new Error(`expected ${length} bytes`);
466
- return result;
467
- }
468
- function word(value) {
469
- if (value < 0n || value >= 1n << 256n) throw new RangeError("value exceeds uint256");
470
- return hexToBytes(value.toString(16).padStart(64, "0"));
471
- }
472
- async function computeOwnerAddress(publicKey) {
473
- const point = secp256k1.ProjectivePoint.fromHex(bytes(publicKey));
474
- point.assertValidity();
475
- return hex(keccak_256(point.toRawBytes(false).slice(1)).slice(12));
476
- }
477
- function walletAuthorizationTypedData(request) {
478
- const { context: context2, operation, capacity, words } = request;
479
- if (!Object.hasOwn(OPERATIONS, operation)) throw new Error("unsupported wallet operation");
480
- const allowed = operation === "transact" ? [
481
- 1,
482
- 2,
483
- 3,
484
- 4,
485
- 5,
486
- 6,
487
- 7,
488
- 8,
489
- 9,
490
- 10,
491
- 20,
492
- 30,
493
- 40,
494
- 50,
495
- 60,
496
- 70,
497
- 80,
498
- 90,
499
- 100,
500
- 110,
501
- 120,
502
- 130,
503
- 140,
504
- 150,
505
- 160,
506
- 170,
507
- 180,
508
- 190
509
- ] : operation === "credit-draw" ? [1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 60, 70, 80] : [1];
510
- if (!allowed.includes(capacity)) throw new Error("invalid operation capacity");
511
- if (!Array.isArray(words) || words.length < 2) throw new Error("public words required");
512
- for (const value of words)
513
- if (typeof value !== "bigint" || value < 0n || value >= FIELD_MODULUS)
514
- throw new RangeError("noncanonical public field");
515
- if (operation !== "transact") {
516
- const expected = operation === "create-credit" ? 11 : operation === "update-credit" ? 14 : operation === "credit-draw" ? 15 + 9 * capacity : 15;
517
- if (words.length !== expected) throw new Error("invalid Credit statement width");
518
- const start = operation === "update-credit" ? 8 : operation === "credit-draw" ? 6 + 5 * capacity : 4;
519
- const count = operation === "credit-draw" ? capacity : 1;
520
- const actual = operation === "credit-draw" ? Number(words[3]) : 1;
521
- if (!Number.isSafeInteger(actual) || actual <= 0 || actual > count)
522
- throw new Error("invalid grant count");
523
- for (let i = 0; i < count; i++) {
524
- if (i < actual) normalizeCreditGrantId(words[start + i]);
525
- else if (words[start + i] !== 0n) throw new Error("grantId padding must be zero");
526
- }
527
- }
528
- const { chainId, protocolAddress } = context2;
529
- if (typeof chainId !== "bigint" || chainId < 0n || chainId >= 1n << 64n)
530
- throw new RangeError("invalid chain id");
531
- if (typeof protocolAddress !== "bigint" || protocolAddress <= 0n || protocolAddress >= 1n << 160n)
532
- throw new RangeError("invalid protocol address");
533
- if (words[0] !== chainId) throw new Error("statement chain mismatch");
534
- if (words[1] !== protocolAddress) throw new Error("statement instance mismatch");
535
- const statement = concatBytes(
536
- word(BigInt(capacity)),
537
- word(64n),
538
- word(BigInt(words.length)),
539
- ...words.map(word)
540
- );
541
- return {
542
- domain: {
543
- name: "InvisibleProtocol",
544
- version: "1",
545
- chainId,
546
- verifyingContract: `0x${protocolAddress.toString(16).padStart(40, "0")}`
547
- },
548
- types: WALLET_AUTHORIZATION_TYPES,
549
- primaryType: "WalletAuthorization",
550
- message: {
551
- operation: hex(
552
- keccak_256(
553
- utf8ToBytes(
554
- `Invisi.${OPERATIONS[operation]}.${operation === "transact" ? "v1" : "GrantId.Uint128.v1"}`
555
- )
556
- )
557
- ),
558
- statementHash: hex(keccak_256(statement))
559
- }
560
- };
561
- }
562
- function computeWalletAuthorizationDigest(request) {
563
- const data = walletAuthorizationTypedData(request), hashText = (text) => keccak_256(utf8ToBytes(text));
564
- const domain = keccak_256(
565
- concatBytes(
566
- hashText(
567
- "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
568
- ),
569
- hashText(data.domain.name),
570
- hashText(data.domain.version),
571
- word(data.domain.chainId),
572
- word(BigInt(data.domain.verifyingContract))
573
- )
574
- );
575
- const structure = keccak_256(
576
- concatBytes(
577
- hashText("WalletAuthorization(bytes32 operation,bytes32 statementHash)"),
578
- bytes(data.message.operation),
579
- bytes(data.message.statementHash)
580
- )
581
- );
582
- return hex(keccak_256(concatBytes(new Uint8Array([25, 1]), domain, structure)));
583
- }
584
- function signWalletAuthorization(privateKey, request) {
585
- return hex(
586
- secp256k1.sign(bytes(computeWalletAuthorizationDigest(request)), bytes(privateKey, 32), {
587
- lowS: true
588
- }).toCompactRawBytes()
589
- );
590
- }
591
- async function verifyWalletAuthorization(expectedIdentity, publicKey, signature, request) {
592
- const raw = bytes(signature, 64), digest = bytes(computeWalletAuthorizationDigest(request));
593
- if (await computeOwnerAddress(publicKey) !== expectedIdentity) return false;
594
- return secp256k1.verify(raw, digest, bytes(publicKey), { lowS: true });
595
- }
596
- async function buildWalletAuthorizationWitness(wallet, request) {
597
- const publicKey = secp256k1.ProjectivePoint.fromHex(bytes(wallet.spendingPublicKey)).toRawBytes(
598
- false
599
- );
600
- const privateKey = bytes(wallet.spendingPrivateKey, 32), identity2 = wallet.ownerAddress;
601
- const statement = { ...request, context: { ...request.context }, words: [...request.words] };
602
- try {
603
- const derived = secp256k1.getPublicKey(privateKey, false);
604
- if (!derived.every((value, i) => value === publicKey[i]))
605
- throw new Error("spending key pair mismatch");
606
- if (BigInt(await computeOwnerAddress(publicKey)) !== BigInt(identity2))
607
- throw new Error("owner address mismatch");
608
- return {
609
- public_key_x: Array.from(publicKey.slice(1, 33)),
610
- public_key_y: Array.from(publicKey.slice(33)),
611
- signature: Array.from(bytes(signWalletAuthorization(privateKey, statement), 64))
612
- };
613
- } finally {
614
- privateKey.fill(0);
615
- }
616
- }
617
-
618
- // src/wallet/capabilities.ts
619
- var copyWitness = (witness) => ({
620
- public_key_x: [...witness.public_key_x],
621
- public_key_y: [...witness.public_key_y],
622
- signature: [...witness.signature]
623
- });
624
- var inspect = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
625
- function copyBytes(value) {
626
- if (typeof value === "string" && !/^0x(?:[0-9a-fA-F]{2})+$/.test(value)) {
627
- throw new Error("invalid hexadecimal bytes");
628
- }
629
- return typeof value === "string" ? hexToBytes2(value.slice(2)) : Uint8Array.from(value);
630
- }
631
- function identity(value) {
632
- return ReceivingAddress.fromIdentity(value).ownerAddress;
633
- }
634
- var ViewingCapability = class {
635
- #key;
636
- ownerAddress;
637
- constructor(ownerAddress, privateKey, expectedPublicKey) {
638
- this.ownerAddress = identity(ownerAddress);
639
- this.#key = copyBytes(privateKey);
640
- const publicKey = viewingPublicKey(this.#key);
641
- if (expectedPublicKey && bytesToHex3(publicKey) !== bytesToHex3(expectedPublicKey)) {
642
- throw new Error("viewing key pair mismatch");
643
- }
644
- Object.freeze(this);
645
- }
646
- decryptNote(envelope, context2) {
647
- return decryptPrivateTransferNote(this.#key, envelope, {
648
- ...context2,
649
- ownerAddress: this.ownerAddress
650
- });
651
- }
652
- decryptCredit(envelope, context2) {
653
- return decryptCreditState(this.#key, envelope, {
654
- ...context2,
655
- ownerAddress: this.ownerAddress
656
- });
657
- }
658
- getPublicKey() {
659
- return viewingPublicKey(this.#key);
660
- }
661
- /** Disclose this authenticated output's payload key, without exporting the wallet viewing key. */
662
- discloseNote(envelope, context2) {
663
- return Disclosure.fromEncryptedNote(this.#key, envelope, {
664
- ...context2,
665
- ownerAddress: this.ownerAddress
666
- });
667
- }
668
- /** Exposes the entire Credit envelope; prefer Disclosure.fromCredit() for hash-only opening. */
669
- discloseCredit(envelope, context2) {
670
- return Disclosure.fromEncryptedCredit(this.#key, envelope, {
671
- ...context2,
672
- ownerAddress: this.ownerAddress
673
- });
674
- }
675
- /** Explicit sensitive export for delegating viewing. It grants note recovery and owner-only sweep permission. */
676
- exportKey() {
677
- return Uint8Array.from(this.#key);
678
- }
679
- toJSON() {
680
- return { capability: "viewing", ownerAddress: this.ownerAddress };
681
- }
682
- [inspect]() {
683
- return this.toJSON();
684
- }
685
- };
686
- var Detector = class {
687
- #key;
688
- #clueKey;
689
- constructor(key) {
690
- this.#key = Uint8Array.from(key);
691
- this.#clueKey = deriveClueKey(this.#key);
692
- Object.freeze(this);
693
- }
694
- getClueKey() {
695
- return Uint8Array.from(this.#clueKey);
696
- }
697
- /** Full detection delegation; the receiver chooses the checked prefix length. */
698
- exportKey() {
699
- return Uint8Array.from(this.#key);
700
- }
701
- toJSON() {
702
- return { capability: "detection" };
703
- }
704
- [inspect]() {
705
- return this.toJSON();
706
- }
707
- };
708
- var NullifierCapability = class _NullifierCapability {
709
- ownerAddress;
710
- constructor(ownerAddress) {
711
- this.ownerAddress = identity(ownerAddress);
712
- Object.freeze(this);
713
- }
714
- static fromIdentity(ownerAddress) {
715
- return new _NullifierCapability(ownerAddress);
716
- }
717
- compute(chainId, protocolAddress, commitment2, nonce2) {
718
- return computeNoteNullifier(chainId, protocolAddress, nonce2, commitment2);
719
- }
720
- toJSON() {
721
- return { capability: "nullifier", ownerAddress: this.ownerAddress };
722
- }
723
- [inspect]() {
724
- return this.toJSON();
725
- }
726
- };
727
- var AuthorizedStatement = class {
728
- #witness;
729
- digest;
730
- ownerAddress;
731
- constructor(ownerAddress, digest, witness) {
732
- this.ownerAddress = ownerAddress;
733
- this.digest = digest;
734
- this.#witness = copyWitness(witness);
735
- Object.freeze(this);
736
- }
737
- withWitness(assemble) {
738
- return assemble(copyWitness(this.#witness));
739
- }
740
- toJSON() {
741
- return { ownerAddress: this.ownerAddress, digest: this.digest };
742
- }
743
- [inspect]() {
744
- return this.toJSON();
745
- }
746
- };
747
- var WalletAuthorization = class _WalletAuthorization {
748
- #privateKey;
749
- #publicKey;
750
- ownerAddress;
751
- constructor(ownerAddress, privateKey, publicKey) {
752
- this.ownerAddress = ownerAddress;
753
- this.#privateKey = privateKey;
754
- this.#publicKey = publicKey;
755
- Object.freeze(this);
756
- }
757
- static async fromMaterial(ownerAddress, privateKey) {
758
- const privateBytes = copyBytes(privateKey);
759
- const publicBytes = secp256k12.getPublicKey(privateBytes, false);
760
- if (await computeOwnerAddress(publicBytes) !== identity(ownerAddress)) {
761
- throw new Error("owner address mismatch");
762
- }
763
- return new _WalletAuthorization(identity(ownerAddress), privateBytes, publicBytes);
764
- }
765
- getPublicKey() {
766
- return Uint8Array.from(this.#publicKey);
767
- }
768
- async authorize(request) {
769
- const frozen = { ...request, context: { ...request.context }, words: [...request.words] };
770
- const digest = computeWalletAuthorizationDigest(frozen);
771
- const witness = await buildWalletAuthorizationWitness(
772
- {
773
- ownerAddress: this.ownerAddress,
774
- spendingPrivateKey: this.#privateKey,
775
- spendingPublicKey: this.#publicKey
776
- },
777
- frozen
778
- );
779
- return new AuthorizedStatement(this.ownerAddress, digest, witness);
780
- }
781
- toJSON() {
782
- return { capability: "wallet-authorization", ownerAddress: this.ownerAddress };
783
- }
784
- [inspect]() {
785
- return this.toJSON();
786
- }
787
- };
788
-
789
- // src/wallet/wallet-object.ts
790
- var WalletAddress = class {
791
- #ownerAddress;
792
- #receivingKeys;
793
- constructor(address) {
794
- this.#receivingKeys = address.getReceivingKeys();
795
- this.#ownerAddress = address.ownerAddress;
796
- }
797
- get ownerAddress() {
798
- return this.#ownerAddress;
799
- }
800
- get viewingPublicKey() {
801
- return this.#receivingKeys.viewingPublicKey.slice();
802
- }
803
- get clueKey() {
804
- return this.#receivingKeys.clueKey.slice();
805
- }
806
- /** Encode the complete public receiving material on demand. */
807
- getAddress() {
808
- return encodeLongAddress({ ownerAddress: this.#ownerAddress, ...this.#receivingKeys });
809
- }
810
- getReceivingAddress() {
811
- return ReceivingAddress.from({ ownerAddress: this.#ownerAddress, ...this.#receivingKeys });
812
- }
813
- /** Nullifiers derive from public identity and do not grant spending authority. */
814
- exportNullifier() {
815
- return NullifierCapability.fromIdentity(this.ownerAddress);
816
- }
817
- toJSON() {
818
- return { ownerAddress: this.ownerAddress, address: this.getAddress() };
819
- }
820
- [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
821
- return this.toJSON();
822
- }
823
- };
824
- var Wallet = class _Wallet extends WalletAddress {
825
- constructor(address) {
826
- super(address);
827
- Object.freeze(this);
828
- }
829
- /** Parse complete 0i receiving material without network access. */
830
- static fromAddress(address) {
831
- if (typeof address !== "string" && !(address instanceof ReceivingAddress)) {
832
- throw new TypeError("expected a validated receiving address");
833
- }
834
- return new _Wallet(typeof address === "string" ? ReceivingAddress.parse(address) : address);
835
- }
836
- };
837
-
838
- // src/delivery/memo.ts
839
- var MAX_MEMO_BYTES = 256;
840
- function encodeMemo(memo) {
841
- if (memo === void 0) return new Uint8Array();
842
- let encoded;
843
- if (typeof memo === "string") {
844
- for (let i = 0; i < memo.length; i++) {
845
- const unit = memo.charCodeAt(i);
846
- if (unit >= 55296 && unit <= 56319) {
847
- const next = memo.charCodeAt(++i);
848
- if (!(next >= 56320 && next <= 57343))
849
- throw new Error("memo contains an invalid surrogate");
850
- } else if (unit >= 56320 && unit <= 57343)
851
- throw new Error("memo contains an invalid surrogate");
852
- }
853
- encoded = new TextEncoder().encode(memo);
854
- } else if (memo instanceof Uint8Array) encoded = Uint8Array.from(memo);
855
- else throw new TypeError("memo must be text or Uint8Array");
856
- if (encoded.length > MAX_MEMO_BYTES) throw new RangeError("memo exceeds 256 bytes");
857
- return encoded;
858
- }
859
- function decodeMemoText(memo) {
860
- return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(memo);
861
- }
862
-
863
- // src/wallet/signing-request.ts
864
- import { TypedDataEncoder } from "ethers";
865
- function createSigningRequest(data) {
866
- const types = Object.fromEntries(
867
- Object.entries(data.types).map(([name, fields]) => [name, [...fields]])
868
- );
869
- const payload = TypedDataEncoder.getPayload(data.domain, types, data.message);
870
- if (payload.primaryType !== data.primaryType) {
871
- throw new Error("signing request primary type mismatch");
872
- }
873
- delete payload.types.EIP712Domain;
874
- return structuredClone(payload);
875
- }
876
-
877
- // src/delivery/payload.ts
878
- function encodeData(data) {
879
- if (!data || typeof data !== "object" || Array.isArray(data)) {
880
- throw new TypeError("v1 payload data must be an object");
881
- }
882
- for (const key of Object.keys(data)) {
883
- if (key !== "memo") throw new Error(`unsupported v1 payload field ${key}`);
884
- }
885
- const memo = encodeMemo(data.memo);
886
- return new Uint8Array([1, ...memo]);
887
- }
888
- function readData(value) {
889
- if (!(value instanceof Uint8Array) || value.length < 1) {
890
- throw new Error("payload version required");
891
- }
892
- if (value[0] !== 1) throw new Error("unsupported payload version");
893
- const memo = Uint8Array.from(value.subarray(1));
894
- if (memo.length > 256) throw new Error("invalid memo length");
895
- return memo.length === 0 ? {} : { memo };
896
- }
897
- var fundsV1 = Object.freeze({
898
- encode(data = {}) {
899
- return encodeData(data);
900
- },
901
- decode(value) {
902
- return readData(value);
903
- }
904
- });
905
- var creditV1 = Object.freeze({
906
- encode(data = {}) {
907
- return encodeData(data);
908
- },
909
- decode(value) {
910
- return readData(value);
911
- }
912
- });
913
-
914
- // src/delivery/decryptor.ts
915
- import { bytesToHex as bytesToHex4 } from "@noble/hashes/utils";
916
- var DeliveryDecryptionError = class extends Error {
917
- constructor(cause) {
918
- super(cause instanceof Error ? cause.message : "delivery decryption failed", { cause });
919
- this.name = "DeliveryDecryptionError";
920
- }
921
- };
922
- function checkedPlaintext(plaintext, codec) {
923
- if (!(plaintext instanceof Uint8Array)) throw new Error("invalid decrypted plaintext");
924
- if (plaintext.length + 78 < codec.minimum || plaintext.length + 78 > codec.maximum)
925
- throw new Error("invalid plaintext length");
926
- return plaintext.slice();
927
- }
928
- function authenticatedDecryptor(owner2, decryptor, expectedKeys) {
929
- const ownerAddress = ReceivingAddress.fromIdentity(owner2).ownerAddress;
930
- const receivingKeys = expectedKeys ? {
931
- viewingPublicKey: expectedKeys.viewingPublicKey.slice(),
932
- clueKey: expectedKeys.clueKey.slice()
933
- } : void 0;
934
- return {
935
- ownerAddress,
936
- async detectCandidates(candidates) {
937
- if (!decryptor.detect) return candidates.map(() => "candidate");
938
- const result = await decryptor.detect(structuredClone(candidates));
939
- if (!result || BigInt(result.ownerAddress) !== BigInt(ownerAddress) || !Array.isArray(result.results) || result.results.length !== candidates.length || result.results.some(
940
- (value) => !["candidate", "not-recipient", "unresolved"].includes(value)
941
- ))
942
- throw new DeliveryDecryptionError(
943
- new Error("invalid detection batch or wrong account")
944
- );
945
- return [...result.results];
946
- },
947
- async decryptNote(envelope, context2) {
948
- context2 = { ...context2 };
949
- try {
950
- const bytes2 = validateDeliveryCiphertext(envelope, "funds");
951
- const full = { ...context2, ownerAddress };
952
- const plaintext = await decryptor.decryptNote(bytes2.slice(), { ...full });
953
- if (plaintext === null) return null;
954
- if (!(plaintext instanceof Uint8Array)) {
955
- if (plaintext?.status === "authentication-failed")
956
- throw new DeliveryAuthenticationError();
957
- throw new Error("invalid decryption result");
958
- }
959
- const codec = deliveryCodec(bytes2[0]);
960
- if (codec.kind !== "funds") throw new Error("unexpected envelope kind");
961
- const note = codec.decode(checkedPlaintext(plaintext, codec), full);
962
- if (BigInt(note.ownerAddress) !== BigInt(ownerAddress) || note.tokenAddress !== context2.tokenAddress)
963
- throw new Error("decrypted note context mismatch");
964
- await noteCommitment(full, note);
965
- return note;
966
- } catch (cause) {
967
- if (cause instanceof DeliveryAuthenticationError) throw cause;
968
- throw new DeliveryDecryptionError(cause);
969
- }
970
- },
971
- async decryptCredit(envelope, context2) {
972
- context2 = { ...context2 };
973
- try {
974
- const bytes2 = validateDeliveryCiphertext(envelope, "credit");
975
- const full = { ...context2, ownerAddress };
976
- const plaintext = await decryptor.decryptCredit(bytes2.slice(), { ...full });
977
- if (plaintext === null) return null;
978
- if (!(plaintext instanceof Uint8Array)) {
979
- if (plaintext?.status === "authentication-failed")
980
- throw new DeliveryAuthenticationError();
981
- throw new Error("invalid decryption result");
982
- }
983
- const codec = deliveryCodec(bytes2[0]);
984
- if (codec.kind !== "credit") throw new Error("unexpected envelope kind");
985
- const state = codec.decode(checkedPlaintext(plaintext, codec), full);
986
- const identity2 = context2.role === "owner" ? state.note.ownerWalletIdentity : state.note.spenderWalletIdentity;
987
- if (BigInt(identity2) !== BigInt(ownerAddress) || state.note.tokenAddress !== context2.tokenAddress)
988
- throw new Error("decrypted credit context mismatch");
989
- if (receivingKeys) {
990
- const keys = context2.role === "owner" ? state.ownerReceivingKeys : state.spenderReceivingKeys;
991
- if (bytesToHex4(keys.viewingPublicKey) !== bytesToHex4(receivingKeys.viewingPublicKey))
992
- throw new Error("decrypted credit receiving key mismatch");
993
- }
994
- await creditCommitment(full, state.note);
995
- return state;
996
- } catch (cause) {
997
- if (cause instanceof DeliveryAuthenticationError) throw cause;
998
- throw new DeliveryDecryptionError(cause);
999
- }
1000
- }
1001
- };
1002
- }
1003
-
1004
- // src/wallet/wallet-wire.ts
1005
- import { bytesToHex as bytesToHex5, hexToBytes as hexToBytes3 } from "@noble/hashes/utils";
1006
- var walletHex = (bytes2) => `0x${bytesToHex5(bytes2)}`;
1007
- function walletBytes(value, length) {
1008
- if (typeof value !== "string" || !/^0x(?:[0-9a-f]{2})*$/.test(value))
1009
- throw new Error("invalid canonical hex bytes");
1010
- const bytes2 = hexToBytes3(value.slice(2));
1011
- if (length !== void 0 && bytes2.length !== length) throw new Error("invalid byte length");
1012
- return bytes2;
1013
- }
1014
- function walletInteger(value) {
1015
- if (typeof value !== "string" || !/^(0|[1-9][0-9]*)$/.test(value) || value.length > 78)
1016
- throw new Error("invalid canonical integer");
1017
- return BigInt(value);
1018
- }
1019
- function walletAuthorizationParams(params) {
1020
- return {
1021
- ...params,
1022
- words: params.words.map(walletInteger),
1023
- context: {
1024
- chainId: walletInteger(params.context.chainId),
1025
- protocolAddress: walletInteger(params.context.protocolAddress)
1026
- }
1027
- };
1028
- }
1029
- function walletDecryptionContext(request) {
1030
- const context2 = request.params.context;
1031
- return {
1032
- chainId: walletInteger(context2.chainId),
1033
- protocolAddress: walletInteger(context2.protocolAddress),
1034
- tokenAddress: walletInteger(context2.tokenAddress),
1035
- outputCommitment: context2.outputCommitment,
1036
- ownerAddress: request.ownerAddress,
1037
- ...context2.role ? { role: context2.role } : {}
1038
- };
1039
- }
1040
- function freeze(value) {
1041
- if (value && typeof value === "object") {
1042
- Object.values(value).forEach(freeze);
1043
- Object.freeze(value);
1044
- }
1045
- return value;
1046
- }
1047
- function exactKeys(value, keys) {
1048
- if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !keys.includes(key)) || keys.some((key) => !Object.hasOwn(value, key)))
1049
- throw new Error("unexpected wallet fields");
1050
- }
1051
- function validateWalletRequest(request) {
1052
- exactKeys(request, ["version", "id", "ownerAddress", "method", "params"]);
1053
- if (request.version !== 1 || typeof request.id !== "string" || !/^[\x21-\x7e]{1,128}$/.test(request.id))
1054
- throw new Error("invalid wallet request envelope");
1055
- walletBytes(request.ownerAddress, 20);
1056
- ReceivingAddress.fromIdentity(request.ownerAddress);
1057
- switch (request.method) {
1058
- case "wallet.public":
1059
- exactKeys(request.params, []);
1060
- break;
1061
- case "wallet.detect": {
1062
- exactKeys(request.params, ["clues"]);
1063
- const { clues } = request.params;
1064
- if (!Array.isArray(clues) || clues.length > 1024) throw new Error("invalid clues");
1065
- clues.forEach((clue) => walletBytes(clue, 68));
1066
- break;
1067
- }
1068
- case "wallet.authorize": {
1069
- exactKeys(request.params, ["operation", "capacity", "words", "context"]);
1070
- const params = request.params;
1071
- exactKeys(params.context, ["chainId", "protocolAddress"]);
1072
- if (!Array.isArray(params.words) || params.words.length > 8192)
1073
- throw new Error("invalid authorization words");
1074
- computeWalletAuthorizationDigest(walletAuthorizationParams(params));
1075
- break;
1076
- }
1077
- case "wallet.decryptNote":
1078
- case "wallet.decryptCredit": {
1079
- const typed = request;
1080
- exactKeys(typed.params, ["envelope", "context"]);
1081
- exactKeys(typed.params.context, [
1082
- "chainId",
1083
- "protocolAddress",
1084
- "tokenAddress",
1085
- "outputCommitment",
1086
- ...request.method === "wallet.decryptCredit" ? ["role"] : []
1087
- ]);
1088
- const context2 = walletDecryptionContext(typed);
1089
- walletBytes(context2.outputCommitment, 32);
1090
- validateContext(context2, context2.tokenAddress);
1091
- if (request.method === "wallet.decryptCredit" && context2.role !== "owner" && context2.role !== "spender")
1092
- throw new Error("invalid credit role");
1093
- if (request.method === "wallet.decryptNote" && context2.role !== void 0)
1094
- throw new Error("unexpected note role");
1095
- walletBytes(typed.params.envelope);
1096
- validateDeliveryCiphertext(
1097
- typed.params.envelope,
1098
- request.method === "wallet.decryptCredit" ? "credit" : "funds"
1099
- );
1100
- break;
1101
- }
1102
- default:
1103
- throw new Error("unsupported wallet method");
1104
- }
1105
- }
1106
- var retainedWallets = /* @__PURE__ */ new WeakMap();
1107
- function prepareWalletRequest(wallet, id, method, params) {
1108
- if (!(wallet instanceof Wallet) && typeof wallet !== "string")
1109
- throw new TypeError("ownerAddress or public Wallet required");
1110
- const ownerAddress = ReceivingAddress.fromIdentity(
1111
- typeof wallet === "string" ? wallet : wallet.ownerAddress
1112
- ).ownerAddress;
1113
- const request = structuredClone({
1114
- version: 1,
1115
- id,
1116
- ownerAddress,
1117
- method,
1118
- params
1119
- });
1120
- validateWalletRequest(request);
1121
- const prepared = freeze({ request });
1122
- retainedWallets.set(
1123
- prepared,
1124
- wallet instanceof Wallet ? { ownerAddress, viewingPublicKey: wallet.viewingPublicKey, clueKey: wallet.clueKey } : { ownerAddress }
1125
- );
1126
- return prepared;
1127
- }
1128
- async function acceptWalletResponse(prepared, response) {
1129
- return acceptResponse(prepared, response);
1130
- }
1131
- async function acceptResponse(prepared, response) {
1132
- const wallet = retainedWallets.get(prepared);
1133
- if (!wallet) throw new Error("wallet request was not prepared by this SDK instance");
1134
- const request = prepared.request;
1135
- validateWalletRequest(request);
1136
- const safe = structuredClone(response);
1137
- if (safe.version !== request.version || safe.id !== request.id || safe.ownerAddress !== request.ownerAddress || safe.method !== request.method)
1138
- throw new Error("wallet response envelope mismatch");
1139
- validateWalletResponses([request], [safe]);
1140
- if ("error" in safe) throw new NativeWalletError(safe.error.code);
1141
- const result = safe.result;
1142
- exactKeys(
1143
- result,
1144
- request.method === "wallet.public" ? ["viewingPublicKey", "spendingPublicKey", "clueKey"] : request.method === "wallet.authorize" ? ["spendingPublicKey", "signature", "digest"] : request.method === "wallet.detect" ? ["matches"] : ["plaintext"]
1145
- );
1146
- if (request.method === "wallet.public") {
1147
- walletBytes(result.spendingPublicKey, 65);
1148
- walletBytes(result.viewingPublicKey, 33);
1149
- walletBytes(result.clueKey, 32);
1150
- if (await computeOwnerAddress(result.spendingPublicKey) !== request.ownerAddress)
1151
- throw new Error("wallet public identity mismatch");
1152
- if (wallet.viewingPublicKey && wallet.clueKey && (walletHex(wallet.viewingPublicKey) !== result.viewingPublicKey || walletHex(wallet.clueKey) !== result.clueKey))
1153
- throw new Error("wallet receiving key mismatch");
1154
- ReceivingAddress.from({
1155
- ownerAddress: request.ownerAddress,
1156
- viewingPublicKey: walletBytes(result.viewingPublicKey),
1157
- clueKey: walletBytes(result.clueKey)
1158
- });
1159
- } else if (request.method === "wallet.authorize") {
1160
- const auth = walletAuthorizationParams(request.params);
1161
- if (result.digest !== computeWalletAuthorizationDigest(auth) || !await verifyWalletAuthorization(
1162
- request.ownerAddress,
1163
- result.spendingPublicKey,
1164
- result.signature,
1165
- auth
1166
- ))
1167
- throw new Error("invalid wallet authorization response");
1168
- const publicKey = walletBytes(result.spendingPublicKey, 65);
1169
- return new AuthorizedStatement(request.ownerAddress, result.digest, {
1170
- public_key_x: Array.from(publicKey.slice(1, 33)),
1171
- public_key_y: Array.from(publicKey.slice(33)),
1172
- signature: Array.from(walletBytes(result.signature, 64))
1173
- });
1174
- } else if (request.method === "wallet.detect") {
1175
- if (!Array.isArray(result.matches) || result.matches.length !== request.params.clues.length || result.matches.some((v) => typeof v !== "boolean"))
1176
- throw new Error("invalid detection response");
1177
- } else {
1178
- const typed = request;
1179
- const context2 = walletDecryptionContext(typed);
1180
- const plaintext = walletBytes(result.plaintext);
1181
- const viewing = authenticatedDecryptor(
1182
- request.ownerAddress,
1183
- {
1184
- decryptNote: async () => plaintext,
1185
- decryptCredit: async () => plaintext
1186
- },
1187
- wallet.viewingPublicKey && wallet.clueKey ? { viewingPublicKey: wallet.viewingPublicKey, clueKey: wallet.clueKey } : void 0
1188
- );
1189
- return typed.method === "wallet.decryptNote" ? viewing.decryptNote(typed.params.envelope, context2) : viewing.decryptCredit(typed.params.envelope, context2);
1190
- }
1191
- return result;
1192
- }
1193
- var NativeWalletError = class extends Error {
1194
- constructor(code) {
1195
- super(code);
1196
- this.code = code;
1197
- this.name = "NativeWalletError";
1198
- }
1199
- };
1200
- var MAX_WALLET_BATCH_BYTES = 16 * 1024 * 1024;
1201
- function boundedJson(value) {
1202
- const json = JSON.stringify(value);
1203
- if (typeof json !== "string" || new TextEncoder().encode(json).length > MAX_WALLET_BATCH_BYTES)
1204
- throw new Error("wallet batch exceeds encoded size limit");
1205
- }
1206
- function validateWalletBatch(requests) {
1207
- if (!Array.isArray(requests) || requests.length > 1024) throw new Error("invalid wallet batch");
1208
- boundedJson(requests);
1209
- const ids = /* @__PURE__ */ new Set();
1210
- for (const request of requests) {
1211
- validateWalletRequest(request);
1212
- if (ids.has(request.id)) throw new Error("duplicate wallet request id");
1213
- if (request.ownerAddress !== requests[0].ownerAddress)
1214
- throw new Error("mixed wallet batch owners");
1215
- ids.add(request.id);
1216
- }
1217
- }
1218
- function validateWalletResponses(requests, responses) {
1219
- validateWalletBatch(requests);
1220
- if (!Array.isArray(responses) || responses.length !== requests.length)
1221
- throw new Error("wallet response batch length mismatch");
1222
- boundedJson(responses);
1223
- const expected = new Map(requests.map((request) => [request.id, request]));
1224
- const found = /* @__PURE__ */ new Map();
1225
- for (const response of responses) {
1226
- if (!response || typeof response !== "object") throw new Error("invalid wallet response");
1227
- const request = expected.get(response.id);
1228
- if (!request || found.has(response.id) || response.version !== 1 || response.method !== request.method || response.ownerAddress !== request.ownerAddress)
1229
- throw new Error("wallet response envelope mismatch");
1230
- if (Object.hasOwn(response, "error")) {
1231
- exactKeys(response, ["version", "id", "ownerAddress", "method", "error"]);
1232
- exactKeys(response.error, ["code"]);
1233
- if (typeof response.error?.code !== "string" || !/^[A-Z][A-Z0-9_]{0,127}$/.test(response.error.code))
1234
- throw new Error("invalid native wallet error");
1235
- } else {
1236
- exactKeys(response, ["version", "id", "ownerAddress", "method", "result"]);
1237
- if (!response.result || typeof response.result !== "object" || Array.isArray(response.result))
1238
- throw new Error("invalid wallet result");
1239
- const result = response.result;
1240
- exactKeys(
1241
- result,
1242
- request.method === "wallet.public" ? ["viewingPublicKey", "spendingPublicKey", "clueKey"] : request.method === "wallet.authorize" ? ["spendingPublicKey", "signature", "digest"] : request.method === "wallet.detect" ? ["matches"] : ["plaintext"]
1243
- );
1244
- if (request.method === "wallet.public") {
1245
- walletBytes(result.viewingPublicKey, 33);
1246
- walletBytes(result.spendingPublicKey, 65);
1247
- walletBytes(result.clueKey, 32);
1248
- } else if (request.method === "wallet.authorize") {
1249
- walletBytes(result.spendingPublicKey, 65);
1250
- walletBytes(result.signature, 64);
1251
- walletBytes(result.digest, 32);
1252
- } else if (request.method === "wallet.detect") {
1253
- if (!Array.isArray(result.matches) || result.matches.length !== request.params.clues.length || result.matches.some((value) => typeof value !== "boolean"))
1254
- throw new Error("invalid detection response");
1255
- } else {
1256
- walletBytes(result.plaintext);
1257
- }
1258
- }
1259
- found.set(response.id, response);
1260
- }
1261
- return requests.map((request) => found.get(request.id));
1262
- }
1263
- async function acceptWalletResponses(prepared, responses) {
1264
- for (const item of prepared) {
1265
- if (!retainedWallets.has(item))
1266
- throw new Error("wallet request was not prepared by this SDK instance");
1267
- }
1268
- const ordered = validateWalletResponses(
1269
- prepared.map((item) => item.request),
1270
- structuredClone(responses)
1271
- );
1272
- return Promise.all(prepared.map((item, index) => acceptWalletResponse(item, ordered[index])));
1273
- }
1274
-
1275
- // src/provenance/intent-hash.ts
1276
- import { AbiCoder, keccak256, toBeHex } from "ethers";
1277
- function provenanceIntentHash(originalRequestHash) {
1278
- return keccak256(
1279
- AbiCoder.defaultAbiCoder().encode(
1280
- ["string", "bytes32"],
1281
- ["InvisiBroadcasterProvenanceIntentV1", toBeHex(BigInt(originalRequestHash), 32)]
1282
- )
1283
- );
1284
- }
1285
- export {
1286
- AuthorizedStatement,
1287
- CREDIT_POLICY_FIELDS,
1288
- CREDIT_USAGE_FIELDS,
1289
- D_CNULL,
1290
- D_CREDIT,
1291
- D_CREDIT_KEY_HASH,
1292
- D_CREDIT_RECOVERY,
1293
- D_CREDIT_STATE_NONCE,
1294
- D_IDENT,
1295
- D_NOTE,
1296
- D_NULL,
1297
- DeliveryAuthenticationError,
1298
- DeliveryDecryptionError,
1299
- Detector,
1300
- Disclosure,
1301
- FIELD_MODULUS,
1302
- MAX_CIPHERTEXT_BYTES,
1303
- MAX_MEMO_BYTES,
1304
- MAX_WALLET_BATCH_BYTES,
1305
- MissingCapabilityError,
1306
- NativeWalletError,
1307
- NullifierCapability,
1308
- ReceivingAddress,
1309
- TREE_DEPTH,
1310
- ViewingCapability,
1311
- WALLET_AUTHORIZATION_TYPES,
1312
- Wallet,
1313
- acceptWalletResponse,
1314
- acceptWalletResponses,
1315
- applyCreditDrawUsage,
1316
- authenticatedDecryptor,
1317
- computeCreditCommitment,
1318
- computeCreditNullifier,
1319
- computeCreditRecoveryPad,
1320
- computeCreditSharedKeyHash,
1321
- computeNoteCommitment,
1322
- computeNoteIdentity,
1323
- computeNoteNullifier,
1324
- computeOwnerAddress,
1325
- computeWalletAuthorizationDigest,
1326
- createClue,
1327
- createClueFromSeed,
1328
- createSigningRequest,
1329
- creditPeriods,
1330
- creditV1,
1331
- decodeAddress,
1332
- decodeDeliveryHeader,
1333
- decodeMemoText,
1334
- decryptCreditState,
1335
- decryptPrivateTransferNote,
1336
- deliveryCodec,
1337
- deliveryHeader,
1338
- deriveClueKey,
1339
- deriveCreditState,
1340
- deriveCreditStateNonce,
1341
- deriveCreditUpdate,
1342
- encodeMemo,
1343
- encryptCreditState,
1344
- encryptPrivateTransferNote,
1345
- fundsV1,
1346
- generateCreditGrantId,
1347
- generateCreditSharedKey,
1348
- generateNonce,
1349
- normalizeCreditDeliveryState,
1350
- normalizeCreditGrantId,
1351
- normalizeCreditPolicy,
1352
- normalizeCreditState,
1353
- normalizeCreditUsage,
1354
- poseidonHash,
1355
- prepareWalletRequest,
1356
- provenanceIntentHash,
1357
- recoverCreditState,
1358
- validateClueKey,
1359
- validateDeliveryCiphertext,
1360
- validateWalletBatch,
1361
- validateWalletResponses,
1362
- verifyWalletAuthorization,
1363
- viewingPublicKey,
1364
- walletAuthorizationTypedData
1365
- };
1
+ import{a as oe}from"./chunk-BEYWZRRT.js";import{A as It,B as St,C as Ut,D as kt,E as Nt,F as Ot,G as zt,H as Bt,I as Tt,J as Mt,K as J,L as E,M as D,N as Ke,O as Re,P as Pe,Q as Y,R as Ie,S as $t,T as Ht,U as N,V as O,W as Se,X as Ue,a as lt,b as ct,c as yt,d as pt,e as ut,f as mt,g as ft,h as wt,i as ht,j as C,k as gt,l as At,m as xt,n as ne,o as ie,p as W,q as Wt,r as Et,s as Dt,t as q,u as V,v as Kt,w as Rt,x as se,y as Pt,z as ae}from"./chunk-HJWID3PL.js";import{a as ke,b as de,c as _t,d as u}from"./chunk-27LYU3N6.js";import{a as s,b as We,c as Ee,d as F,e as vt,f as bt,g as Ct,h as De}from"./chunk-C35XZ674.js";import{bytesToHex as jt}from"@noble/hashes/utils";var Lt=["ownerAddress","amount","nonce"],Ne=["spenderWalletIdentity","ownerWalletIdentity","grantId","nonce","expiry","creditSharedKeyHash","singleLimit","dailyLimit","monthlyLimit","availableCredit","unlimited","lastDay","dailySpent","lastMonth","monthlySpent","totalSpent"];function le(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("invalid disclosure object");let r=Object.keys(e);if(r.length!==t.length||r.some(n=>!t.includes(n)))throw new Error("unexpected disclosure fields");return e}s(le,"record");function v(e,t,r){if(typeof e!="bigint"||e<0n||e>=1n<<BigInt(t))throw new Error(`invalid disclosure ${r}`);return e}s(v,"number");function X(e,t,r){if(typeof e!="string"||!/^(0|[1-9][0-9]*)$/.test(e)||e.length>78)throw new Error(`invalid disclosure ${r}`);return v(BigInt(e),t,r)}s(X,"decimal");function G(e,t,r=!0){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new Error(`invalid disclosure ${t}`);if(r&&BigInt(e)>=C)throw new Error(`invalid disclosure ${t}`);return e.toLowerCase()}s(G,"hash");function B(e,t){if(typeof e!="string"||!/^0x[0-9a-fA-F]{40}$/.test(e)||BigInt(e)===0n)throw new Error(`invalid disclosure ${t}`);return e.toLowerCase()}s(B,"owner");function ce(e){if(e<0n||e>=C)throw new Error("invalid disclosure nonce");return e}s(ce,"nonce");function x(e){let t={chainId:v(e.chainId,64,"chainId"),protocolAddress:v(e.protocolAddress,160,"protocolAddress"),tokenAddress:v(e.tokenAddress,160,"tokenAddress")};if(t.protocolAddress===0n||t.tokenAddress===0n)throw new Error("disclosure addresses must be nonzero");return t}s(x,"context");function z(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r.toString()]))}s(z,"encode");async function Oe(e){let t={...e};return{...x(t),...q(t),...V(t),availableCredit:v(t.availableCredit,128,"availableCredit"),unlimited:t.unlimited,spenderWalletIdentity:B(t.spenderWalletIdentity,"spender identity"),ownerWalletIdentity:B(t.ownerWalletIdentity,"owner identity"),grantId:W(t.grantId),nonce:ce(t.nonce),expiry:v(t.expiry,64,"expiry"),creditSharedKeyHash:await se(t.creditSharedKey)}}s(Oe,"creditOpening");async function Z(e){return"creditSharedKeyHash"in e?ae({...e,creditSharedKey:0n},e.creditSharedKeyHash):ie(e.chainId,BigInt(e.protocolAddress),await ne(BigInt(e.ownerAddress),e.nonce),e.tokenAddress,e.amount)}s(Z,"commitment");var K=class e{static{s(this,"Disclosure")}#e;constructor(t){this.#e={...t,context:Object.freeze({...t.context}),data:Object.freeze({...t.data})},Object.freeze(this.#e),Object.freeze(this)}static async fromNote(t){let r={...t},n={...x(r),ownerAddress:B(r.ownerAddress,"owner address"),amount:v(r.amount,128,"amount"),nonce:ce(r.nonce)};return new e({version:1,kind:"note",method:"opening",context:{...z(x(n)),outputCommitment:await Z(n)},data:z({ownerAddress:n.ownerAddress,amount:n.amount,nonce:n.nonce})})}static async fromCredit(t){let r=await Oe(t),n=Object.fromEntries(Ne.map(i=>[i,i==="unlimited"?r.unlimited?"1":"0":r[i].toString()]));return new e({version:1,kind:"credit",method:"opening",context:{...z(x(r)),outputCommitment:await Z(r)},data:n})}static async fromEncryptedNote(t,r,n){let i={...n},o=typeof r=="string"?r:Uint8Array.from(r),a=typeof t=="string"?t:Uint8Array.from(t);try{return await N(a,o,i),await e.fromEnvelope(a,o,i,"funds")}finally{a instanceof Uint8Array&&a.fill(0)}}static async fromEncryptedCredit(t,r,n){let i={...n},o=typeof r=="string"?r:Uint8Array.from(r),a=typeof t=="string"?t:Uint8Array.from(t);try{return await O(a,o,i),await e.fromEnvelope(a,o,i,i.role)}finally{a instanceof Uint8Array&&a.fill(0)}}static async fromEnvelope(t,r,n,i){let o=await Ie(t,r,i!=="funds");try{return new e({version:1,kind:i==="funds"?"note":"credit",method:"payload-key",context:{...z(x(n)),outputCommitment:G(n.outputCommitment,"commitment")},data:{payloadKey:`0x${jt(o)}`,ownerAddress:B(n.ownerAddress,"owner address"),role:i}})}finally{o.fill(0)}}static async fromExport(t){let r=le(t,["version","kind","method","context","data"]);if(r.version!==1||r.kind!=="note"&&r.kind!=="credit"||r.method!=="opening"&&r.method!=="payload-key")throw new Error("unsupported disclosure format");let n=le(r.context,["chainId","protocolAddress","tokenAddress","outputCommitment"]),i=x({chainId:X(n.chainId,64,"chainId"),protocolAddress:X(n.protocolAddress,160,"protocolAddress"),tokenAddress:X(n.tokenAddress,160,"tokenAddress")}),o=G(n.outputCommitment,"commitment"),a=r.method==="payload-key"?["payloadKey","ownerAddress","role"]:r.kind==="note"?Lt:Ne,d=le(r.data,a),c={};for(let l of a)if(l==="role"){if(r.kind==="note"?d[l]!=="funds":d[l]!=="owner"&&d[l]!=="spender")throw new Error("invalid disclosure role");c[l]=d[l]}else if(l==="payloadKey"||l.endsWith("Identity")||l==="ownerAddress"||l==="creditSharedKeyHash")c[l]=l.endsWith("Identity")||l==="ownerAddress"?B(d[l],l):G(d[l],l,l!=="payloadKey");else if(l==="unlimited"){if(d[l]!=="0"&&d[l]!=="1")throw Error("invalid disclosure unlimited");c[l]=d[l]}else{let g=l==="availableCredit"||l==="grantId"?128:l.endsWith("Payout")?160:l==="expiry"?64:l==="amount"?r.kind==="note"?128:126:254,h=X(d[l],g,l);l==="nonce"&&ce(h),c[l]=h.toString()}let y={version:1,kind:r.kind,method:r.method,context:{...z(i),outputCommitment:o},data:c},m=new e(y);return y.method==="opening"&&await m.verify({...i,outputCommitment:o,role:y.kind==="note"?"funds":"owner"}),m}getScope(){let{version:t,kind:r,method:n}=this.#e;return{version:t,kind:r,method:n,permitsOwnerSweep:r==="note",revealsNoteConsumption:r==="note",revealsCreditSharedKey:r==="credit"&&n==="payload-key",revealsReceivingKeys:r==="credit"&&n==="payload-key",revealsMemo:n==="payload-key",revealsPayload:n==="payload-key"}}export(){return{...this.#e,context:{...this.#e.context},data:{...this.#e.data}}}async verify(t){let r={...t,ciphertext:t.ciphertext instanceof Uint8Array?Uint8Array.from(t.ciphertext):t.ciphertext},n=x(r),i=this.#e;for(let d of["chainId","protocolAddress","tokenAddress"])if(n[d].toString()!==i.context[d])throw new Error("disclosure deployment context mismatch");if(G(r.outputCommitment,"commitment")!==i.context.outputCommitment)throw new Error("disclosure output commitment mismatch");if(i.kind==="note"?r.role!=="funds":r.role!=="owner"&&r.role!=="spender")throw new Error("disclosure output role mismatch");let o=i.data;if(i.method==="payload-key"){if(r.role!==o.role||r.ciphertext===void 0)throw new Error("disclosure requires the selected role envelope");let d={...n,outputCommitment:r.outputCommitment,ownerAddress:o.ownerAddress};if(i.kind==="note")return{kind:"note",note:Object.freeze(await Se(o.payloadKey,r.ciphertext,d))};let c=await Ue(o.payloadKey,r.ciphertext,{...d,role:r.role});return{kind:"credit",note:Object.freeze({...await Oe(c.note),...c.note.payload===void 0?{}:{payload:structuredClone(c.note.payload)}})}}if(i.kind==="note"){let d={...n,ownerAddress:o.ownerAddress,amount:BigInt(o.amount),nonce:BigInt(o.nonce)};if(await Z(d)!==i.context.outputCommitment)throw new Error("disclosure opening commitment mismatch");return{kind:"note",note:Object.freeze(d)}}let a={...n,spenderWalletIdentity:o.spenderWalletIdentity,ownerWalletIdentity:o.ownerWalletIdentity,grantId:W(o.grantId),nonce:BigInt(o.nonce),expiry:BigInt(o.expiry),...q(Object.fromEntries(["singleLimit","dailyLimit","monthlyLimit"].map(d=>[d,BigInt(o[d])]))),...V(Object.fromEntries(["lastDay","dailySpent","lastMonth","monthlySpent","totalSpent"].map(d=>[d,BigInt(o[d])]))),availableCredit:BigInt(o.availableCredit),unlimited:o.unlimited==="1",creditSharedKeyHash:o.creditSharedKeyHash};if(await Z(a)!==i.context.outputCommitment)throw new Error("disclosure opening commitment mismatch");return{kind:"credit",note:Object.freeze(a)}}toJSON(){return{capability:"disclosure",...this.getScope()}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}};import{secp256k1 as Gt}from"@noble/curves/secp256k1";import{bytesToHex as Ve,hexToBytes as Zt}from"@noble/hashes/utils";import{secp256k1 as M}from"@noble/curves/secp256k1";import{keccak_256 as R}from"@noble/hashes/sha3";import{bytesToHex as Yt,concatBytes as Q,hexToBytes as _e,utf8ToBytes as je}from"@noble/hashes/utils";import{secp256k1 as ye}from"@noble/curves/secp256k1";import{hkdf as pe}from"@noble/hashes/hkdf";import{sha256 as ue}from"@noble/hashes/sha256";import{keccak_256 as Be}from"@noble/hashes/sha3";import{bytesToHex as Te,concatBytes as Ft,hexToBytes as Me,utf8ToBytes as T}from"@noble/hashes/utils";function $e(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{40}$/.test(e))throw new Error("expected a nonzero EVM owner address");return de(e).ownerAddress}s($e,"normalizeOwnerAddress");function me(e){return`0x${Te(Be(e.subarray(1)).subarray(12))}`}s(me,"ownerAddressFromUncompressedPublicKey");function fe(e){return T(`Invisi Privacy Receiving Keys v1
2
+ Account: ${$e(e)}
3
+ Purpose: derive viewing and detection keys only.`)}s(fe,"buildReceivingKeyMessage");function qt(e){let t=fe(e),r=T(`Ethereum Signed Message:
4
+ ${t.length}`);return Be(Ft(r,t))}s(qt,"receivingKeyDigest");function Vt(e,t,r){if(typeof r!="string"?!(r instanceof Uint8Array)||r.length!==64&&r.length!==65:!/^0x(?:[0-9a-fA-F]{128}|[0-9a-fA-F]{130})$/.test(r))throw new Error("invalid receiving signature encoding");let n=typeof r=="string"?Me(r.slice(2)):Uint8Array.from(r);try{let i;if(n.length===64)i=n[32]>>>7,n[32]=n[32]&127;else{let d=n[64];if(i=d>=27?d-27:d,i!==0&&i!==1)throw new Error("invalid receiving signature recovery bit")}let o,a;try{let d=ye.Signature.fromCompact(n.subarray(0,64));if(o=d.normalizeS().addRecoveryBit(i^Number(d.hasHighS())),a=o.recoverPublicKey(t).toRawBytes(!1),!ye.verify(o,t,a,{lowS:!0,prehash:!1}))throw new Error("signature verification failed")}catch{throw new Error("invalid receiving signature")}if(me(a)!==e)throw new Error("receiving signature owner mismatch");return o.toCompactRawBytes()}finally{n.fill(0)}}s(Vt,"normalizeReceivingSignature");function Jt(e,t){return pe(ue,t,T("Invisi.ReceivingRoot.v1"),Me(e.slice(2)),32)}s(Jt,"deriveReceivingRoot");function ze(e,t,r,n=!1){let i=T(t);for(let o=0;o<=4294967295;o++){let a=Uint8Array.of(o>>>24,o>>>16,o>>>8,o),d=pe(ue,e,i,a,32);n&&(d[31]=d[31]&7);let c=n?Ee(d):BigInt(`0x${Te(d)}`);if(c>0n&&c<r)return d;d.fill(0)}throw new Error("scalar derivation exhausted")}s(ze,"deriveScalar");function we(e,t){let r=$e(e),n=Vt(r,qt(r),t),i,o,a,d=!1;try{i=Jt(r,n),o=ze(i,"Invisi.WalletViewingKey.v1",ye.CURVE.n),a=pe(ue,i,T("Invisi.WalletDetectionSeed.v1"),new Uint8Array,32);let c=ze(a,"Invisi.WalletDetectionKey.v1",We,!0);return d=!0,{ownerAddress:r,viewingPrivateKey:o,detectionSeed:a,detectionKey:c}}finally{n.fill(0),i?.fill(0),d||(o?.fill(0),a?.fill(0))}}s(we,"deriveReceivingSecrets");var He={transact:"Transact","create-credit":"CreateCredit","create-credit-initial-payment":"CreateCreditInitialPayment","credit-draw":"CreditDraw","update-credit":"UpdateCredit"},Le={WalletAuthorization:[{name:"operation",type:"bytes32"},{name:"statementHash",type:"bytes32"}]},ee=s(e=>`0x${Yt(e)}`,"hex");function w(e,t){if(typeof e=="string"&&!/^0x(?:[0-9a-fA-F]{2})*$/.test(e))throw new Error("invalid hexadecimal bytes");if(typeof e!="string"&&!(e instanceof Uint8Array))throw new TypeError("expected bytes");let r=typeof e=="string"?_e(e.slice(2)):Uint8Array.from(e);if(t!==void 0&&r.length!==t)throw new Error(`expected ${t} bytes`);return r}s(w,"bytes");function P(e){if(e<0n||e>=1n<<256n)throw new RangeError("value exceeds uint256");return _e(e.toString(16).padStart(64,"0"))}s(P,"word");async function b(e){let t=M.ProjectivePoint.fromHex(w(e));return t.assertValidity(),me(t.toRawBytes(!1))}s(b,"computeOwnerAddress");function Fe(e){let{context:t,operation:r,capacity:n,words:i}=e;if(!Object.hasOwn(He,r))throw new Error("unsupported wallet operation");if(!(r==="transact"?[1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190]:r==="credit-draw"?[1,2,3,4,5,10,20,30,40,50,60,70,80]:[1]).includes(n))throw new Error("invalid operation capacity");if(!Array.isArray(i)||i.length<2)throw new Error("public words required");for(let y of i)if(typeof y!="bigint"||y<0n||y>=C)throw new RangeError("noncanonical public field");if(r!=="transact"){let y=r==="create-credit"?11:r==="update-credit"?14:r==="credit-draw"?15+9*n:15;if(i.length!==y)throw new Error("invalid Credit statement width");let m=r==="update-credit"?8:r==="credit-draw"?6+5*n:4,l=r==="credit-draw"?n:1,g=r==="credit-draw"?Number(i[3]):1;if(!Number.isSafeInteger(g)||g<=0||g>l)throw new Error("invalid grant count");for(let h=0;h<l;h++)if(h<g)W(i[m+h]);else if(i[m+h]!==0n)throw new Error("grantId padding must be zero")}let{chainId:a,protocolAddress:d}=t;if(typeof a!="bigint"||a<0n||a>=1n<<64n)throw new RangeError("invalid chain id");if(typeof d!="bigint"||d<=0n||d>=1n<<160n)throw new RangeError("invalid protocol address");if(i[0]!==a)throw new Error("statement chain mismatch");if(i[1]!==d)throw new Error("statement instance mismatch");let c=Q(P(BigInt(n)),P(64n),P(BigInt(i.length)),...i.map(P));return{domain:{name:"InvisibleProtocol",version:"1",chainId:a,verifyingContract:`0x${d.toString(16).padStart(40,"0")}`},types:Le,primaryType:"WalletAuthorization",message:{operation:ee(R(je(`Invisi.${He[r]}.${r==="transact"?"v1":"GrantId.Uint128.v1"}`))),statementHash:ee(R(c))}}}s(Fe,"walletAuthorizationTypedData");function A(e){let t=Fe(e),r=s(o=>R(je(o)),"hashText"),n=R(Q(r("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),r(t.domain.name),r(t.domain.version),P(t.domain.chainId),P(BigInt(t.domain.verifyingContract)))),i=R(Q(r("WalletAuthorization(bytes32 operation,bytes32 statementHash)"),w(t.message.operation),w(t.message.statementHash)));return ee(R(Q(new Uint8Array([25,1]),n,i)))}s(A,"computeWalletAuthorizationDigest");function Xt(e,t){return ee(M.sign(w(A(t)),w(e,32),{lowS:!0}).toCompactRawBytes())}s(Xt,"signWalletAuthorization");async function he(e,t,r,n){let i=w(r,64),o=w(A(n));return await b(t)!==e?!1:M.verify(i,o,w(t),{lowS:!0})}s(he,"verifyWalletAuthorization");async function qe(e,t){let r=M.ProjectivePoint.fromHex(w(e.spendingPublicKey)).toRawBytes(!1),n=w(e.spendingPrivateKey,32),i=e.ownerAddress,o={...t,context:{...t.context},words:[...t.words]};try{if(!M.getPublicKey(n,!1).every((d,c)=>d===r[c]))throw new Error("spending key pair mismatch");if(BigInt(await b(r))!==BigInt(i))throw new Error("owner address mismatch");return{public_key_x:Array.from(r.slice(1,33)),public_key_y:Array.from(r.slice(33)),signature:Array.from(w(Xt(n,o),64))}}finally{n.fill(0)}}s(qe,"buildWalletAuthorizationWitness");var Je=s(e=>({public_key_x:[...e.public_key_x],public_key_y:[...e.public_key_y],signature:[...e.signature]}),"copyWitness"),j=Symbol.for("nodejs.util.inspect.custom");function Xe(e){if(typeof e=="string"&&!/^0x(?:[0-9a-fA-F]{2})+$/.test(e))throw new Error("invalid hexadecimal bytes");return typeof e=="string"?Zt(e.slice(2)):Uint8Array.from(e)}s(Xe,"copyBytes");function te(e){return u.fromIdentity(e).ownerAddress}s(te,"identity");var $=class{static{s(this,"ViewingCapability")}#e;ownerAddress;constructor(t,r,n){this.ownerAddress=te(t),this.#e=Xe(r);let i=Y(this.#e);if(n&&Ve(i)!==Ve(n))throw new Error("viewing key pair mismatch");Object.freeze(this)}decryptNote(t,r){return N(this.#e,t,{...r,ownerAddress:this.ownerAddress})}decryptCredit(t,r){return O(this.#e,t,{...r,ownerAddress:this.ownerAddress})}getPublicKey(){return Y(this.#e)}discloseNote(t,r){return K.fromEncryptedNote(this.#e,t,{...r,ownerAddress:this.ownerAddress})}discloseCredit(t,r){return K.fromEncryptedCredit(this.#e,t,{...r,ownerAddress:this.ownerAddress})}exportKey(){return Uint8Array.from(this.#e)}toJSON(){return{capability:"viewing",ownerAddress:this.ownerAddress}}[j](){return this.toJSON()}},H=class{static{s(this,"Detector")}#e;#t;constructor(t){this.#e=Uint8Array.from(t),this.#t=F(this.#e),Object.freeze(this)}getClueKey(){return Uint8Array.from(this.#t)}detectClue(t){return De(this.#e,t)}exportKey(){return Uint8Array.from(this.#e)}toJSON(){return{capability:"detection"}}[j](){return this.toJSON()}},_=class e{static{s(this,"NullifierCapability")}ownerAddress;constructor(t){this.ownerAddress=te(t),Object.freeze(this)}static fromIdentity(t){return new e(t)}compute(t,r,n,i){return oe(t,r,i,n)}toJSON(){return{capability:"nullifier",ownerAddress:this.ownerAddress}}[j](){return this.toJSON()}},I=class{static{s(this,"AuthorizedStatement")}#e;digest;ownerAddress;constructor(t,r,n){this.ownerAddress=t,this.digest=r,this.#e=Je(n),Object.freeze(this)}withWitness(t){return t(Je(this.#e))}toJSON(){return{ownerAddress:this.ownerAddress,digest:this.digest}}[j](){return this.toJSON()}},Ye=class e{static{s(this,"WalletAuthorization")}#e;#t;ownerAddress;constructor(t,r,n){this.ownerAddress=t,this.#e=r,this.#t=n,Object.freeze(this)}static async fromMaterial(t,r){let n=Xe(r),i=Gt.getPublicKey(n,!1);if(await b(i)!==te(t))throw new Error("owner address mismatch");return new e(te(t),n,i)}getPublicKey(){return Uint8Array.from(this.#t)}async authorize(t){let r={...t,context:{...t.context},words:[...t.words]},n=A(r),i=await qe({ownerAddress:this.ownerAddress,spendingPrivateKey:this.#e,spendingPublicKey:this.#t},r);return new I(this.ownerAddress,n,i)}toJSON(){return{capability:"wallet-authorization",ownerAddress:this.ownerAddress}}[j](){return this.toJSON()}};var L=class{static{s(this,"WalletAddress")}#e;#t;constructor(t){this.#t=t.getReceivingKeys(),this.#e=t.ownerAddress}get ownerAddress(){return this.#e}get viewingPublicKey(){return this.#t.viewingPublicKey.slice()}get clueKey(){return this.#t.clueKey.slice()}getAddress(){return ke({ownerAddress:this.#e,...this.#t})}getReceivingAddress(){return u.from({ownerAddress:this.#e,...this.#t})}exportNullifier(){return _.fromIdentity(this.ownerAddress)}toJSON(){return{ownerAddress:this.ownerAddress,address:this.getAddress()}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}},S=class e extends L{static{s(this,"Wallet")}constructor(t){super(t),Object.freeze(this)}static fromAddress(t){if(typeof t!="string"&&!(t instanceof u))throw new TypeError("expected a validated receiving address");return new e(typeof t=="string"?u.parse(t):t)}};var ge=class extends L{static{s(this,"ReceivingKeyMaterial")}#e;#t;constructor(t,r){super(u.from({ownerAddress:t.ownerAddress,viewingPublicKey:t.getPublicKey(),clueKey:r.getClueKey()})),this.#e=t,this.#t=r,Object.freeze(this)}getViewer(){return this.#e}getDetector(){return this.#t}};function Qt({ownerAddress:e,signature:t}){let r=we(e,t);try{return new ge(new $(r.ownerAddress,r.viewingPrivateKey),new H(r.detectionKey))}finally{r.viewingPrivateKey.fill(0),r.detectionSeed.fill(0),r.detectionKey.fill(0)}}s(Qt,"deriveReceivingKeysFromSignature");var er=256;function Ae(e){if(e===void 0)return new Uint8Array;let t;if(typeof e=="string"){for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=e.charCodeAt(++r);if(!(i>=56320&&i<=57343))throw new Error("memo contains an invalid surrogate")}else if(n>=56320&&n<=57343)throw new Error("memo contains an invalid surrogate")}t=new TextEncoder().encode(e)}else if(e instanceof Uint8Array)t=Uint8Array.from(e);else throw new TypeError("memo must be text or Uint8Array");if(t.length>256)throw new RangeError("memo exceeds 256 bytes");return t}s(Ae,"encodeMemo");function tr(e){return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e)}s(tr,"decodeMemoText");import{TypedDataEncoder as rr}from"ethers/hash";function nr(e){let t=Object.fromEntries(Object.entries(e.types).map(([n,i])=>[n,[...i]])),r=rr.getPayload(e.domain,t,e.message);if(r.primaryType!==e.primaryType)throw new Error("signing request primary type mismatch");return delete r.types.EIP712Domain,structuredClone(r)}s(nr,"createSigningRequest");function Ge(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("v1 payload data must be an object");for(let r of Object.keys(e))if(r!=="memo")throw new Error(`unsupported v1 payload field ${r}`);let t=Ae(e.memo);return new Uint8Array([1,...t])}s(Ge,"encodeData");function Ze(e){if(!(e instanceof Uint8Array)||e.length<1)throw new Error("payload version required");if(e[0]!==1)throw new Error("unsupported payload version");let t=Uint8Array.from(e.subarray(1));if(t.length>256)throw new Error("invalid memo length");return t.length===0?{}:{memo:t}}s(Ze,"readData");var ir=Object.freeze({encode(e={}){return Ge(e)},decode(e){return Ze(e)}}),or=Object.freeze({encode(e={}){return Ge(e)},decode(e){return Ze(e)}});import{bytesToHex as Qe}from"@noble/hashes/utils";var U=class extends Error{static{s(this,"DeliveryDecryptionError")}constructor(t){super(t instanceof Error?t.message:"delivery decryption failed",{cause:t}),this.name="DeliveryDecryptionError"}};function et(e,t){if(!(e instanceof Uint8Array))throw new Error("invalid decrypted plaintext");if(e.length+78<t.minimum||e.length+78>t.maximum)throw new Error("invalid plaintext length");return e.slice()}s(et,"checkedPlaintext");function xe(e,t,r){let n=u.fromIdentity(e).ownerAddress,i=r?{viewingPublicKey:r.viewingPublicKey.slice(),clueKey:r.clueKey.slice()}:void 0;return{ownerAddress:n,async detectCandidates(o){if(!t.detect)return o.map(()=>"candidate");let a=await t.detect(structuredClone(o));if(!a||BigInt(a.ownerAddress)!==BigInt(n)||!Array.isArray(a.results)||a.results.length!==o.length||a.results.some(d=>!["candidate","not-recipient","unresolved"].includes(d)))throw new U(new Error("invalid detection batch or wrong account"));return[...a.results]},async decryptNote(o,a){a={...a};try{let d=E(o,"funds"),c={...a,ownerAddress:n},y=await t.decryptNote(d.slice(),{...c});if(y===null)return null;if(!(y instanceof Uint8Array))throw y?.status==="authentication-failed"?new D:new Error("invalid decryption result");let m=J(d[0]);if(m.kind!=="funds")throw new Error("unexpected envelope kind");let l=m.decode(et(y,m),c);if(BigInt(l.ownerAddress)!==BigInt(n)||l.tokenAddress!==a.tokenAddress)throw new Error("decrypted note context mismatch");return await Re(c,l),l}catch(d){throw d instanceof D?d:new U(d)}},async decryptCredit(o,a){a={...a};try{let d=E(o,"credit"),c={...a,ownerAddress:n},y=await t.decryptCredit(d.slice(),{...c});if(y===null)return null;if(!(y instanceof Uint8Array))throw y?.status==="authentication-failed"?new D:new Error("invalid decryption result");let m=J(d[0]);if(m.kind!=="credit")throw new Error("unexpected envelope kind");let l=m.decode(et(y,m),c),g=a.role==="owner"?l.note.ownerWalletIdentity:l.note.spenderWalletIdentity;if(BigInt(g)!==BigInt(n)||l.note.tokenAddress!==a.tokenAddress)throw new Error("decrypted credit context mismatch");if(i){let h=a.role==="owner"?l.ownerReceivingKeys:l.spenderReceivingKeys;if(Qe(h.viewingPublicKey)!==Qe(i.viewingPublicKey))throw new Error("decrypted credit receiving key mismatch")}return await Pe(c,l.note),l}catch(d){throw d instanceof D?d:new U(d)}}}}s(xe,"authenticatedDecryptor");import{bytesToHex as sr,hexToBytes as ar}from"@noble/hashes/utils";var tt=s(e=>`0x${sr(e)}`,"walletHex");function p(e,t){if(typeof e!="string"||!/^0x(?:[0-9a-f]{2})*$/.test(e))throw new Error("invalid canonical hex bytes");let r=ar(e.slice(2));if(t!==void 0&&r.length!==t)throw new Error("invalid byte length");return r}s(p,"walletBytes");function k(e){if(typeof e!="string"||!/^(0|[1-9][0-9]*)$/.test(e)||e.length>78)throw new Error("invalid canonical integer");return BigInt(e)}s(k,"walletInteger");function rt(e){return{...e,words:e.words.map(k),context:{chainId:k(e.context.chainId),protocolAddress:k(e.context.protocolAddress)}}}s(rt,"walletAuthorizationParams");function nt(e){let t=e.params.context;return{chainId:k(t.chainId),protocolAddress:k(t.protocolAddress),tokenAddress:k(t.tokenAddress),outputCommitment:t.outputCommitment,ownerAddress:e.ownerAddress,...t.role?{role:t.role}:{}}}s(nt,"walletDecryptionContext");function it(e){return e&&typeof e=="object"&&(Object.values(e).forEach(it),Object.freeze(e)),e}s(it,"freeze");function f(e,t){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(r=>!t.includes(r))||t.some(r=>!Object.hasOwn(e,r)))throw new Error("unexpected wallet fields")}s(f,"exactKeys");function ve(e){if(f(e,["version","id","ownerAddress","method","params"]),e.version!==1||typeof e.id!="string"||!/^[\x21-\x7e]{1,128}$/.test(e.id))throw new Error("invalid wallet request envelope");switch(p(e.ownerAddress,20),u.fromIdentity(e.ownerAddress),e.method){case"wallet.public":f(e.params,[]);break;case"wallet.detect":{f(e.params,["clues"]);let{clues:t}=e.params;if(!Array.isArray(t)||t.length>1024)throw new Error("invalid clues");t.forEach(r=>p(r,68));break}case"wallet.authorize":{f(e.params,["operation","capacity","words","context"]);let t=e.params;if(f(t.context,["chainId","protocolAddress"]),!Array.isArray(t.words)||t.words.length>8192)throw new Error("invalid authorization words");A(rt(t));break}case"wallet.decryptNote":case"wallet.decryptCredit":{let t=e;f(t.params,["envelope","context"]),f(t.params.context,["chainId","protocolAddress","tokenAddress","outputCommitment",...e.method==="wallet.decryptCredit"?["role"]:[]]);let r=nt(t);if(p(r.outputCommitment,32),Ke(r,r.tokenAddress),e.method==="wallet.decryptCredit"&&r.role!=="owner"&&r.role!=="spender")throw new Error("invalid credit role");if(e.method==="wallet.decryptNote"&&r.role!==void 0)throw new Error("unexpected note role");p(t.params.envelope),E(t.params.envelope,e.method==="wallet.decryptCredit"?"credit":"funds");break}default:throw new Error("unsupported wallet method")}}s(ve,"validateWalletRequest");var be=new WeakMap;function dr(e,t,r,n){if(!(e instanceof S)&&typeof e!="string")throw new TypeError("ownerAddress or public Wallet required");let i=u.fromIdentity(typeof e=="string"?e:e.ownerAddress).ownerAddress,o=structuredClone({version:1,id:t,ownerAddress:i,method:r,params:n});ve(o);let a=it({request:o});return be.set(a,e instanceof S?{ownerAddress:i,viewingPublicKey:e.viewingPublicKey,clueKey:e.clueKey}:{ownerAddress:i}),a}s(dr,"prepareWalletRequest");async function ot(e,t){return lr(e,t)}s(ot,"acceptWalletResponse");async function lr(e,t){let r=be.get(e);if(!r)throw new Error("wallet request was not prepared by this SDK instance");let n=e.request;ve(n);let i=structuredClone(t);if(i.version!==n.version||i.id!==n.id||i.ownerAddress!==n.ownerAddress||i.method!==n.method)throw new Error("wallet response envelope mismatch");if(Ce([n],[i]),"error"in i)throw new re(i.error.code);let o=i.result;if(f(o,n.method==="wallet.public"?["viewingPublicKey","spendingPublicKey","clueKey"]:n.method==="wallet.authorize"?["spendingPublicKey","signature","digest"]:n.method==="wallet.detect"?["matches"]:["plaintext"]),n.method==="wallet.public"){if(p(o.spendingPublicKey,65),p(o.viewingPublicKey,33),p(o.clueKey,32),await b(o.spendingPublicKey)!==n.ownerAddress)throw new Error("wallet public identity mismatch");if(r.viewingPublicKey&&r.clueKey&&(tt(r.viewingPublicKey)!==o.viewingPublicKey||tt(r.clueKey)!==o.clueKey))throw new Error("wallet receiving key mismatch");u.from({ownerAddress:n.ownerAddress,viewingPublicKey:p(o.viewingPublicKey),clueKey:p(o.clueKey)})}else if(n.method==="wallet.authorize"){let a=rt(n.params);if(o.digest!==A(a)||!await he(n.ownerAddress,o.spendingPublicKey,o.signature,a))throw new Error("invalid wallet authorization response");let d=p(o.spendingPublicKey,65);return new I(n.ownerAddress,o.digest,{public_key_x:Array.from(d.slice(1,33)),public_key_y:Array.from(d.slice(33)),signature:Array.from(p(o.signature,64))})}else if(n.method==="wallet.detect"){if(!Array.isArray(o.matches)||o.matches.length!==n.params.clues.length||o.matches.some(a=>typeof a!="boolean"))throw new Error("invalid detection response")}else{let a=n,d=nt(a),c=p(o.plaintext),y=xe(n.ownerAddress,{decryptNote:s(async()=>c,"decryptNote"),decryptCredit:s(async()=>c,"decryptCredit")},r.viewingPublicKey&&r.clueKey?{viewingPublicKey:r.viewingPublicKey,clueKey:r.clueKey}:void 0);return a.method==="wallet.decryptNote"?y.decryptNote(a.params.envelope,d):y.decryptCredit(a.params.envelope,d)}return o}s(lr,"acceptResponse");var re=class extends Error{constructor(r){super(r);this.code=r;this.name="NativeWalletError"}static{s(this,"NativeWalletError")}},st=16*1024*1024;function at(e){let t=JSON.stringify(e);if(typeof t!="string"||new TextEncoder().encode(t).length>st)throw new Error("wallet batch exceeds encoded size limit")}s(at,"boundedJson");function dt(e){if(!Array.isArray(e)||e.length>1024)throw new Error("invalid wallet batch");at(e);let t=new Set;for(let r of e){if(ve(r),t.has(r.id))throw new Error("duplicate wallet request id");if(r.ownerAddress!==e[0].ownerAddress)throw new Error("mixed wallet batch owners");t.add(r.id)}}s(dt,"validateWalletBatch");function Ce(e,t){if(dt(e),!Array.isArray(t)||t.length!==e.length)throw new Error("wallet response batch length mismatch");at(t);let r=new Map(e.map(i=>[i.id,i])),n=new Map;for(let i of t){if(!i||typeof i!="object")throw new Error("invalid wallet response");let o=r.get(i.id);if(!o||n.has(i.id)||i.version!==1||i.method!==o.method||i.ownerAddress!==o.ownerAddress)throw new Error("wallet response envelope mismatch");if(Object.hasOwn(i,"error")){if(f(i,["version","id","ownerAddress","method","error"]),f(i.error,["code"]),typeof i.error?.code!="string"||!/^[A-Z][A-Z0-9_]{0,127}$/.test(i.error.code))throw new Error("invalid native wallet error")}else{if(f(i,["version","id","ownerAddress","method","result"]),!i.result||typeof i.result!="object"||Array.isArray(i.result))throw new Error("invalid wallet result");let a=i.result;if(f(a,o.method==="wallet.public"?["viewingPublicKey","spendingPublicKey","clueKey"]:o.method==="wallet.authorize"?["spendingPublicKey","signature","digest"]:o.method==="wallet.detect"?["matches"]:["plaintext"]),o.method==="wallet.public")p(a.viewingPublicKey,33),p(a.spendingPublicKey,65),p(a.clueKey,32);else if(o.method==="wallet.authorize")p(a.spendingPublicKey,65),p(a.signature,64),p(a.digest,32);else if(o.method==="wallet.detect"){if(!Array.isArray(a.matches)||a.matches.length!==o.params.clues.length||a.matches.some(d=>typeof d!="boolean"))throw new Error("invalid detection response")}else p(a.plaintext)}n.set(i.id,i)}return e.map(i=>n.get(i.id))}s(Ce,"validateWalletResponses");async function cr(e,t){for(let n of e)if(!be.has(n))throw new Error("wallet request was not prepared by this SDK instance");let r=Ce(e.map(n=>n.request),structuredClone(t));return Promise.all(e.map((n,i)=>ot(n,r[i])))}s(cr,"acceptWalletResponses");import{AbiCoder as yr}from"ethers/abi";import{keccak256 as pr}from"ethers/crypto";import{toBeHex as ur}from"ethers/utils";function mr(e){return pr(yr.defaultAbiCoder().encode(["string","bytes32"],["InvisiBroadcasterProvenanceIntentV1",ur(BigInt(e),32)]))}s(mr,"provenanceIntentHash");export{I as AuthorizedStatement,Et as CREDIT_POLICY_FIELDS,Dt as CREDIT_USAGE_FIELDS,ut as D_CNULL,pt as D_CREDIT,mt as D_CREDIT_KEY_HASH,ft as D_CREDIT_RECOVERY,wt as D_CREDIT_STATE_NONCE,lt as D_IDENT,ct as D_NOTE,yt as D_NULL,D as DeliveryAuthenticationError,U as DeliveryDecryptionError,H as Detector,K as Disclosure,C as FIELD_MODULUS,Bt as MAX_CIPHERTEXT_BYTES,er as MAX_MEMO_BYTES,st as MAX_WALLET_BATCH_BYTES,_t as MissingCapabilityError,re as NativeWalletError,_ as NullifierCapability,u as ReceivingAddress,ht as TREE_DEPTH,$ as ViewingCapability,Le as WALLET_AUTHORIZATION_TYPES,S as Wallet,ot as acceptWalletResponse,cr as acceptWalletResponses,Rt as applyCreditDrawUsage,xe as authenticatedDecryptor,fe as buildReceivingKeyMessage,ae as computeCreditCommitment,It as computeCreditNullifier,Ut as computeCreditRecoveryPad,se as computeCreditSharedKeyHash,ie as computeNoteCommitment,ne as computeNoteIdentity,oe as computeNoteNullifier,b as computeOwnerAddress,A as computeWalletAuthorizationDigest,bt as createClue,Ct as createClueFromSeed,nr as createSigningRequest,Kt as creditPeriods,or as creditV1,de as decodeAddress,Mt as decodeDeliveryHeader,tr as decodeMemoText,O as decryptCreditState,N as decryptPrivateTransferNote,J as deliveryCodec,Tt as deliveryHeader,F as deriveClueKey,Nt as deriveCreditState,St as deriveCreditStateNonce,Ot as deriveCreditUpdate,Qt as deriveReceivingKeysFromSignature,Ae as encodeMemo,Ht as encryptCreditState,$t as encryptPrivateTransferNote,ir as fundsV1,Wt as generateCreditGrantId,At as generateCreditSharedKey,gt as generateNonce,zt as normalizeCreditDeliveryState,W as normalizeCreditGrantId,q as normalizeCreditPolicy,Pt as normalizeCreditState,V as normalizeCreditUsage,xt as poseidonHash,dr as prepareWalletRequest,mr as provenanceIntentHash,kt as recoverCreditState,vt as validateClueKey,E as validateDeliveryCiphertext,dt as validateWalletBatch,Ce as validateWalletResponses,he as verifyWalletAuthorization,Y as viewingPublicKey,Fe as walletAuthorizationTypedData};
1366
5
  //# sourceMappingURL=index.js.map