@invisi-labs/sdk 1.1.7 → 1.2.0

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 (118) hide show
  1. package/README.md +5 -0
  2. package/dist/broadcaster-3KTB4JO2.cjs +21 -0
  3. package/dist/broadcaster-3KTB4JO2.cjs.map +1 -0
  4. package/dist/broadcaster-7ZKKSTZQ.js +21 -0
  5. package/dist/broadcaster-preparation-PJ263WBL.cjs +15 -0
  6. package/dist/broadcaster-preparation-PJ263WBL.cjs.map +1 -0
  7. package/dist/broadcaster-preparation-ZQAPZAUG.js +15 -0
  8. package/dist/broadcaster-preparation-ZQAPZAUG.js.map +1 -0
  9. package/dist/{chunk-LOU7AP2B.cjs → chunk-2URICDPW.cjs} +72 -33
  10. package/dist/chunk-2URICDPW.cjs.map +1 -0
  11. package/dist/chunk-3D24ABYR.js +86 -0
  12. package/dist/chunk-3D24ABYR.js.map +1 -0
  13. package/dist/chunk-3KTQQZOW.cjs +71 -0
  14. package/dist/chunk-3KTQQZOW.cjs.map +1 -0
  15. package/dist/chunk-4H4FARQK.js +1582 -0
  16. package/dist/chunk-4H4FARQK.js.map +1 -0
  17. package/dist/chunk-4SDP53YQ.cjs +765 -0
  18. package/dist/chunk-4SDP53YQ.cjs.map +1 -0
  19. package/dist/{chunk-XHKQ2BO2.js → chunk-4VI6LYGH.js} +25 -2
  20. package/dist/chunk-4VI6LYGH.js.map +1 -0
  21. package/dist/chunk-BBSRP4MH.cjs +287 -0
  22. package/dist/chunk-BBSRP4MH.cjs.map +1 -0
  23. package/dist/chunk-DGMVGFKM.js +41 -0
  24. package/dist/chunk-DGMVGFKM.js.map +1 -0
  25. package/dist/chunk-GUD3LAUO.js +765 -0
  26. package/dist/chunk-GUD3LAUO.js.map +1 -0
  27. package/dist/chunk-HCB7RQ3S.cjs +79 -0
  28. package/dist/chunk-HCB7RQ3S.cjs.map +1 -0
  29. package/dist/{chunk-GTPUYPQL.js → chunk-HKGJXQVN.js} +69 -30
  30. package/dist/chunk-HKGJXQVN.js.map +1 -0
  31. package/dist/chunk-HLH5JZD4.js +287 -0
  32. package/dist/chunk-HLH5JZD4.js.map +1 -0
  33. package/dist/chunk-J6TZZVAM.cjs +230 -0
  34. package/dist/chunk-J6TZZVAM.cjs.map +1 -0
  35. package/dist/{chunk-7F7ZZW3L.cjs → chunk-LOR6PYH5.cjs} +25 -2
  36. package/dist/chunk-LOR6PYH5.cjs.map +1 -0
  37. package/dist/chunk-MA2QZEF5.cjs +399 -0
  38. package/dist/chunk-MA2QZEF5.cjs.map +1 -0
  39. package/dist/chunk-MI4IP4ZD.cjs +86 -0
  40. package/dist/chunk-MI4IP4ZD.cjs.map +1 -0
  41. package/dist/chunk-NKYHYIRP.cjs +1582 -0
  42. package/dist/chunk-NKYHYIRP.cjs.map +1 -0
  43. package/dist/chunk-OCZLJKIA.cjs +41 -0
  44. package/dist/chunk-OCZLJKIA.cjs.map +1 -0
  45. package/dist/chunk-R5YAOJKB.js +71 -0
  46. package/dist/chunk-R5YAOJKB.js.map +1 -0
  47. package/dist/chunk-RY4M2CIQ.js +399 -0
  48. package/dist/chunk-RY4M2CIQ.js.map +1 -0
  49. package/dist/chunk-THMD5QO2.js +79 -0
  50. package/dist/chunk-THMD5QO2.js.map +1 -0
  51. package/dist/chunk-ZD2652WH.js +230 -0
  52. package/dist/chunk-ZD2652WH.js.map +1 -0
  53. package/dist/credit.cjs +1 -0
  54. package/dist/credit.cjs.map +1 -0
  55. package/dist/credit.d.cts +12 -0
  56. package/dist/credit.d.ts +12 -0
  57. package/dist/credit.js +1 -0
  58. package/dist/credit.js.map +1 -0
  59. package/dist/ethers.cjs +2 -2
  60. package/dist/ethers.cjs.map +1 -1
  61. package/dist/ethers.d.cts +15 -4
  62. package/dist/ethers.d.ts +15 -4
  63. package/dist/ethers.js +1 -1
  64. package/dist/index-CLhGwLxZ.d.cts +42 -0
  65. package/dist/index-Crp-ZFiM.d.ts +42 -0
  66. package/dist/index.cjs +64 -38
  67. package/dist/index.cjs.map +1 -1
  68. package/dist/index.d.cts +21 -14
  69. package/dist/index.d.ts +21 -14
  70. package/dist/index.js +59 -33
  71. package/dist/index.js.map +1 -1
  72. package/dist/note.cjs +11 -0
  73. package/dist/note.cjs.map +1 -0
  74. package/dist/note.d.cts +29 -0
  75. package/dist/note.d.ts +29 -0
  76. package/dist/note.js +11 -0
  77. package/dist/note.js.map +1 -0
  78. package/dist/{broadcaster-preparation-DMxxZ_1Q.d.cts → operation-bridge-CoECSxfi.d.cts} +130 -245
  79. package/dist/{broadcaster-preparation-DMxxZ_1Q.d.ts → operation-bridge-CoECSxfi.d.ts} +130 -245
  80. package/dist/preparation-HUBTVCZE.js +404 -0
  81. package/dist/preparation-HUBTVCZE.js.map +1 -0
  82. package/dist/preparation-QD3ZSYV5.cjs +404 -0
  83. package/dist/preparation-QD3ZSYV5.cjs.map +1 -0
  84. package/dist/provenance-preparation-43DN2WK7.cjs +16 -0
  85. package/dist/provenance-preparation-43DN2WK7.cjs.map +1 -0
  86. package/dist/provenance-preparation-HEZE4L5H.js +16 -0
  87. package/dist/provenance-preparation-HEZE4L5H.js.map +1 -0
  88. package/dist/provenance.cjs +59 -0
  89. package/dist/provenance.cjs.map +1 -0
  90. package/dist/provenance.d.cts +34 -0
  91. package/dist/provenance.d.ts +34 -0
  92. package/dist/provenance.js +59 -0
  93. package/dist/provenance.js.map +1 -0
  94. package/dist/{receipt-logs-m0-bhaxW.d.ts → receipt-logs-8Msm_HZS.d.ts} +82 -78
  95. package/dist/{receipt-logs-CvC951p7.d.cts → receipt-logs-DWG4In8N.d.cts} +82 -78
  96. package/dist/session-support.cjs +28 -7
  97. package/dist/session-support.cjs.map +1 -1
  98. package/dist/session-support.d.cts +71 -39
  99. package/dist/session-support.d.ts +71 -39
  100. package/dist/session-support.js +58 -37
  101. package/dist/session-support.js.map +1 -1
  102. package/package.json +22 -6
  103. package/dist/broadcaster-preparation-RMWQFYNL.js +0 -11
  104. package/dist/broadcaster-preparation-UGOTO4SX.cjs +0 -11
  105. package/dist/broadcaster-preparation-UGOTO4SX.cjs.map +0 -1
  106. package/dist/chunk-7F7ZZW3L.cjs.map +0 -1
  107. package/dist/chunk-EHP5TBC6.js +0 -3565
  108. package/dist/chunk-EHP5TBC6.js.map +0 -1
  109. package/dist/chunk-GTPUYPQL.js.map +0 -1
  110. package/dist/chunk-ITTGBIG2.js +0 -1877
  111. package/dist/chunk-ITTGBIG2.js.map +0 -1
  112. package/dist/chunk-J2JH6HIG.cjs +0 -1877
  113. package/dist/chunk-J2JH6HIG.cjs.map +0 -1
  114. package/dist/chunk-LOU7AP2B.cjs.map +0 -1
  115. package/dist/chunk-RHNIHI4P.cjs +0 -3565
  116. package/dist/chunk-RHNIHI4P.cjs.map +0 -1
  117. package/dist/chunk-XHKQ2BO2.js.map +0 -1
  118. /package/dist/{broadcaster-preparation-RMWQFYNL.js.map → broadcaster-7ZKKSTZQ.js.map} +0 -0
@@ -0,0 +1,1582 @@
1
+ import {
2
+ TransactionPreparation,
3
+ exportBroadcasterIntent
4
+ } from "./chunk-HLH5JZD4.js";
5
+ import {
6
+ authorizationRequest,
7
+ requiresAuthorization,
8
+ statement
9
+ } from "./chunk-THMD5QO2.js";
10
+ import {
11
+ TransactionOutput
12
+ } from "./chunk-DGMVGFKM.js";
13
+ import {
14
+ bindBroadcasterOperation
15
+ } from "./chunk-R5YAOJKB.js";
16
+ import {
17
+ assertCreditUpdatePlan,
18
+ configureRecipientInfrastructure,
19
+ positiveAmount
20
+ } from "./chunk-RY4M2CIQ.js";
21
+ import {
22
+ prepareWithErrors
23
+ } from "./chunk-GUD3LAUO.js";
24
+ import {
25
+ EthersChainReader,
26
+ EthersFundingVerifier
27
+ } from "./chunk-4VI6LYGH.js";
28
+
29
+ // src/protocol/AddressRegistry.ts
30
+ import { AddressRegistry as Registry } from "@invisi-labs/rpc";
31
+ var AddressRegistry = class extends Registry {
32
+ prepareRegistration(options) {
33
+ return prepareWithErrors("prepareRegistration", async () => {
34
+ if ("provider" in options) {
35
+ const { provider, ...preparation } = options;
36
+ return super.prepareRegistration({
37
+ ...preparation,
38
+ reader: new EthersChainReader(provider)
39
+ });
40
+ }
41
+ return super.prepareRegistration(options);
42
+ });
43
+ }
44
+ };
45
+
46
+ // src/transactions/signing/revocation.ts
47
+ import { createSigningRequest } from "@invisi-labs/primitives";
48
+ import { encodeRevokeCreditTypedData } from "@invisi-labs/protocol";
49
+ import { getAddress, verifyTypedData } from "ethers";
50
+ async function revocationSigningRequest(plan, runtime) {
51
+ const params = plan.credit?.revocation;
52
+ if (!params) throw Error("operation is not a public Credit revocation");
53
+ await runtime.options.protocol.validateDeployment(runtime.reader);
54
+ const block = await runtime.reader.getBlock(await runtime.reader.getLatestBlockNumber());
55
+ if (block.timestamp > params.deadline) throw Error("revocation authorization expired");
56
+ const request = createSigningRequest(
57
+ encodeRevokeCreditTypedData({ ...plan.context, now: block.timestamp }, params)
58
+ );
59
+ if ((await runtime.reader.getBlock(block.number)).hash !== block.hash)
60
+ throw Error("canonical revocation block changed");
61
+ return request;
62
+ }
63
+ async function acceptRevocationSignature(plan, signature, runtime) {
64
+ if (!/^0x(?:[0-9a-fA-F]{2})+$/.test(signature)) throw Error("invalid revocation signature");
65
+ const request = await revocationSigningRequest(plan, runtime), owner = plan.credit.revocation.owner;
66
+ let valid = false;
67
+ try {
68
+ valid = getAddress(
69
+ verifyTypedData(request.domain, request.types, request.message, signature)
70
+ ) === getAddress(owner);
71
+ } catch {
72
+ }
73
+ if (!valid && runtime.options.fundingVerifier)
74
+ valid = await runtime.options.fundingVerifier.verifyTypedData({
75
+ ...request,
76
+ address: owner,
77
+ signature
78
+ });
79
+ if (!valid) throw Error("invalid owner revocation signature");
80
+ return signature;
81
+ }
82
+
83
+ // src/transactions/records.ts
84
+ function creditReservationKey(commitment) {
85
+ return "credit:" + commitment;
86
+ }
87
+
88
+ // src/transactions/preparation/inputs.ts
89
+ function inputFacts(plan) {
90
+ const credit = plan.credit;
91
+ const noteNullifiers = plan.params?.nullifiers ?? [];
92
+ let creditNullifiers = [];
93
+ if (credit?.draw) {
94
+ creditNullifiers = credit.draw.nullifiers;
95
+ } else if (credit?.update) {
96
+ creditNullifiers = [credit.update.nullifier];
97
+ }
98
+ if (noteNullifiers.length !== plan.inputs.length || creditNullifiers.length !== (credit?.inputs.length ?? 0)) {
99
+ throw new Error("operation input statement count mismatch");
100
+ }
101
+ return [
102
+ ...plan.inputs.map((input, index2) => ({
103
+ key: input.commitment,
104
+ reservationKey: input.commitment,
105
+ nullifier: noteNullifiers[index2],
106
+ kind: "notes"
107
+ })),
108
+ ...(credit?.inputs ?? []).map((input, index2) => ({
109
+ key: input.commitment + ":" + input.role,
110
+ reservationKey: creditReservationKey(input.commitment),
111
+ nullifier: creditNullifiers[index2],
112
+ kind: "credits"
113
+ }))
114
+ ];
115
+ }
116
+ function operationSources(plan) {
117
+ const noteSources = plan.params?.sources;
118
+ if (noteSources != null) return noteSources;
119
+ const credit = plan.credit;
120
+ if (credit?.draw) return credit.draw.sources;
121
+ if (credit?.update) return [credit.update.source];
122
+ return [];
123
+ }
124
+
125
+ // src/gas/gas-estimation.ts
126
+ import { getDocumentedGasReference } from "@invisi-labs/protocol";
127
+ import { getDocumentedGasReference as getDocumentedGasReference2 } from "@invisi-labs/protocol";
128
+ function getOperationGasReference(plan, _protocol) {
129
+ let query = { kind: plan.kind };
130
+ const credit = plan.credit;
131
+ if (plan.statement?.target === "noir-recursive")
132
+ return getDocumentedGasReference({ kind: "aggregate" });
133
+ if (credit?.creation)
134
+ query = { kind: "create-credit", scenario: "first-allocation-empty-tree" };
135
+ else if (credit?.update)
136
+ query = { kind: "update-credit", scenario: "after-draw-preserve-usage" };
137
+ else if (credit?.draw)
138
+ query = {
139
+ kind: "draw-credit",
140
+ capacity: plan.capacity,
141
+ creditInputs: credit.inputs.length,
142
+ distinctPayers: credit.draw.payers.length,
143
+ sourceTrees: operationSources(plan).length,
144
+ noteOutputs: 1,
145
+ creditOutputs: credit.outputs.length,
146
+ creditCiphertextBytes: 485,
147
+ noteCiphertextBytes: 160,
148
+ clueBytes: 68,
149
+ scenario: "distinct-payers"
150
+ };
151
+ else if (plan.kind === "transfer")
152
+ query = {
153
+ kind: "transact",
154
+ capacity: plan.capacity,
155
+ noteInputs: plan.inputs.length,
156
+ noteOutputs: plan.outputs.length,
157
+ sourceTrees: operationSources(plan).length,
158
+ noteCiphertextBytes: 160,
159
+ clueBytes: 68,
160
+ scenario: !plan.inputs.length ? "public-funding" : !plan.outputs.length ? "withdrawal" : !(plan.funding.amount ?? 0n) && !(plan.params?.withdrawalAmount ?? 0n) && !(plan.params?.feeAmount ?? 0n) ? "private" : "mixed"
161
+ };
162
+ if (credit) {
163
+ const feeAmount = credit.creation?.feeAmount ?? credit.update?.feeAmount ?? credit.draw?.feeAmount ?? credit.revocation?.feeAmount ?? 0n;
164
+ query = {
165
+ ...query,
166
+ feeEnabled: feeAmount > 0n,
167
+ feeMechanism: feeAmount > 0n ? credit.draw ? "draw-deduction" : "owner-pull" : "none"
168
+ };
169
+ }
170
+ if (plan.outputs.some((o) => (o.delivery.ciphertext.length - 2) / 2 !== 160) || credit?.outputs.some((o) => o.deliveries.some((d) => (d.ciphertext.length - 2) / 2 !== 485)))
171
+ return getDocumentedGasReference({ kind: "unmeasured-delivery-size" });
172
+ return getDocumentedGasReference(query);
173
+ }
174
+
175
+ // src/transactions/proving/proof.ts
176
+ function publicProof(bundle) {
177
+ return {
178
+ formatVersion: bundle.formatVersion,
179
+ circuitName: bundle.circuitName,
180
+ target: bundle.target,
181
+ bbVersion: bundle.bbVersion,
182
+ artifactSha256: bundle.artifactSha256,
183
+ vkSha256: bundle.vkSha256,
184
+ proofHex: bundle.proofHex,
185
+ proofSha256: bundle.proofSha256,
186
+ publicInputs: [...bundle.publicInputs]
187
+ };
188
+ }
189
+
190
+ // src/transactions/proving/proof-integrity.ts
191
+ import { sha256 } from "@noble/hashes/sha256";
192
+ import { bytesToHex } from "@noble/hashes/utils";
193
+ import { getBytes } from "ethers";
194
+ function check(ok, message) {
195
+ if (!ok) throw new Error(message);
196
+ }
197
+ function sameStatement(proof, expected) {
198
+ check(
199
+ proof.formatVersion === 1 && proof.bbVersion === "6.0.0" && proof.circuitName === expected.circuitName && proof.target === expected.target && proof.artifactSha256 === expected.artifactSha256 && proof.vkSha256 === expected.vkSha256,
200
+ "proof release/target mismatch"
201
+ );
202
+ check(
203
+ proof.publicInputs.length === expected.expectedPublicInputs.length && proof.publicInputs.every((word, i) => word === expected.expectedPublicInputs[i]),
204
+ "proof public statement mismatch"
205
+ );
206
+ check(
207
+ /^0x(?:[a-fA-F0-9]{2})+$/.test(proof.proofHex) && bytesToHex(sha256(getBytes(proof.proofHex))) === proof.proofSha256,
208
+ "proof integrity mismatch"
209
+ );
210
+ }
211
+
212
+ // src/transactions/execution/calldata.ts
213
+ import {
214
+ buildRevokeCreditCalldata,
215
+ buildCreateCreditCalldata,
216
+ buildCreditDrawCalldata,
217
+ buildShieldCalldata,
218
+ buildUpdateCreditCalldata,
219
+ buildTransactCalldata
220
+ } from "@invisi-labs/protocol";
221
+ async function encodeOperation(saved) {
222
+ const plan = saved.plan;
223
+ const credit = plan.credit;
224
+ const caller = plan.fundingMode === "caller" ? plan.funding.payer : void 0;
225
+ const common = { context: plan.context, proof: saved.proof?.proofHex ?? "0x" };
226
+ const funded = { ...common, funding: plan.funding, ...caller ? { caller } : {} };
227
+ let encoded;
228
+ if (credit?.update) {
229
+ encoded = buildUpdateCreditCalldata({
230
+ ...funded,
231
+ params: credit.update,
232
+ deliveries: credit.deliveries
233
+ });
234
+ } else if (credit?.creation) {
235
+ encoded = buildCreateCreditCalldata({
236
+ ...funded,
237
+ params: credit.creation,
238
+ deliveries: credit.deliveries
239
+ });
240
+ } else if (credit?.draw) {
241
+ encoded = buildCreditDrawCalldata({
242
+ ...common,
243
+ params: credit.draw,
244
+ deliveries: credit.deliveries
245
+ });
246
+ } else if (credit?.revocation) {
247
+ encoded = buildRevokeCreditCalldata({
248
+ context: plan.context,
249
+ params: credit.revocation,
250
+ signature: credit.revocationSignature ?? "0x",
251
+ ...credit.revocationCaller ? { caller: credit.revocationCaller } : {}
252
+ });
253
+ } else if (plan.kind === "shield") {
254
+ encoded = await buildShieldCalldata({
255
+ ...funded,
256
+ params: plan.shieldParams,
257
+ outputs: plan.shieldOutputs,
258
+ deliveries: plan.outputs.map((output) => output.delivery)
259
+ });
260
+ } else {
261
+ encoded = buildTransactCalldata({
262
+ ...funded,
263
+ params: plan.params,
264
+ deliveries: plan.outputs.map((output) => output.delivery)
265
+ });
266
+ }
267
+ return { to: plan.context.protocolAddress, data: encoded.data, value: 0n };
268
+ }
269
+
270
+ // src/transactions/proving/witness.ts
271
+ import { WitnessBuilder } from "@invisi-labs/prover";
272
+ async function witnessFor(protocol, plan, authorization) {
273
+ const builder = new WitnessBuilder(protocol);
274
+ const credit = plan.credit;
275
+ if (credit) {
276
+ if (!authorization) throw new Error("private Credit wallet authorization required");
277
+ if (credit.update) {
278
+ await assertCreditUpdatePlan(plan);
279
+ if (!credit.updateChanges) throw Error("Credit update adjustment required");
280
+ return builder.updateCredit({
281
+ params: credit.update,
282
+ deliveries: credit.deliveries,
283
+ input: credit.inputs[0],
284
+ state: credit.outputs[0].state,
285
+ changes: credit.updateChanges,
286
+ authorization
287
+ });
288
+ }
289
+ if (credit.creation)
290
+ return builder.createCredit({
291
+ params: credit.creation,
292
+ deliveries: credit.deliveries,
293
+ state: credit.outputs[0].state,
294
+ authorization
295
+ });
296
+ if (credit.draw) {
297
+ return builder.drawCredit({
298
+ timestamp: plan.preparedAt.timestamp,
299
+ params: credit.draw,
300
+ deliveries: credit.deliveries,
301
+ inputs: credit.inputs,
302
+ amounts: credit.amounts,
303
+ output: plan.outputs[0].note,
304
+ authorization
305
+ });
306
+ }
307
+ throw new Error("unsupported Credit operation");
308
+ }
309
+ return builder.transact({
310
+ params: plan.params,
311
+ deliveries: plan.outputs.map((output) => output.delivery),
312
+ funding: plan.funding,
313
+ inputs: plan.inputs,
314
+ outputs: plan.outputs.map((output) => ({
315
+ identity: output.identity,
316
+ amount: output.amount,
317
+ ...output.note ? { note: output.note } : {}
318
+ })),
319
+ ...authorization ? { authorization } : {},
320
+ target: plan.statement.target
321
+ });
322
+ }
323
+
324
+ // src/transactions/signing/funding.ts
325
+ import {
326
+ encodeAggregateFundingTypedData,
327
+ encodeShieldFundingTypedData,
328
+ encodeTransactFundingTypedData
329
+ } from "@invisi-labs/protocol";
330
+ async function fundingTypedData(saved) {
331
+ const plan = saved.plan;
332
+ if (plan.credit) throw Error("Credit operations have no funding authorization");
333
+ if (plan.kind === "shield") {
334
+ return encodeShieldFundingTypedData({
335
+ context: plan.context,
336
+ params: plan.shieldParams,
337
+ outputs: plan.shieldOutputs,
338
+ deliveries: plan.outputs.map((output) => output.delivery),
339
+ funding: plan.funding
340
+ });
341
+ }
342
+ if (plan.statement?.target === "noir-recursive") {
343
+ return encodeAggregateFundingTypedData(plan.context, {
344
+ params: plan.params,
345
+ deliveries: plan.outputs.map((output) => output.delivery),
346
+ funding: plan.funding
347
+ });
348
+ }
349
+ return encodeTransactFundingTypedData(
350
+ plan.context,
351
+ saved.proof.proofHex,
352
+ plan.params,
353
+ plan.outputs.map((output) => output.delivery),
354
+ plan.funding
355
+ );
356
+ }
357
+
358
+ // src/transactions/execution/operation-execution.ts
359
+ import {
360
+ AuthorizedStatement,
361
+ computeOwnerAddress,
362
+ computeWalletAuthorizationDigest,
363
+ createSigningRequest as createSigningRequest2,
364
+ walletAuthorizationTypedData
365
+ } from "@invisi-labs/primitives";
366
+ import { WitnessBuilder as WitnessBuilder2 } from "@invisi-labs/prover";
367
+ import { Signature, SigningKey, concat, getBytes as getBytes2, verifyTypedData as verifyTypedData2 } from "ethers";
368
+ async function proveOperation(protocol, plan, authorization, prover, options) {
369
+ if (Object.hasOwn(options, "target")) {
370
+ throw new Error("prove accepts execution, not a backend target");
371
+ }
372
+ const { execution = "single", ...proverOptions } = options;
373
+ if (execution !== "single" && execution !== "aggregate") {
374
+ throw new Error("execution must be single or aggregate");
375
+ }
376
+ const frozen = statement(plan);
377
+ if (execution === "aggregate" && (plan.kind !== "transfer" || !plan.capacity || plan.capacity > 10)) {
378
+ throw new Error("aggregate execution requires a C1..C10 transfer");
379
+ }
380
+ if (plan.kind === "transfer") {
381
+ plan.statement = WitnessBuilder2.statement(
382
+ frozen.circuitName,
383
+ frozen.expectedPublicInputs,
384
+ execution === "aggregate" ? "noir-recursive" : "evm"
385
+ );
386
+ }
387
+ const request = await witnessFor(protocol, plan, authorization);
388
+ if (JSON.stringify({ ...request, witness: void 0 }) !== JSON.stringify(plan.statement))
389
+ throw new Error("prepared proof statement changed");
390
+ try {
391
+ const proof = publicProof(await prover.prove(request, proverOptions));
392
+ sameStatement(proof, plan.statement);
393
+ if (await prover.verify(
394
+ structuredClone(proof),
395
+ structuredClone(plan.statement),
396
+ proverOptions
397
+ ) !== true)
398
+ throw new Error("proof verification failed");
399
+ return proof;
400
+ } catch {
401
+ options.signal?.throwIfAborted();
402
+ throw new Error("operation proof generation or verification failed");
403
+ }
404
+ }
405
+ async function signOperationFunding(saved, signer, verifier) {
406
+ const payer = saved.plan.funding.payer;
407
+ if (signer.address.toLowerCase() !== payer.toLowerCase())
408
+ throw new Error("funding signer is not the payer");
409
+ const typed = await fundingTypedData(saved);
410
+ const signature = await signer.signTypedData(structuredClone(typed));
411
+ return verifyFundingSignature(typed, payer, signature, verifier);
412
+ }
413
+ function walletSigningRequest(plan) {
414
+ return createSigningRequest2(walletAuthorizationTypedData(authorizationRequest(plan)));
415
+ }
416
+ async function acceptWalletSignature(plan, signature) {
417
+ const request = authorizationRequest(plan);
418
+ const digest = computeWalletAuthorizationDigest(request);
419
+ try {
420
+ const signed = Signature.from(signature);
421
+ const publicKey = getBytes2(SigningKey.recoverPublicKey(digest, signed));
422
+ const owner = await computeOwnerAddress(publicKey);
423
+ if (owner.toLowerCase() !== plan.scope.ownerAddress.toLowerCase()) {
424
+ throw new Error("wallet signature identity mismatch");
425
+ }
426
+ return new AuthorizedStatement(plan.scope.ownerAddress, digest, {
427
+ public_key_x: Array.from(publicKey.slice(1, 33)),
428
+ public_key_y: Array.from(publicKey.slice(33)),
429
+ signature: Array.from(getBytes2(concat([signed.r, signed.s])))
430
+ });
431
+ } catch {
432
+ throw new Error("invalid wallet authorization signature");
433
+ }
434
+ }
435
+ async function fundingSigningRequest(saved, runtime) {
436
+ const plan = saved.plan;
437
+ if (plan.fundingMode !== "signature") {
438
+ throw new Error("operation does not require a funding signature");
439
+ }
440
+ if (plan.kind !== "shield" && !saved.proof) {
441
+ throw new Error("proof must precede funding authorization");
442
+ }
443
+ await runtime.options.protocol.validateDeployment(runtime.reader);
444
+ const block = await runtime.reader.getBlock(await runtime.reader.getLatestBlockNumber());
445
+ if (block.timestamp > plan.deadline || block.timestamp > (plan.funding.deadline ?? 0n)) {
446
+ throw new Error("funding authorization expired");
447
+ }
448
+ if (await runtime.reader.getFundingNonce(plan.context, plan.funding.payer, block) !== plan.funding.sigNonce) {
449
+ throw new Error("funding nonce changed; prepare again");
450
+ }
451
+ const request = createSigningRequest2(await fundingTypedData(saved));
452
+ if ((await runtime.reader.getBlock(block.number)).hash !== block.hash) {
453
+ throw new Error("canonical funding block changed");
454
+ }
455
+ return request;
456
+ }
457
+ async function acceptFundingSignature(saved, signature, runtime) {
458
+ if (!/^0x(?:[a-fA-F0-9]{2})+$/.test(signature)) {
459
+ throw new Error("invalid EVM funding signature");
460
+ }
461
+ const request = await fundingSigningRequest(saved, runtime);
462
+ return verifyFundingSignature(
463
+ request,
464
+ saved.plan.funding.payer,
465
+ signature,
466
+ runtime.options.fundingVerifier
467
+ );
468
+ }
469
+ async function verifyFundingSignature(request, payer, signature, verifier) {
470
+ if (!/^0x(?:[a-fA-F0-9]{2})+$/.test(signature)) {
471
+ throw new Error("invalid EVM funding signature");
472
+ }
473
+ const types = Object.fromEntries(
474
+ Object.entries(request.types).map(([name, fields]) => [name, [...fields]])
475
+ );
476
+ let validEOA = false;
477
+ try {
478
+ validEOA = verifyTypedData2(request.domain, types, request.message, signature).toLowerCase() === payer.toLowerCase();
479
+ if (validEOA) {
480
+ signature = Signature.from(signature).serialized;
481
+ }
482
+ } catch {
483
+ validEOA = false;
484
+ }
485
+ const valid = verifier ? await verifier.verifyTypedData({
486
+ ...structuredClone(request),
487
+ address: payer,
488
+ signature
489
+ }) : validEOA;
490
+ if (valid !== true) {
491
+ throw new Error("invalid EVM funding signature");
492
+ }
493
+ return signature;
494
+ }
495
+
496
+ // src/transactions/execution/operation-preview.ts
497
+ import { normalizeCreditPolicy, normalizeCreditUsage } from "@invisi-labs/primitives";
498
+ import { normalizeFunding } from "@invisi-labs/protocol";
499
+ function operationPreview(plan, status) {
500
+ const p = plan;
501
+ const fee = p.params ?? p.shieldParams ?? p.credit?.creation ?? p.credit?.update ?? p.credit?.draw ?? p.credit?.revocation;
502
+ const funding = normalizeFunding(p.funding);
503
+ return {
504
+ id: p.id,
505
+ kind: p.kind,
506
+ status,
507
+ context: { ...p.context },
508
+ inputs: inputFacts(p).length,
509
+ inputDetails: [
510
+ ...p.inputs.map((input) => ({
511
+ kind: "notes",
512
+ commitment: input.commitment,
513
+ amount: input.note.amount,
514
+ owner: input.note.ownerAddress,
515
+ treeId: input.treeId,
516
+ leafIndex: input.leafIndex
517
+ })),
518
+ ...(p.credit?.inputs ?? []).map((input) => ({
519
+ kind: "credits",
520
+ commitment: input.commitment,
521
+ revocationShard: input.state.note.revocationShard,
522
+ revocationSlot: input.state.note.revocationSlot,
523
+ owner: input.state.note.ownerWalletIdentity,
524
+ spender: input.state.note.spenderWalletIdentity,
525
+ expiry: input.state.note.expiry,
526
+ availableCredit: input.state.note.availableCredit,
527
+ unlimited: input.state.note.unlimited,
528
+ role: input.role,
529
+ treeId: input.treeId,
530
+ leafIndex: input.leafIndex
531
+ }))
532
+ ],
533
+ funding: {
534
+ payer: funding.payer,
535
+ amount: funding.amount,
536
+ authorization: p.fundingMode,
537
+ sigNonce: funding.sigNonce,
538
+ deadline: funding.deadline,
539
+ permit: { deadline: funding.permit.deadline }
540
+ },
541
+ creditOutputs: p.credit?.outputs.map((output) => ({
542
+ commitment: output.commitment,
543
+ revocationShard: output.state.note.revocationShard,
544
+ revocationSlot: output.state.note.revocationSlot,
545
+ expiry: output.state.note.expiry,
546
+ owner: output.state.note.ownerWalletIdentity,
547
+ spender: output.state.note.spenderWalletIdentity,
548
+ ...normalizeCreditPolicy(output.state.note),
549
+ availableCredit: output.state.note.availableCredit,
550
+ unlimited: output.state.note.unlimited,
551
+ ...normalizeCreditUsage(output.state.note)
552
+ })),
553
+ creditUpdate: p.credit?.updateChanges ? structuredClone(p.credit.updateChanges) : void 0,
554
+ creditDraw: p.credit?.draw ? {
555
+ grossAmount: p.credit.draw.totalAmount,
556
+ feeAmount: p.credit.draw.feeAmount ?? 0n,
557
+ netAmount: p.credit.draw.totalAmount - (p.credit.draw.feeAmount ?? 0n),
558
+ payers: p.credit.draw.payers.map((payer) => ({ ...payer }))
559
+ } : void 0,
560
+ creditFeePayer: p.credit?.creation?.owner ?? p.credit?.update?.owner ?? p.credit?.revocation?.owner,
561
+ outputs: p.outputs.map((output) => ({
562
+ commitment: output.commitment,
563
+ to: output.address,
564
+ amount: output.amount,
565
+ change: output.change
566
+ })),
567
+ capacity: p.capacity,
568
+ deadline: p.deadline,
569
+ feeRecipient: fee?.feeRecipient,
570
+ feeAmount: fee?.feeAmount ?? 0n,
571
+ fundingAmount: p.funding.amount ?? 0n,
572
+ fundingPayer: p.funding.payer,
573
+ withdrawalAmount: p.params?.withdrawalAmount ?? 0n,
574
+ withdrawalAddress: p.params?.withdrawalAddress,
575
+ permissions: {
576
+ walletAuthorization: requiresAuthorization(p),
577
+ proof: p.kind !== "shield" && p.kind !== "revoke-credit",
578
+ fundingAuthorization: p.fundingMode === "signature"
579
+ }
580
+ };
581
+ }
582
+
583
+ // src/transactions/execution/PreparedTransaction.ts
584
+ import {
585
+ Wallet,
586
+ prepareWalletRequest,
587
+ acceptWalletResponse
588
+ } from "@invisi-labs/primitives";
589
+ import { MissingCapabilityError } from "@invisi-labs/primitives";
590
+ import { normalizeFunding as normalizeFunding2 } from "@invisi-labs/protocol";
591
+ function check2(ok, message) {
592
+ if (!ok) throw new Error(message);
593
+ }
594
+ var PreparedTransaction = class _PreparedTransaction {
595
+ #runtime;
596
+ #saved;
597
+ #authorization;
598
+ #walletRequests = /* @__PURE__ */ new Map();
599
+ #lifecycle;
600
+ status;
601
+ constructor(runtime, saved, status, lifecycle, authorization) {
602
+ this.#runtime = runtime;
603
+ this.#saved = structuredClone(saved);
604
+ this.#lifecycle = lifecycle;
605
+ this.#authorization = authorization;
606
+ this.status = status;
607
+ bindBroadcasterOperation(this, {
608
+ quote: (client, options) => this.#quoteForBroadcaster(client, options),
609
+ submit: (client) => this.#submitViaBroadcaster(client),
610
+ provenanceContext: async () => {
611
+ this.current();
612
+ return {
613
+ chainId: this.#saved.plan.context.chainId,
614
+ protocolAddress: this.#saved.plan.context.protocolAddress
615
+ };
616
+ },
617
+ readProvenance: async () => {
618
+ this.current();
619
+ return structuredClone(this.#saved.provenance);
620
+ },
621
+ proveProvenance: (capability, reprove) => this.#proveProvenance(capability, reprove)
622
+ });
623
+ Object.freeze(this);
624
+ }
625
+ static prepare(runtime, plan) {
626
+ return new _PreparedTransaction(
627
+ runtime,
628
+ { plan: structuredClone(plan), generation: 0 },
629
+ "prepared",
630
+ { generation: 0, busy: false }
631
+ );
632
+ }
633
+ broadcasterQuote() {
634
+ return this.#saved.broadcasterQuote ? structuredClone(this.#saved.broadcasterQuote) : void 0;
635
+ }
636
+ async #quoteForBroadcaster(client, options) {
637
+ this.current();
638
+ check2(
639
+ this.status === "prepared" && this.#runtime.reprepare,
640
+ "broadcaster must attach to an unsigned prepared transaction"
641
+ );
642
+ const { prepareBroadcasterPlan } = await import("./broadcaster-preparation-ZQAPZAUG.js");
643
+ const selected = await prepareBroadcasterPlan(
644
+ this.#saved.plan,
645
+ this.#runtime.reprepare,
646
+ client,
647
+ options
648
+ );
649
+ return new _PreparedTransaction(
650
+ this.#runtime,
651
+ {
652
+ plan: selected.plan,
653
+ broadcasterQuote: selected.quote,
654
+ broadcasterBinding: selected.broadcasterBinding,
655
+ generation: 0
656
+ },
657
+ "prepared",
658
+ { generation: 0, busy: false }
659
+ );
660
+ }
661
+ async #proveProvenance(capability, reprove = false) {
662
+ this.current();
663
+ check2(this.status === "ready", "Ready transaction required for Provenance");
664
+ const { provePreparedProvenance } = await import("./provenance-preparation-HEZE4L5H.js");
665
+ this.#lifecycle.busy = true;
666
+ try {
667
+ const packet = await provePreparedProvenance(
668
+ this.#saved,
669
+ this.#runtime,
670
+ capability,
671
+ reprove
672
+ );
673
+ if (!this.#saved.broadcasterAttempted) this.#saved.provenance = structuredClone(packet);
674
+ return packet;
675
+ } finally {
676
+ this.#lifecycle.busy = false;
677
+ }
678
+ }
679
+ async #submitViaBroadcaster(client) {
680
+ this.current();
681
+ check2(this.status === "ready", "transaction is not ready");
682
+ const { validateBroadcastEnvelope, validatePreparedBroadcast } = await import("./provenance-preparation-HEZE4L5H.js");
683
+ validateBroadcastEnvelope(this.#saved, client);
684
+ if (this.#saved.broadcasterSubmissionId) {
685
+ try {
686
+ return await client.status(this.#saved.broadcasterSubmissionId);
687
+ } catch (error) {
688
+ const { BroadcasterRpcError } = await import("./broadcaster-7ZKKSTZQ.js");
689
+ if (!(error instanceof BroadcasterRpcError) || error.code !== -32001) throw error;
690
+ }
691
+ }
692
+ if (!this.#saved.broadcasterAttempted) {
693
+ const requirements = await client.submissionRequirements(this.#saved.broadcasterQuote);
694
+ if (requirements.provenanceRequired && this.#saved.plan.inputs.length && !this.#saved.provenance)
695
+ await this.#proveProvenance();
696
+ await validatePreparedBroadcast(this.#saved, client, this.#runtime);
697
+ }
698
+ this.#saved.externalized = true;
699
+ this.#saved.broadcasterAttempted = true;
700
+ const result = await client.submitTransaction(
701
+ this.#saved.call.data,
702
+ this.#saved.broadcasterQuote,
703
+ structuredClone(this.#saved.provenance?.sidecars ?? [])
704
+ );
705
+ check2(
706
+ !this.#saved.broadcasterSubmissionId || this.#saved.broadcasterSubmissionId === result.id,
707
+ "broadcaster changed submission ID"
708
+ );
709
+ this.#saved.broadcasterSubmissionId = result.id;
710
+ return result;
711
+ }
712
+ get id() {
713
+ return this.#saved.plan.id;
714
+ }
715
+ get kind() {
716
+ return this.#saved.plan.kind;
717
+ }
718
+ async estimateGas(options = {}) {
719
+ const provider = this.#runtime.options.provider;
720
+ if (!provider)
721
+ throw new MissingCapabilityError("ethers provider for final eth_estimateGas");
722
+ const call = await this.exportTransaction();
723
+ return {
724
+ source: "rpc",
725
+ gasUnits: await provider.estimateGas({ ...call, ...options })
726
+ };
727
+ }
728
+ getGasReference() {
729
+ return getOperationGasReference(this.#saved.plan, this.#runtime.options.protocol);
730
+ }
731
+ /** Final Note outputs, including change; Credit outputs are not exported as IPN. */
732
+ getOutputs() {
733
+ return Object.freeze(
734
+ this.#saved.plan.outputs.map((output) => new TransactionOutput(output))
735
+ );
736
+ }
737
+ preview() {
738
+ return operationPreview(this.#saved.plan, this.status);
739
+ }
740
+ /** Obtain a firm quote before signing. This intent contains no private inputs or witness. */
741
+ async exportBroadcasterIntent() {
742
+ this.current();
743
+ check2(
744
+ ["prepared", "authorized"].includes(this.status),
745
+ "quote intent requires a prepared transaction"
746
+ );
747
+ return exportBroadcasterIntent(this.#saved.plan);
748
+ }
749
+ current() {
750
+ check2(
751
+ !this.#lifecycle.busy && this.#lifecycle.generation === this.#saved.generation,
752
+ "stale transaction handle or active worker"
753
+ );
754
+ }
755
+ async stage(stage, allowed, work, signal) {
756
+ signal?.throwIfAborted();
757
+ this.current();
758
+ check2(allowed.includes(this.status), `invalid transaction stage for ${stage}`);
759
+ this.#lifecycle.busy = true;
760
+ const saved = structuredClone(this.#saved);
761
+ try {
762
+ const next = await work(saved);
763
+ signal?.throwIfAborted();
764
+ saved.generation++;
765
+ this.#lifecycle.generation = saved.generation;
766
+ return new _PreparedTransaction(
767
+ this.#runtime,
768
+ saved,
769
+ next.status,
770
+ this.#lifecycle,
771
+ next.authorization ?? this.#authorization
772
+ );
773
+ } finally {
774
+ this.#lifecycle.busy = false;
775
+ }
776
+ }
777
+ async exportRevocationAuthorization() {
778
+ this.current();
779
+ check2(this.status === "prepared", "revocation is not awaiting authorization");
780
+ return revocationSigningRequest(this.#saved.plan, this.#runtime);
781
+ }
782
+ async withRevocationSignature(signature) {
783
+ this.current();
784
+ const verified = await acceptRevocationSignature(
785
+ this.#saved.plan,
786
+ signature,
787
+ this.#runtime
788
+ );
789
+ return this.stage("revocation authorization", ["prepared"], async (saved) => {
790
+ saved.plan.credit.revocationSignature = verified;
791
+ saved.call = await this.encode(saved);
792
+ return { status: "ready" };
793
+ });
794
+ }
795
+ /** Export the same portable request used by managed native wallet transports. */
796
+ async exportWalletRequest(id, options = {}) {
797
+ options.signal?.throwIfAborted();
798
+ this.current();
799
+ check2(
800
+ requiresAuthorization(this.#saved.plan),
801
+ "operation does not require wallet authorization"
802
+ );
803
+ check2(
804
+ ["prepared", "authorized"].includes(this.status),
805
+ "operation is not awaiting wallet authorization"
806
+ );
807
+ check2(!this.#walletRequests.has(id), "wallet request id already exported");
808
+ const request = authorizationRequest(this.#saved.plan);
809
+ const prepared = prepareWalletRequest(
810
+ Wallet.fromAddress(this.#saved.plan.scope.ownerAddress),
811
+ id,
812
+ "wallet.authorize",
813
+ {
814
+ ...request,
815
+ words: request.words.map(String),
816
+ context: {
817
+ chainId: request.context.chainId.toString(),
818
+ protocolAddress: request.context.protocolAddress.toString()
819
+ }
820
+ }
821
+ );
822
+ this.#walletRequests.set(id, prepared);
823
+ return structuredClone(prepared.request);
824
+ }
825
+ /** Independently validate host authorization against the retained request and frozen plan. */
826
+ async withWalletResponse(response, options = {}) {
827
+ options.signal?.throwIfAborted();
828
+ this.current();
829
+ check2(
830
+ requiresAuthorization(this.#saved.plan),
831
+ "operation does not require wallet authorization"
832
+ );
833
+ const prepared = this.#walletRequests.get(response.id);
834
+ check2(prepared, "unknown wallet request response");
835
+ const authorization = await acceptWalletResponse(
836
+ prepared,
837
+ response
838
+ );
839
+ return this.stage(
840
+ "wallet authorization",
841
+ ["prepared", "authorized"],
842
+ async () => ({ status: "authorized", authorization }),
843
+ options.signal
844
+ );
845
+ }
846
+ /** Public EIP-712 request; signing transport and key custody belong to the caller. */
847
+ async exportWalletAuthorization(options = {}) {
848
+ options.signal?.throwIfAborted();
849
+ this.current();
850
+ check2(
851
+ requiresAuthorization(this.#saved.plan),
852
+ "operation does not require wallet authorization"
853
+ );
854
+ check2(
855
+ ["prepared", "authorized"].includes(this.status),
856
+ "operation is not awaiting wallet authorization"
857
+ );
858
+ return walletSigningRequest(this.#saved.plan);
859
+ }
860
+ /** Attach an external EOA signature, retaining its witness only at the private proving boundary. */
861
+ async withWalletSignature(signature, options = {}) {
862
+ options.signal?.throwIfAborted();
863
+ this.current();
864
+ check2(
865
+ requiresAuthorization(this.#saved.plan),
866
+ "operation does not require wallet authorization"
867
+ );
868
+ check2(
869
+ ["prepared", "authorized"].includes(this.status),
870
+ "operation is not awaiting wallet authorization"
871
+ );
872
+ const authorization = await acceptWalletSignature(this.#saved.plan, signature);
873
+ return this.stage(
874
+ "wallet authorization",
875
+ ["prepared", "authorized"],
876
+ async () => ({ status: "authorized", authorization }),
877
+ options.signal
878
+ );
879
+ }
880
+ /** Export only after proving when the funding authorization binds an actual proof hash. */
881
+ async exportFundingAuthorization(options = {}) {
882
+ options.signal?.throwIfAborted();
883
+ this.current();
884
+ check2(
885
+ this.status === (this.kind === "shield" ? "prepared" : "proved"),
886
+ "operation is not awaiting funding authorization or proof"
887
+ );
888
+ const request = await fundingSigningRequest(this.#saved, this.#runtime);
889
+ options.signal?.throwIfAborted();
890
+ this.current();
891
+ return request;
892
+ }
893
+ /** Verify an external signature against this handle's own frozen operation. */
894
+ async withFundingSignature(signature, options = {}) {
895
+ options.signal?.throwIfAborted();
896
+ this.current();
897
+ check2(
898
+ this.status === (this.kind === "shield" ? "prepared" : "proved"),
899
+ "operation is not awaiting funding authorization or proof"
900
+ );
901
+ const verified = await acceptFundingSignature(this.#saved, signature, this.#runtime);
902
+ return this.stage(
903
+ "funding authorization",
904
+ this.kind === "shield" ? ["prepared"] : ["proved"],
905
+ async (saved) => {
906
+ saved.plan.funding.signature = verified;
907
+ if (saved.plan.statement?.target !== "noir-recursive") {
908
+ saved.call = await this.encode(saved);
909
+ }
910
+ return { status: "ready" };
911
+ },
912
+ options.signal
913
+ );
914
+ }
915
+ async prove(backendOrOptions = {}, suppliedOptions = {}) {
916
+ const options = { ..."prove" in backendOrOptions ? suppliedOptions : backendOrOptions };
917
+ check2(
918
+ !this.#saved.broadcasterQuote || options.execution !== "aggregate",
919
+ "a broadcaster quote requires direct execution"
920
+ );
921
+ const plan = this.#saved.plan;
922
+ check2(
923
+ plan.kind !== "shield" && plan.kind !== "revoke-credit",
924
+ "operation requires no proof"
925
+ );
926
+ if (requiresAuthorization(plan)) {
927
+ check2(
928
+ this.#authorization,
929
+ "local wallet authorization required; authorize again after recovery"
930
+ );
931
+ }
932
+ const prover = "prove" in backendOrOptions ? backendOrOptions : this.#runtime.options.prover;
933
+ if (!prover) {
934
+ throw new MissingCapabilityError("prover");
935
+ }
936
+ return this.stage(
937
+ "proof",
938
+ requiresAuthorization(plan) ? ["authorized"] : ["prepared"],
939
+ async (saved) => {
940
+ const p = saved.plan;
941
+ saved.proof = await proveOperation(
942
+ this.#runtime.options.protocol,
943
+ p,
944
+ this.#authorization,
945
+ prover,
946
+ options
947
+ );
948
+ if (p.fundingMode === "signature") {
949
+ return { status: "proved" };
950
+ }
951
+ if (p.statement?.target !== "noir-recursive") {
952
+ saved.call = await this.encode(saved);
953
+ }
954
+ return { status: "ready" };
955
+ },
956
+ options.signal
957
+ );
958
+ }
959
+ encode(saved) {
960
+ return encodeOperation(saved);
961
+ }
962
+ /** Shield caller funding needs no wallet signing or proof; this step only encodes its frozen request. */
963
+ async ready() {
964
+ check2(
965
+ this.kind === "shield" && this.#saved.plan.fundingMode === "caller" || this.kind === "revoke-credit",
966
+ "operation needs authorization or proof first"
967
+ );
968
+ return this.stage("encoding", ["prepared"], async (saved) => {
969
+ saved.call = await this.encode(saved);
970
+ return { status: "ready" };
971
+ });
972
+ }
973
+ async exportTransaction() {
974
+ this.current();
975
+ check2(
976
+ this.#saved.plan.statement?.target !== "noir-recursive",
977
+ "recursive operations must be exported as aggregate members"
978
+ );
979
+ check2(this.status === "ready" && this.#saved.call, "transaction is not ready");
980
+ return structuredClone(this.#saved.call);
981
+ }
982
+ exportProof() {
983
+ this.current();
984
+ check2(this.#saved.proof, "transaction has no proof");
985
+ return publicProof(this.#saved.proof);
986
+ }
987
+ exportAggregateMember() {
988
+ this.current();
989
+ const saved = this.#saved, plan = saved.plan;
990
+ check2(
991
+ this.status === "ready" && plan.params && saved.proof && plan.statement?.target === "noir-recursive" && plan.statement.circuitName.startsWith("transact_user_slots") && (plan.capacity ?? 0) <= 10,
992
+ "ready recursive C1..C10 transaction required"
993
+ );
994
+ sameStatement(saved.proof, statement(plan));
995
+ check2(
996
+ saved.proof.proofHex.length === 2 + 458 * 64,
997
+ "recursive member proof must have 458 fields"
998
+ );
999
+ return {
1000
+ bundle: publicProof(saved.proof),
1001
+ statement: structuredClone(plan.statement),
1002
+ context: { ...plan.context },
1003
+ request: {
1004
+ params: structuredClone(plan.params),
1005
+ deliveries: plan.outputs.map((output) => structuredClone(output.delivery)),
1006
+ funding: normalizeFunding2(plan.funding)
1007
+ }
1008
+ };
1009
+ }
1010
+ toJSON() {
1011
+ return { transaction: true, id: this.id, kind: this.kind, status: this.status };
1012
+ }
1013
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
1014
+ return this.toJSON();
1015
+ }
1016
+ };
1017
+
1018
+ // src/client/infrastructure.ts
1019
+ import { MissingCapabilityError as MissingCapabilityError2 } from "@invisi-labs/primitives";
1020
+ import { ProtocolRpcClient } from "@invisi-labs/rpc";
1021
+ function configureTransactionInfrastructure(options) {
1022
+ const { provider } = options;
1023
+ const reader = options.chainReader ?? (provider ? new EthersChainReader(provider) : void 0);
1024
+ const protocolRpc = options.protocolRpc instanceof ProtocolRpcClient && reader ? options.protocolRpc.withReader(reader) : options.protocolRpc;
1025
+ const fundingVerifier = options.fundingVerifier ?? (provider ? new EthersFundingVerifier(provider, options.protocol.context.chainId) : void 0);
1026
+ return configureRecipientInfrastructure({
1027
+ ...options,
1028
+ ...reader ? { chainReader: reader } : {},
1029
+ ...protocolRpc ? { protocolRpc } : {},
1030
+ ...fundingVerifier ? { fundingVerifier } : {}
1031
+ });
1032
+ }
1033
+ async function validateTransactionInfrastructure(options) {
1034
+ if (!options.chainReader) throw new MissingCapabilityError2("chain reader");
1035
+ if (options.provider && (await options.provider.getNetwork()).chainId !== options.protocol.context.chainId)
1036
+ throw new Error("provider deployment chain mismatch");
1037
+ await options.protocol.validateDeployment(options.chainReader);
1038
+ }
1039
+
1040
+ // src/client/Invisi.ts
1041
+ import { MissingCapabilityError as MissingCapabilityError3, Wallet as Wallet2 } from "@invisi-labs/primitives";
1042
+ import { ProtocolRpcClient as ProtocolRpcClient2 } from "@invisi-labs/rpc";
1043
+
1044
+ // src/transactions/preparation/explicit-preparation.ts
1045
+ import { getAddress as getAddress2 } from "ethers";
1046
+ function explicitPreparation(options, data, tokenAddress) {
1047
+ if (!options.chainReader) throw new Error("chain reader required");
1048
+ const inputs = structuredClone(data.inputs ?? []);
1049
+ const credits = structuredClone(data.creditInputs ?? []);
1050
+ const inventory = { notes: {}, credits: {}, reservations: {} };
1051
+ const context = options.protocol.context;
1052
+ function position2(input) {
1053
+ if (typeof input.treeId !== "bigint" || input.treeId < 0n || input.treeId >= 1n << 256n || !Number.isInteger(input.leafIndex) || input.leafIndex < 0 || input.leafIndex >= 65536)
1054
+ throw new Error("invalid explicit input position");
1055
+ }
1056
+ for (const input of inputs) {
1057
+ position2(input);
1058
+ positiveAmount(input.note.amount);
1059
+ if (inventory.notes[input.commitment]) throw new Error("duplicate explicit note input");
1060
+ if (input.note.chainId !== context.chainId || input.note.protocolAddress !== BigInt(context.protocolAddress) || input.note.ownerAddress !== options.wallet.ownerAddress)
1061
+ throw new Error("explicit note identity or deployment mismatch");
1062
+ inventory.notes[input.commitment] = { ...input, spent: "unspent" };
1063
+ }
1064
+ for (const input of credits) {
1065
+ position2(input);
1066
+ if (input.role !== "owner" && input.role !== "spender")
1067
+ throw new Error("invalid explicit Credit role");
1068
+ const key = input.commitment + ":" + input.role;
1069
+ if (inventory.credits[key]) throw new Error("duplicate explicit Credit input");
1070
+ inventory.credits[key] = { ...input, spent: "unspent" };
1071
+ }
1072
+ const scope = {
1073
+ ...context,
1074
+ namespace: "explicit",
1075
+ ownerAddress: options.wallet.ownerAddress
1076
+ };
1077
+ const capabilities = options;
1078
+ if (inputs.some((input) => input.note.tokenAddress !== BigInt(getAddress2(tokenAddress))))
1079
+ throw new Error("explicit note token mismatch");
1080
+ const runtime = {
1081
+ options: { ...capabilities, protocol: options.protocol.forToken(tokenAddress) },
1082
+ reader: options.chainReader,
1083
+ scope
1084
+ };
1085
+ const reprepare = (intent) => import("./broadcaster-preparation-ZQAPZAUG.js").then(
1086
+ ({ prepareIntent }) => prepareIntent(
1087
+ {
1088
+ ...runtime,
1089
+ explicitInputs: true,
1090
+ ...data.changeAddress ? { changeAddress: data.changeAddress } : {},
1091
+ readInventory: async () => structuredClone(inventory),
1092
+ complete: async (plan) => plan
1093
+ },
1094
+ intent
1095
+ )
1096
+ );
1097
+ return new TransactionPreparation({
1098
+ ...runtime,
1099
+ explicitInputs: true,
1100
+ ...data.changeAddress ? { changeAddress: data.changeAddress } : {},
1101
+ readInventory: async () => structuredClone(inventory),
1102
+ complete: async (plan) => PreparedTransaction.prepare({ ...runtime, reprepare }, plan)
1103
+ });
1104
+ }
1105
+
1106
+ // src/client/Invisi.ts
1107
+ var Invisi = class {
1108
+ #options;
1109
+ constructor(options = {}) {
1110
+ if ("addressLookup" in options || "addressResolver" in options)
1111
+ throw new TypeError(
1112
+ "Recipient lookup belongs to each EVM output; caller resolver injection is not supported"
1113
+ );
1114
+ if ("ciphertextCodecs" in options || "envelopeVersion" in options) {
1115
+ throw new Error(
1116
+ "SDK envelope versions are fixed; encode application payload bytes externally"
1117
+ );
1118
+ }
1119
+ if ("signer" in options || "fundingSigner" in options) {
1120
+ throw new Error(
1121
+ "Invisi does not accept signer defaults; export a signing request and attach the external signature"
1122
+ );
1123
+ }
1124
+ for (const key of [
1125
+ "store",
1126
+ "viewing",
1127
+ "authorization",
1128
+ "namespace",
1129
+ "coinSelector",
1130
+ "wallet",
1131
+ "protocol"
1132
+ ]) {
1133
+ if (key in options)
1134
+ throw new TypeError(`Wallet state and permissions belong to WalletSession: ${key}`);
1135
+ }
1136
+ this.#options = {
1137
+ ...options
1138
+ };
1139
+ Object.freeze(this);
1140
+ }
1141
+ /** A detached snapshot of shared infrastructure; wallet permissions and persistence stay external. */
1142
+ getInfrastructure() {
1143
+ return Object.freeze({
1144
+ ...this.#options
1145
+ });
1146
+ }
1147
+ async resolve(options) {
1148
+ const runtime = configureTransactionInfrastructure({
1149
+ ...this.getInfrastructure(),
1150
+ ...options
1151
+ });
1152
+ await validateTransactionInfrastructure(runtime);
1153
+ return runtime;
1154
+ }
1155
+ /** Discover the selected chain's registry and prepare an independent signing request. */
1156
+ async prepareRegistration(options) {
1157
+ return prepareWithErrors("prepareRegistration", async () => {
1158
+ for (const key of Object.keys(options)) {
1159
+ if (!["wallet", "update", "deadline"].includes(key)) {
1160
+ throw new Error(`Unknown registration option: ${key}`);
1161
+ }
1162
+ }
1163
+ this.assertPublicIdentity(options);
1164
+ const selected = { ...options };
1165
+ const { provider, protocolRpc } = this.#options;
1166
+ if (!provider) throw new MissingCapabilityError3("ethers provider");
1167
+ if (!(protocolRpc instanceof ProtocolRpcClient2)) {
1168
+ throw new MissingCapabilityError3("Protocol RPC deployment discovery");
1169
+ }
1170
+ const chainId = (await provider.getNetwork()).chainId;
1171
+ const deployment = await protocolRpc.getDeployment(chainId);
1172
+ if (!deployment.registry) {
1173
+ throw new MissingCapabilityError3("receiving-key registry deployment");
1174
+ }
1175
+ const registry = new AddressRegistry(
1176
+ { chainId, registryAddress: deployment.registry.address },
1177
+ { expectedRuntimeCodeHash: deployment.registry.runtimeCodeHash }
1178
+ );
1179
+ return registry.prepareRegistration({ ...selected, provider });
1180
+ });
1181
+ }
1182
+ assertPublicIdentity(options) {
1183
+ const { wallet } = options;
1184
+ if (!(wallet instanceof Wallet2) || ["getViewer", "getDetector", "exportAuthorization"].some((key) => key in wallet)) {
1185
+ throw new Error(
1186
+ "Independent preparation requires a Wallet without private capabilities"
1187
+ );
1188
+ }
1189
+ for (const key of ["authorization", "signer", "fundingSigner", "viewing"]) {
1190
+ if (key in options)
1191
+ throw new Error(`Independent preparation does not accept capability: ${key}`);
1192
+ }
1193
+ }
1194
+ resolveExplicit(options) {
1195
+ this.assertPublicIdentity(options);
1196
+ return this.resolve({ wallet: options.wallet, protocol: options.protocol });
1197
+ }
1198
+ async prepareTransfer(options) {
1199
+ return prepareWithErrors("prepareTransfer", async () => {
1200
+ const { wallet, protocol, ...input } = options;
1201
+ const request = structuredClone(input);
1202
+ const runtime = await this.resolveExplicit(options);
1203
+ const preparation = explicitPreparation(runtime, request, request.tokenAddress);
1204
+ return preparation.prepareTransfer(request);
1205
+ });
1206
+ }
1207
+ async prepareShield(options) {
1208
+ return prepareWithErrors("prepareShield", async () => {
1209
+ const { wallet, protocol, ...input } = options;
1210
+ const request = structuredClone(input);
1211
+ const runtime = await this.resolveExplicit(options);
1212
+ const preparation = explicitPreparation(runtime, {}, request.tokenAddress);
1213
+ return preparation.prepareShield(request);
1214
+ });
1215
+ }
1216
+ async prepareCreateCredit(options) {
1217
+ return prepareWithErrors("prepareCreateCredit", async () => {
1218
+ const { wallet, protocol, ...input } = options;
1219
+ const request = structuredClone(input);
1220
+ const runtime = await this.resolveExplicit(options);
1221
+ const preparation = explicitPreparation(runtime, {}, request.tokenAddress);
1222
+ return preparation.prepareCreateCredit(request);
1223
+ });
1224
+ }
1225
+ async prepareDrawCredit(options) {
1226
+ return prepareWithErrors("prepareDrawCredit", async () => {
1227
+ const { wallet, protocol, ...input } = options;
1228
+ const request = structuredClone(input);
1229
+ const runtime = await this.resolveExplicit(options);
1230
+ const preparation = explicitPreparation(runtime, request, request.tokenAddress);
1231
+ return preparation.prepareDrawCredit(request);
1232
+ });
1233
+ }
1234
+ async prepareUpdateCredit(options) {
1235
+ return prepareWithErrors("prepareUpdateCredit", async () => {
1236
+ const { wallet, protocol, ...input } = options;
1237
+ const request = structuredClone(input);
1238
+ const runtime = await this.resolveExplicit(options);
1239
+ const preparation = explicitPreparation(runtime, request, request.tokenAddress);
1240
+ return preparation.prepareUpdateCredit(request);
1241
+ });
1242
+ }
1243
+ async prepareRevokeCredit(options) {
1244
+ return prepareWithErrors("prepareRevokeCredit", async () => {
1245
+ const { wallet, protocol, ...input } = options;
1246
+ const request = structuredClone(input);
1247
+ const runtime = await this.resolveExplicit(options);
1248
+ const preparation = explicitPreparation(runtime, {}, request.tokenAddress);
1249
+ return preparation.prepareRevokeCredit(request);
1250
+ });
1251
+ }
1252
+ toJSON() {
1253
+ return { invisi: true };
1254
+ }
1255
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
1256
+ return this.toJSON();
1257
+ }
1258
+ };
1259
+
1260
+ // src/discovery/protocol-events.ts
1261
+ import { invisiProtocolAbi } from "@invisi-labs/protocol/contracts";
1262
+ import { Interface } from "ethers";
1263
+ var protocolInterface = new Interface(invisiProtocolAbi);
1264
+ function decodeProtocolEvent(log) {
1265
+ const decoded = protocolInterface.parseLog(log);
1266
+ if (!decoded) throw new Error("Unknown protocol receipt event");
1267
+ const encoded = protocolInterface.encodeEventLog(decoded.fragment, decoded.args);
1268
+ if (encoded.data.toLowerCase() !== log.data.toLowerCase() || encoded.topics.length !== log.topics.length || encoded.topics.some(
1269
+ (topic, index2) => topic.toLowerCase() !== log.topics[index2].toLowerCase()
1270
+ ))
1271
+ throw new Error("Noncanonical protocol receipt event");
1272
+ const value = (type, item) => {
1273
+ if (type.baseType === "array")
1274
+ return Array.from(item, (v) => value(type.arrayChildren, v));
1275
+ if (type.baseType === "tuple")
1276
+ return Object.fromEntries(
1277
+ type.components.map((t, i) => [t.name, value(t, item[i])])
1278
+ );
1279
+ return item;
1280
+ };
1281
+ const args = Object.fromEntries(
1282
+ decoded.fragment.inputs.map((type, i) => [type.name, value(type, decoded.args[i])])
1283
+ );
1284
+ return { eventName: decoded.name, args };
1285
+ }
1286
+
1287
+ // src/discovery/receipt-logs.ts
1288
+ function readProtocolLogs(receipt, protocolAddress) {
1289
+ if (receipt.status !== "success" || !/^0x[0-9a-fA-F]{64}$/.test(receipt.transactionHash) || typeof receipt.block.number !== "bigint" || receipt.block.number < 0n || !/^0x[0-9a-fA-F]{64}$/.test(receipt.block.hash))
1290
+ throw new Error("Invalid canonical protocol receipt");
1291
+ const seen = /* @__PURE__ */ new Set();
1292
+ return receipt.logs.filter((log) => log.address.toLowerCase() === protocolAddress.toLowerCase()).map((log) => {
1293
+ if (log.transactionHash.toLowerCase() !== receipt.transactionHash.toLowerCase() || !Number.isSafeInteger(log.logIndex) || log.logIndex < 0 || seen.has(log.logIndex))
1294
+ throw new Error("Invalid canonical receipt log identity");
1295
+ seen.add(log.logIndex);
1296
+ const decoded = decodeProtocolEvent(log);
1297
+ return {
1298
+ address: log.address,
1299
+ eventName: decoded.eventName,
1300
+ args: decoded.args,
1301
+ blockNumber: receipt.block.number,
1302
+ blockHash: receipt.block.hash,
1303
+ transactionHash: receipt.transactionHash.toLowerCase(),
1304
+ logIndex: log.logIndex,
1305
+ removed: false
1306
+ };
1307
+ }).sort((a, b) => a.logIndex - b.logIndex);
1308
+ }
1309
+
1310
+ // src/discovery/discovery.ts
1311
+ import { DeliveryDecryptionError } from "@invisi-labs/primitives";
1312
+ import { MAX_CIPHERTEXT_BYTES } from "@invisi-labs/primitives";
1313
+ import { isAddress } from "ethers";
1314
+ import {
1315
+ decodeAddress,
1316
+ ReceivingAddress
1317
+ } from "@invisi-labs/primitives";
1318
+ import { normalizeOpaqueDelivery } from "@invisi-labs/protocol";
1319
+ var EVENTS = /* @__PURE__ */ new Set([
1320
+ "CommitmentsInserted",
1321
+ "BatchOutputs",
1322
+ "Shield",
1323
+ "Transact",
1324
+ "CrossTreeTransact",
1325
+ "CreditCreated",
1326
+ "CreditDraw",
1327
+ "CreditUpdated",
1328
+ "CreditRevoked"
1329
+ ]);
1330
+ function check3(ok, message) {
1331
+ if (!ok) throw new Error(message);
1332
+ }
1333
+ function object(value) {
1334
+ check3(value && typeof value === "object" && !Array.isArray(value), "invalid event object");
1335
+ return value;
1336
+ }
1337
+ function array(value) {
1338
+ check3(Array.isArray(value), "invalid event array");
1339
+ check3(
1340
+ Array.from({ length: value.length }, (_, i) => i in value).every(Boolean),
1341
+ "sparse event array"
1342
+ );
1343
+ return value;
1344
+ }
1345
+ function integer(value) {
1346
+ check3(
1347
+ typeof value === "bigint" || typeof value === "number" && Number.isSafeInteger(value),
1348
+ "invalid event integer"
1349
+ );
1350
+ const n = BigInt(value);
1351
+ check3(n >= 0n, "negative event integer");
1352
+ return n;
1353
+ }
1354
+ function index(value) {
1355
+ const n = integer(value);
1356
+ check3(n < 65536n, "invalid event leaf index");
1357
+ return Number(n);
1358
+ }
1359
+ function hash(value) {
1360
+ check3(typeof value === "string" && /^0x[0-9a-fA-F]{64}$/.test(value), "invalid event hash");
1361
+ return value.toLowerCase();
1362
+ }
1363
+ function contextCheck(context) {
1364
+ check3(context.chainId >= 0n && context.chainId < 1n << 64n, "invalid discovery chain");
1365
+ check3(
1366
+ isAddress(context.protocolAddress) && BigInt(context.protocolAddress) !== 0n,
1367
+ "invalid discovery instance/token"
1368
+ );
1369
+ }
1370
+ var position = (tree, at) => `${tree}:${at}`;
1371
+ function extractDeliveryCandidates(logs, context, confirmedThrough) {
1372
+ contextCheck(context);
1373
+ check3(confirmedThrough >= 0n, "invalid confirmed height");
1374
+ const relevant = logs.filter(
1375
+ (log) => log.address.toLowerCase() === context.protocolAddress.toLowerCase() && EVENTS.has(log.eventName)
1376
+ );
1377
+ const insertions = /* @__PURE__ */ new Map();
1378
+ const metadata = (log) => {
1379
+ check3(!log.removed, "discovery resync required after reorg");
1380
+ check3(
1381
+ typeof log.blockNumber === "bigint" && log.blockNumber >= 0n && log.blockNumber <= confirmedThrough,
1382
+ "event is not confirmed"
1383
+ );
1384
+ check3(Number.isSafeInteger(log.logIndex) && log.logIndex >= 0, "invalid log position");
1385
+ return {
1386
+ blockNumber: log.blockNumber,
1387
+ blockHash: hash(log.blockHash),
1388
+ transactionHash: hash(log.transactionHash)
1389
+ };
1390
+ };
1391
+ const insertionKey = (log, tree, at) => `${hash(log.transactionHash)}:${position(tree, at)}`;
1392
+ for (const log of relevant) {
1393
+ metadata(log);
1394
+ if (log.eventName !== "CommitmentsInserted" && log.eventName !== "BatchOutputs") continue;
1395
+ const a = object(log.args), tree = integer(a.treeId), start = index(a.startLeafIndex), leaves = array(log.eventName === "BatchOutputs" ? a.noteCommitments : a.commitments);
1396
+ check3(tree > 0n && tree < 1n << 64n, "invalid insertion tree");
1397
+ check3(start + leaves.length <= 65536, "insertion exceeds tree capacity");
1398
+ for (const [i, leaf] of leaves.entries()) {
1399
+ const key = insertionKey(log, tree, start + i), value = hash(leaf), previous = insertions.get(key);
1400
+ check3(!previous || previous === value, "conflicting insertion events");
1401
+ insertions.set(key, value);
1402
+ }
1403
+ }
1404
+ const results = /* @__PURE__ */ new Map();
1405
+ const add = (log, tree, at, commitment, role, wire, token = log.args?.token ?? log.args?.params?.token ?? log.args?.params?.creation?.token) => {
1406
+ check3(tree > 0n && tree < 1n << 64n, "invalid output tree");
1407
+ const inserted = insertions.get(insertionKey(log, tree, at));
1408
+ check3(inserted, "delivery has no matching canonical insertion");
1409
+ if (commitment !== void 0)
1410
+ check3(hash(commitment) === inserted, "delivery commitment conflicts with insertion");
1411
+ const delivery = normalizeOpaqueDelivery(wire, { allowEmpty: role === "funds" });
1412
+ check3(
1413
+ typeof token === "string" && isAddress(token) && BigInt(token) !== 0n,
1414
+ "invalid event token"
1415
+ );
1416
+ const value = {
1417
+ tokenAddress: token,
1418
+ treeId: tree,
1419
+ leafIndex: at,
1420
+ commitment: inserted,
1421
+ role,
1422
+ delivery,
1423
+ ...metadata(log)
1424
+ };
1425
+ const key = `${insertionKey(log, tree, at)}:${role}`, previous = results.get(key);
1426
+ check3(
1427
+ !previous || previous.tokenAddress.toLowerCase() === token.toLowerCase() && previous.delivery.ciphertext === delivery.ciphertext && previous.delivery.clue === delivery.clue && previous.blockHash === value.blockHash,
1428
+ "conflicting delivery events"
1429
+ );
1430
+ results.set(key, value);
1431
+ };
1432
+ const creation = (log, a, fields) => {
1433
+ const tree = integer(a.outputTreeId), leaf = index(a.leafIndex), ds = array(a.deliveries);
1434
+ check3(ds.length === 2, "invalid Credit delivery slots");
1435
+ add(log, tree, leaf, fields.creditCommitment, "owner", ds[0]);
1436
+ add(log, tree, leaf, fields.creditCommitment, "spender", ds[1]);
1437
+ };
1438
+ for (const log of relevant) {
1439
+ const a = object(log.args);
1440
+ if (log.eventName === "Shield") {
1441
+ const ds = array(a.deliveries), tree = integer(a.treeId), start = index(a.startLeafIndex);
1442
+ check3(start + ds.length <= 65536, "shield exceeds tree capacity");
1443
+ ds.forEach((d, i) => add(log, tree, start + i, void 0, "funds", d));
1444
+ } else if (log.eventName === "Transact" || log.eventName === "CrossTreeTransact") {
1445
+ const cs = array(a.noteCommitments), ds = array(a.deliveries), leaves = array(a.leafIndices), tree = integer(a.outputTreeId);
1446
+ check3(
1447
+ cs.length === ds.length && cs.length === leaves.length,
1448
+ "invalid transact delivery slots"
1449
+ );
1450
+ cs.forEach((c, i) => add(log, tree, index(leaves[i]), c, "funds", ds[i]));
1451
+ } else if (log.eventName === "BatchOutputs") {
1452
+ const tokens = array(a.tokens);
1453
+ const cs = array(a.noteCommitments), tree = integer(a.treeId), start = index(a.startLeafIndex), packed = a.packedDeliveries;
1454
+ check3(
1455
+ typeof packed === "string" && /^0x(?:[0-9a-fA-F]{2})*$/.test(packed),
1456
+ "invalid packed deliveries"
1457
+ );
1458
+ check3(tokens.length === cs.length, "batch token count mismatch");
1459
+ check3(start + cs.length <= 65536, "batch exceeds tree capacity");
1460
+ let offset = 2;
1461
+ cs.forEach((c, i) => {
1462
+ check3(offset + 4 <= packed.length, "truncated delivery length prefix");
1463
+ const length = Number.parseInt(packed.slice(offset, offset + 4), 16);
1464
+ offset += 4;
1465
+ check3(
1466
+ length <= MAX_CIPHERTEXT_BYTES && offset + length * 2 + (length === 0 ? 0 : 136) <= packed.length,
1467
+ "invalid packed delivery length"
1468
+ );
1469
+ const ciphertext = `0x${packed.slice(offset, offset + length * 2)}`;
1470
+ offset += length * 2;
1471
+ const clue = length === 0 ? "0x" : `0x${packed.slice(offset, offset + 136)}`;
1472
+ if (length !== 0) offset += 136;
1473
+ add(log, tree, start + i, c, "funds", { ciphertext, clue }, tokens[i]);
1474
+ });
1475
+ check3(offset === packed.length, "trailing packed delivery bytes");
1476
+ } else if (log.eventName === "CreditCreated") creation(log, a, a);
1477
+ else if (log.eventName === "CreditUpdated") creation(log, a, object(a.params));
1478
+ else if (log.eventName === "CreditDraw") {
1479
+ const p = object(a.params), cs = array(p.creditCommitments), ds = array(a.deliveries), leaves = array(a.leafIndices), tree = integer(a.outputTreeId);
1480
+ check3(
1481
+ ds.length === 2 * cs.length + 1 && leaves.length === cs.length + 1,
1482
+ "invalid draw delivery slots"
1483
+ );
1484
+ cs.forEach((c, i) => {
1485
+ add(log, tree, index(leaves[i]), c, "owner", ds[2 * i]);
1486
+ add(log, tree, index(leaves[i]), c, "spender", ds[2 * i + 1]);
1487
+ });
1488
+ add(
1489
+ log,
1490
+ tree,
1491
+ index(leaves[cs.length]),
1492
+ p.noteCommitment,
1493
+ "funds",
1494
+ ds[2 * cs.length],
1495
+ p.token
1496
+ );
1497
+ }
1498
+ }
1499
+ return [...results.values()];
1500
+ }
1501
+ async function decryptCandidates(logs, options) {
1502
+ contextCheck(options.context);
1503
+ decodeAddress(ReceivingAddress.fromIdentity(options.viewing.ownerAddress).toString());
1504
+ check3(
1505
+ !logs.some(
1506
+ (log) => log.address.toLowerCase() === options.context.protocolAddress.toLowerCase() && log.removed
1507
+ ),
1508
+ "discovery resync required after reorg"
1509
+ );
1510
+ const candidates = extractDeliveryCandidates(logs, options.context, options.confirmedThrough);
1511
+ const positions = /* @__PURE__ */ new Map();
1512
+ const unique = /* @__PURE__ */ new Map();
1513
+ for (const candidate of candidates) {
1514
+ const key = position(candidate.treeId, candidate.leafIndex);
1515
+ const previous = positions.get(key);
1516
+ check3(
1517
+ !previous || previous.commitment === candidate.commitment && previous.blockHash === candidate.blockHash && previous.transactionHash === candidate.transactionHash && previous.tokenAddress.toLowerCase() === candidate.tokenAddress.toLowerCase(),
1518
+ "conflicting canonical position"
1519
+ );
1520
+ positions.set(key, candidate);
1521
+ unique.set(`${key}:${candidate.role}`, candidate);
1522
+ }
1523
+ const notes = [];
1524
+ const credits = [];
1525
+ for (const candidate of unique.values()) {
1526
+ const { delivery, role, ...positionData } = candidate;
1527
+ const context = {
1528
+ chainId: options.context.chainId,
1529
+ protocolAddress: BigInt(options.context.protocolAddress),
1530
+ tokenAddress: BigInt(candidate.tokenAddress),
1531
+ outputCommitment: candidate.commitment
1532
+ };
1533
+ try {
1534
+ if (role === "funds") {
1535
+ if (delivery.ciphertext === "0x") continue;
1536
+ const note = await options.viewing.decryptNote(delivery.ciphertext, context);
1537
+ if (note !== null) notes.push({ ...positionData, note });
1538
+ } else {
1539
+ const state = await options.viewing.decryptCredit(delivery.ciphertext, {
1540
+ ...context,
1541
+ role
1542
+ });
1543
+ if (state !== null) credits.push({ ...positionData, role, state });
1544
+ }
1545
+ } catch (error) {
1546
+ if (error instanceof DeliveryDecryptionError) throw error;
1547
+ }
1548
+ }
1549
+ return { notes, credits };
1550
+ }
1551
+
1552
+ export {
1553
+ AddressRegistry,
1554
+ revocationSigningRequest,
1555
+ acceptRevocationSignature,
1556
+ creditReservationKey,
1557
+ inputFacts,
1558
+ operationSources,
1559
+ getOperationGasReference,
1560
+ getDocumentedGasReference2 as getDocumentedGasReference,
1561
+ publicProof,
1562
+ sameStatement,
1563
+ encodeOperation,
1564
+ witnessFor,
1565
+ fundingTypedData,
1566
+ proveOperation,
1567
+ signOperationFunding,
1568
+ walletSigningRequest,
1569
+ acceptWalletSignature,
1570
+ fundingSigningRequest,
1571
+ acceptFundingSignature,
1572
+ operationPreview,
1573
+ PreparedTransaction,
1574
+ configureTransactionInfrastructure,
1575
+ validateTransactionInfrastructure,
1576
+ Invisi,
1577
+ decodeProtocolEvent,
1578
+ readProtocolLogs,
1579
+ extractDeliveryCandidates,
1580
+ decryptCandidates
1581
+ };
1582
+ //# sourceMappingURL=chunk-4H4FARQK.js.map