@invisi-labs/sdk 1.1.6 → 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 (132) 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-2URICDPW.cjs +167 -0
  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-QC6TQR3R.js → chunk-4VI6LYGH.js} +35 -12
  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/{broadcaster-preparation-QVL62KM6.js → chunk-HKGJXQVN.js} +73 -34
  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-LOR6PYH5.cjs +397 -0
  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 +11 -385
  60. package/dist/ethers.cjs.map +1 -1
  61. package/dist/ethers.d.cts +16 -6
  62. package/dist/ethers.d.ts +16 -6
  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 +479 -7847
  67. package/dist/index.cjs.map +1 -1
  68. package/dist/index.d.cts +87 -710
  69. package/dist/index.d.ts +87 -710
  70. package/dist/index.js +407 -869
  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/operation-bridge-CoECSxfi.d.cts +472 -0
  79. package/dist/operation-bridge-CoECSxfi.d.ts +472 -0
  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-8Msm_HZS.d.ts +322 -0
  95. package/dist/receipt-logs-DWG4In8N.d.cts +322 -0
  96. package/dist/session-support.cjs +189 -0
  97. package/dist/session-support.cjs.map +1 -0
  98. package/dist/session-support.d.cts +284 -0
  99. package/dist/session-support.d.ts +284 -0
  100. package/dist/session-support.js +189 -0
  101. package/dist/session-support.js.map +1 -0
  102. package/package.json +25 -19
  103. package/dist/NoteOutput-DRkVnwlx.d.cts +0 -398
  104. package/dist/NoteOutput-DpDC6T2O.d.ts +0 -398
  105. package/dist/broadcaster-preparation-QVL62KM6.js.map +0 -1
  106. package/dist/chunk-4SD3MW6N.js +0 -4711
  107. package/dist/chunk-4SD3MW6N.js.map +0 -1
  108. package/dist/chunk-FL4TIGWW.js +0 -1781
  109. package/dist/chunk-FL4TIGWW.js.map +0 -1
  110. package/dist/chunk-QC6TQR3R.js.map +0 -1
  111. package/dist/indexeddb.cjs +0 -6878
  112. package/dist/indexeddb.cjs.map +0 -1
  113. package/dist/indexeddb.d.cts +0 -20
  114. package/dist/indexeddb.d.ts +0 -20
  115. package/dist/indexeddb.js +0 -71
  116. package/dist/indexeddb.js.map +0 -1
  117. package/dist/memory.cjs +0 -6886
  118. package/dist/memory.cjs.map +0 -1
  119. package/dist/memory.d.cts +0 -12
  120. package/dist/memory.d.ts +0 -12
  121. package/dist/memory.js +0 -11
  122. package/dist/sqlite.cjs +0 -6862
  123. package/dist/sqlite.cjs.map +0 -1
  124. package/dist/sqlite.d.cts +0 -28
  125. package/dist/sqlite.d.ts +0 -28
  126. package/dist/sqlite.js +0 -55
  127. package/dist/sqlite.js.map +0 -1
  128. package/dist/state-C4HZFotm.d.cts +0 -78
  129. package/dist/state-C4HZFotm.d.ts +0 -78
  130. package/dist/store-8aBhnbGr.d.ts +0 -42
  131. package/dist/store-YrbXb6CY.d.cts +0 -42
  132. /package/dist/{memory.js.map → broadcaster-7ZKKSTZQ.js.map} +0 -0
@@ -0,0 +1,1582 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+ var _chunkBBSRP4MHcjs = require('./chunk-BBSRP4MH.cjs');
5
+
6
+
7
+
8
+
9
+ var _chunkHCB7RQ3Scjs = require('./chunk-HCB7RQ3S.cjs');
10
+
11
+
12
+ var _chunkOCZLJKIAcjs = require('./chunk-OCZLJKIA.cjs');
13
+
14
+
15
+ var _chunk3KTQQZOWcjs = require('./chunk-3KTQQZOW.cjs');
16
+
17
+
18
+
19
+
20
+ var _chunkMA2QZEF5cjs = require('./chunk-MA2QZEF5.cjs');
21
+
22
+
23
+ var _chunk4SDP53YQcjs = require('./chunk-4SDP53YQ.cjs');
24
+
25
+
26
+
27
+ var _chunkLOR6PYH5cjs = require('./chunk-LOR6PYH5.cjs');
28
+
29
+ // src/protocol/AddressRegistry.ts
30
+ var _rpc = require('@invisi-labs/rpc');
31
+ var AddressRegistry = class extends _rpc.AddressRegistry {
32
+ prepareRegistration(options) {
33
+ return _chunk4SDP53YQcjs.prepareWithErrors.call(void 0, "prepareRegistration", async () => {
34
+ if ("provider" in options) {
35
+ const { provider, ...preparation } = options;
36
+ return super.prepareRegistration({
37
+ ...preparation,
38
+ reader: new (0, _chunkLOR6PYH5cjs.EthersChainReader)(provider)
39
+ });
40
+ }
41
+ return super.prepareRegistration(options);
42
+ });
43
+ }
44
+ };
45
+
46
+ // src/transactions/signing/revocation.ts
47
+ var _primitives = require('@invisi-labs/primitives');
48
+ var _protocol2 = require('@invisi-labs/protocol');
49
+ var _ethers = require('ethers');
50
+ async function revocationSigningRequest(plan, runtime) {
51
+ const params = _optionalChain([plan, 'access', _2 => _2.credit, 'optionalAccess', _3 => _3.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 = _primitives.createSigningRequest.call(void 0,
57
+ _protocol2.encodeRevokeCreditTypedData.call(void 0, { ...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 = _ethers.getAddress.call(void 0,
69
+ _ethers.verifyTypedData.call(void 0, request.domain, request.types, request.message, signature)
70
+ ) === _ethers.getAddress.call(void 0, owner);
71
+ } catch (e) {
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 = _nullishCoalesce(_optionalChain([plan, 'access', _4 => _4.params, 'optionalAccess', _5 => _5.nullifiers]), () => ( []));
92
+ let creditNullifiers = [];
93
+ if (_optionalChain([credit, 'optionalAccess', _6 => _6.draw])) {
94
+ creditNullifiers = credit.draw.nullifiers;
95
+ } else if (_optionalChain([credit, 'optionalAccess', _7 => _7.update])) {
96
+ creditNullifiers = [credit.update.nullifier];
97
+ }
98
+ if (noteNullifiers.length !== plan.inputs.length || creditNullifiers.length !== (_nullishCoalesce(_optionalChain([credit, 'optionalAccess', _8 => _8.inputs, 'access', _9 => _9.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
+ ...(_nullishCoalesce(_optionalChain([credit, 'optionalAccess', _10 => _10.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 = _optionalChain([plan, 'access', _11 => _11.params, 'optionalAccess', _12 => _12.sources]);
118
+ if (noteSources != null) return noteSources;
119
+ const credit = plan.credit;
120
+ if (_optionalChain([credit, 'optionalAccess', _13 => _13.draw])) return credit.draw.sources;
121
+ if (_optionalChain([credit, 'optionalAccess', _14 => _14.update])) return [credit.update.source];
122
+ return [];
123
+ }
124
+
125
+ // src/gas/gas-estimation.ts
126
+
127
+
128
+ function getOperationGasReference(plan, _protocol) {
129
+ let query = { kind: plan.kind };
130
+ const credit = plan.credit;
131
+ if (_optionalChain([plan, 'access', _15 => _15.statement, 'optionalAccess', _16 => _16.target]) === "noir-recursive")
132
+ return _protocol2.getDocumentedGasReference.call(void 0, { kind: "aggregate" });
133
+ if (_optionalChain([credit, 'optionalAccess', _17 => _17.creation]))
134
+ query = { kind: "create-credit", scenario: "first-allocation-empty-tree" };
135
+ else if (_optionalChain([credit, 'optionalAccess', _18 => _18.update]))
136
+ query = { kind: "update-credit", scenario: "after-draw-preserve-usage" };
137
+ else if (_optionalChain([credit, 'optionalAccess', _19 => _19.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" : !(_nullishCoalesce(plan.funding.amount, () => ( 0n))) && !(_nullishCoalesce(_optionalChain([plan, 'access', _20 => _20.params, 'optionalAccess', _21 => _21.withdrawalAmount]), () => ( 0n))) && !(_nullishCoalesce(_optionalChain([plan, 'access', _22 => _22.params, 'optionalAccess', _23 => _23.feeAmount]), () => ( 0n))) ? "private" : "mixed"
161
+ };
162
+ if (credit) {
163
+ const feeAmount = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([credit, 'access', _24 => _24.creation, 'optionalAccess', _25 => _25.feeAmount]), () => ( _optionalChain([credit, 'access', _26 => _26.update, 'optionalAccess', _27 => _27.feeAmount]))), () => ( _optionalChain([credit, 'access', _28 => _28.draw, 'optionalAccess', _29 => _29.feeAmount]))), () => ( _optionalChain([credit, 'access', _30 => _30.revocation, 'optionalAccess', _31 => _31.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) || _optionalChain([credit, 'optionalAccess', _32 => _32.outputs, 'access', _33 => _33.some, 'call', _34 => _34((o) => o.deliveries.some((d) => (d.ciphertext.length - 2) / 2 !== 485))]))
171
+ return _protocol2.getDocumentedGasReference.call(void 0, { kind: "unmeasured-delivery-size" });
172
+ return _protocol2.getDocumentedGasReference.call(void 0, 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
+ var _sha256 = require('@noble/hashes/sha256');
192
+ var _utils = require('@noble/hashes/utils');
193
+
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) && _utils.bytesToHex.call(void 0, _sha256.sha256.call(void 0, _ethers.getBytes.call(void 0, proof.proofHex))) === proof.proofSha256,
208
+ "proof integrity mismatch"
209
+ );
210
+ }
211
+
212
+ // src/transactions/execution/calldata.ts
213
+
214
+
215
+
216
+
217
+
218
+
219
+
220
+
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: _nullishCoalesce(_optionalChain([saved, 'access', _35 => _35.proof, 'optionalAccess', _36 => _36.proofHex]), () => ( "0x")) };
226
+ const funded = { ...common, funding: plan.funding, ...caller ? { caller } : {} };
227
+ let encoded;
228
+ if (_optionalChain([credit, 'optionalAccess', _37 => _37.update])) {
229
+ encoded = _protocol2.buildUpdateCreditCalldata.call(void 0, {
230
+ ...funded,
231
+ params: credit.update,
232
+ deliveries: credit.deliveries
233
+ });
234
+ } else if (_optionalChain([credit, 'optionalAccess', _38 => _38.creation])) {
235
+ encoded = _protocol2.buildCreateCreditCalldata.call(void 0, {
236
+ ...funded,
237
+ params: credit.creation,
238
+ deliveries: credit.deliveries
239
+ });
240
+ } else if (_optionalChain([credit, 'optionalAccess', _39 => _39.draw])) {
241
+ encoded = _protocol2.buildCreditDrawCalldata.call(void 0, {
242
+ ...common,
243
+ params: credit.draw,
244
+ deliveries: credit.deliveries
245
+ });
246
+ } else if (_optionalChain([credit, 'optionalAccess', _40 => _40.revocation])) {
247
+ encoded = _protocol2.buildRevokeCreditCalldata.call(void 0, {
248
+ context: plan.context,
249
+ params: credit.revocation,
250
+ signature: _nullishCoalesce(credit.revocationSignature, () => ( "0x")),
251
+ ...credit.revocationCaller ? { caller: credit.revocationCaller } : {}
252
+ });
253
+ } else if (plan.kind === "shield") {
254
+ encoded = await _protocol2.buildShieldCalldata.call(void 0, {
255
+ ...funded,
256
+ params: plan.shieldParams,
257
+ outputs: plan.shieldOutputs,
258
+ deliveries: plan.outputs.map((output) => output.delivery)
259
+ });
260
+ } else {
261
+ encoded = _protocol2.buildTransactCalldata.call(void 0, {
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
+ var _prover = require('@invisi-labs/prover');
272
+ async function witnessFor(protocol, plan, authorization) {
273
+ const builder = new (0, _prover.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 _chunkMA2QZEF5cjs.assertCreditUpdatePlan.call(void 0, 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
+
326
+
327
+
328
+
329
+
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 _protocol2.encodeShieldFundingTypedData.call(void 0, {
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 (_optionalChain([plan, 'access', _41 => _41.statement, 'optionalAccess', _42 => _42.target]) === "noir-recursive") {
343
+ return _protocol2.encodeAggregateFundingTypedData.call(void 0, plan.context, {
344
+ params: plan.params,
345
+ deliveries: plan.outputs.map((output) => output.delivery),
346
+ funding: plan.funding
347
+ });
348
+ }
349
+ return _protocol2.encodeTransactFundingTypedData.call(void 0,
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
+
360
+
361
+
362
+
363
+
364
+
365
+
366
+
367
+
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 = _chunkHCB7RQ3Scjs.statement.call(void 0, 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 = _prover.WitnessBuilder.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 (e2) {
401
+ _optionalChain([options, 'access', _43 => _43.signal, 'optionalAccess', _44 => _44.throwIfAborted, 'call', _45 => _45()]);
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 _primitives.createSigningRequest.call(void 0, _primitives.walletAuthorizationTypedData.call(void 0, _chunkHCB7RQ3Scjs.authorizationRequest.call(void 0, plan)));
415
+ }
416
+ async function acceptWalletSignature(plan, signature) {
417
+ const request = _chunkHCB7RQ3Scjs.authorizationRequest.call(void 0, plan);
418
+ const digest = _primitives.computeWalletAuthorizationDigest.call(void 0, request);
419
+ try {
420
+ const signed = _ethers.Signature.from(signature);
421
+ const publicKey = _ethers.getBytes.call(void 0, _ethers.SigningKey.recoverPublicKey(digest, signed));
422
+ const owner = await _primitives.computeOwnerAddress.call(void 0, publicKey);
423
+ if (owner.toLowerCase() !== plan.scope.ownerAddress.toLowerCase()) {
424
+ throw new Error("wallet signature identity mismatch");
425
+ }
426
+ return new (0, _primitives.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(_ethers.getBytes.call(void 0, _ethers.concat.call(void 0, [signed.r, signed.s])))
430
+ });
431
+ } catch (e3) {
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 > (_nullishCoalesce(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 = _primitives.createSigningRequest.call(void 0, 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 = _ethers.verifyTypedData.call(void 0, request.domain, types, request.message, signature).toLowerCase() === payer.toLowerCase();
479
+ if (validEOA) {
480
+ signature = _ethers.Signature.from(signature).serialized;
481
+ }
482
+ } catch (e4) {
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
+
498
+
499
+ function operationPreview(plan, status) {
500
+ const p = plan;
501
+ const fee = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(p.params, () => ( p.shieldParams)), () => ( _optionalChain([p, 'access', _46 => _46.credit, 'optionalAccess', _47 => _47.creation]))), () => ( _optionalChain([p, 'access', _48 => _48.credit, 'optionalAccess', _49 => _49.update]))), () => ( _optionalChain([p, 'access', _50 => _50.credit, 'optionalAccess', _51 => _51.draw]))), () => ( _optionalChain([p, 'access', _52 => _52.credit, 'optionalAccess', _53 => _53.revocation])));
502
+ const funding = _protocol2.normalizeFunding.call(void 0, 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
+ ...(_nullishCoalesce(_optionalChain([p, 'access', _54 => _54.credit, 'optionalAccess', _55 => _55.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: _optionalChain([p, 'access', _56 => _56.credit, 'optionalAccess', _57 => _57.outputs, 'access', _58 => _58.map, 'call', _59 => _59((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
+ ..._primitives.normalizeCreditPolicy.call(void 0, output.state.note),
549
+ availableCredit: output.state.note.availableCredit,
550
+ unlimited: output.state.note.unlimited,
551
+ ..._primitives.normalizeCreditUsage.call(void 0, output.state.note)
552
+ }))]),
553
+ creditUpdate: _optionalChain([p, 'access', _60 => _60.credit, 'optionalAccess', _61 => _61.updateChanges]) ? structuredClone(p.credit.updateChanges) : void 0,
554
+ creditDraw: _optionalChain([p, 'access', _62 => _62.credit, 'optionalAccess', _63 => _63.draw]) ? {
555
+ grossAmount: p.credit.draw.totalAmount,
556
+ feeAmount: _nullishCoalesce(p.credit.draw.feeAmount, () => ( 0n)),
557
+ netAmount: p.credit.draw.totalAmount - (_nullishCoalesce(p.credit.draw.feeAmount, () => ( 0n))),
558
+ payers: p.credit.draw.payers.map((payer) => ({ ...payer }))
559
+ } : void 0,
560
+ creditFeePayer: _nullishCoalesce(_nullishCoalesce(_optionalChain([p, 'access', _64 => _64.credit, 'optionalAccess', _65 => _65.creation, 'optionalAccess', _66 => _66.owner]), () => ( _optionalChain([p, 'access', _67 => _67.credit, 'optionalAccess', _68 => _68.update, 'optionalAccess', _69 => _69.owner]))), () => ( _optionalChain([p, 'access', _70 => _70.credit, 'optionalAccess', _71 => _71.revocation, 'optionalAccess', _72 => _72.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: _optionalChain([fee, 'optionalAccess', _73 => _73.feeRecipient]),
570
+ feeAmount: _nullishCoalesce(_optionalChain([fee, 'optionalAccess', _74 => _74.feeAmount]), () => ( 0n)),
571
+ fundingAmount: _nullishCoalesce(p.funding.amount, () => ( 0n)),
572
+ fundingPayer: p.funding.payer,
573
+ withdrawalAmount: _nullishCoalesce(_optionalChain([p, 'access', _75 => _75.params, 'optionalAccess', _76 => _76.withdrawalAmount]), () => ( 0n)),
574
+ withdrawalAddress: _optionalChain([p, 'access', _77 => _77.params, 'optionalAccess', _78 => _78.withdrawalAddress]),
575
+ permissions: {
576
+ walletAuthorization: _chunkHCB7RQ3Scjs.requiresAuthorization.call(void 0, 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
+
585
+
586
+
587
+
588
+
589
+
590
+
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
+
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
+ _chunk3KTQQZOWcjs.bindBroadcasterOperation.call(void 0, 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 Promise.resolve().then(() => _interopRequireWildcard(require("./broadcaster-preparation-PJ263WBL.cjs")));
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 Promise.resolve().then(() => _interopRequireWildcard(require("./provenance-preparation-43DN2WK7.cjs")));
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 Promise.resolve().then(() => _interopRequireWildcard(require("./provenance-preparation-43DN2WK7.cjs")));
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 Promise.resolve().then(() => _interopRequireWildcard(require("./broadcaster-3KTB4JO2.cjs")));
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(_nullishCoalesce(_optionalChain([this, 'access', _79 => _79.#saved, 'access', _80 => _80.provenance, 'optionalAccess', _81 => _81.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 (0, _primitives.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 (0, _chunkOCZLJKIAcjs.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 _chunkBBSRP4MHcjs.exportBroadcasterIntent.call(void 0, 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
+ _optionalChain([signal, 'optionalAccess', _82 => _82.throwIfAborted, 'call', _83 => _83()]);
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
+ _optionalChain([signal, 'optionalAccess', _84 => _84.throwIfAborted, 'call', _85 => _85()]);
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
+ _nullishCoalesce(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
+ _optionalChain([options, 'access', _86 => _86.signal, 'optionalAccess', _87 => _87.throwIfAborted, 'call', _88 => _88()]);
798
+ this.current();
799
+ check2(
800
+ _chunkHCB7RQ3Scjs.requiresAuthorization.call(void 0, 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 = _chunkHCB7RQ3Scjs.authorizationRequest.call(void 0, this.#saved.plan);
809
+ const prepared = _primitives.prepareWalletRequest.call(void 0,
810
+ _primitives.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
+ _optionalChain([options, 'access', _89 => _89.signal, 'optionalAccess', _90 => _90.throwIfAborted, 'call', _91 => _91()]);
828
+ this.current();
829
+ check2(
830
+ _chunkHCB7RQ3Scjs.requiresAuthorization.call(void 0, 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 _primitives.acceptWalletResponse.call(void 0,
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
+ _optionalChain([options, 'access', _92 => _92.signal, 'optionalAccess', _93 => _93.throwIfAborted, 'call', _94 => _94()]);
849
+ this.current();
850
+ check2(
851
+ _chunkHCB7RQ3Scjs.requiresAuthorization.call(void 0, 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
+ _optionalChain([options, 'access', _95 => _95.signal, 'optionalAccess', _96 => _96.throwIfAborted, 'call', _97 => _97()]);
863
+ this.current();
864
+ check2(
865
+ _chunkHCB7RQ3Scjs.requiresAuthorization.call(void 0, 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
+ _optionalChain([options, 'access', _98 => _98.signal, 'optionalAccess', _99 => _99.throwIfAborted, 'call', _100 => _100()]);
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
+ _optionalChain([options, 'access', _101 => _101.signal, 'optionalAccess', _102 => _102.throwIfAborted, 'call', _103 => _103()]);
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
+ _optionalChain([options, 'access', _104 => _104.signal, 'optionalAccess', _105 => _105.throwIfAborted, 'call', _106 => _106()]);
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 (_optionalChain([saved, 'access', _107 => _107.plan, 'access', _108 => _108.statement, 'optionalAccess', _109 => _109.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 (_chunkHCB7RQ3Scjs.requiresAuthorization.call(void 0, 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 (0, _primitives.MissingCapabilityError)("prover");
935
+ }
936
+ return this.stage(
937
+ "proof",
938
+ _chunkHCB7RQ3Scjs.requiresAuthorization.call(void 0, 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 (_optionalChain([p, 'access', _110 => _110.statement, 'optionalAccess', _111 => _111.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
+ _optionalChain([this, 'access', _112 => _112.#saved, 'access', _113 => _113.plan, 'access', _114 => _114.statement, 'optionalAccess', _115 => _115.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 && _optionalChain([plan, 'access', _116 => _116.statement, 'optionalAccess', _117 => _117.target]) === "noir-recursive" && plan.statement.circuitName.startsWith("transact_user_slots") && (_nullishCoalesce(plan.capacity, () => ( 0))) <= 10,
992
+ "ready recursive C1..C10 transaction required"
993
+ );
994
+ sameStatement(saved.proof, _chunkHCB7RQ3Scjs.statement.call(void 0, 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: _protocol2.normalizeFunding.call(void 0, 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
+
1020
+
1021
+ function configureTransactionInfrastructure(options) {
1022
+ const { provider } = options;
1023
+ const reader = _nullishCoalesce(options.chainReader, () => ( (provider ? new (0, _chunkLOR6PYH5cjs.EthersChainReader)(provider) : void 0)));
1024
+ const protocolRpc = options.protocolRpc instanceof _rpc.ProtocolRpcClient && reader ? options.protocolRpc.withReader(reader) : options.protocolRpc;
1025
+ const fundingVerifier = _nullishCoalesce(options.fundingVerifier, () => ( (provider ? new (0, _chunkLOR6PYH5cjs.EthersFundingVerifier)(provider, options.protocol.context.chainId) : void 0)));
1026
+ return _chunkMA2QZEF5cjs.configureRecipientInfrastructure.call(void 0, {
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 (0, _primitives.MissingCapabilityError)("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
+
1042
+
1043
+
1044
+ // src/transactions/preparation/explicit-preparation.ts
1045
+
1046
+ function explicitPreparation(options, data, tokenAddress) {
1047
+ if (!options.chainReader) throw new Error("chain reader required");
1048
+ const inputs = structuredClone(_nullishCoalesce(data.inputs, () => ( [])));
1049
+ const credits = structuredClone(_nullishCoalesce(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
+ _chunkMA2QZEF5cjs.positiveAmount.call(void 0, 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(_ethers.getAddress.call(void 0, 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) => Promise.resolve().then(() => _interopRequireWildcard(require("./broadcaster-preparation-PJ263WBL.cjs"))).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 (0, _chunkBBSRP4MHcjs.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 _chunk4SDP53YQcjs.prepareWithErrors.call(void 0, "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 (0, _primitives.MissingCapabilityError)("ethers provider");
1167
+ if (!(protocolRpc instanceof _rpc.ProtocolRpcClient)) {
1168
+ throw new (0, _primitives.MissingCapabilityError)("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 (0, _primitives.MissingCapabilityError)("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 _primitives.Wallet) || ["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 _chunk4SDP53YQcjs.prepareWithErrors.call(void 0, "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 _chunk4SDP53YQcjs.prepareWithErrors.call(void 0, "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 _chunk4SDP53YQcjs.prepareWithErrors.call(void 0, "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 _chunk4SDP53YQcjs.prepareWithErrors.call(void 0, "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 _chunk4SDP53YQcjs.prepareWithErrors.call(void 0, "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 _chunk4SDP53YQcjs.prepareWithErrors.call(void 0, "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
+ var _contracts = require('@invisi-labs/protocol/contracts');
1262
+
1263
+ var protocolInterface = new (0, _ethers.Interface)(_contracts.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
+
1312
+
1313
+
1314
+
1315
+
1316
+
1317
+
1318
+
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
+ _ethers.isAddress.call(void 0, 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 = _nullishCoalesce(_nullishCoalesce(_optionalChain([log, 'access', _118 => _118.args, 'optionalAccess', _119 => _119.token]), () => ( _optionalChain([log, 'access', _120 => _120.args, 'optionalAccess', _121 => _121.params, 'optionalAccess', _122 => _122.token]))), () => ( _optionalChain([log, 'access', _123 => _123.args, 'optionalAccess', _124 => _124.params, 'optionalAccess', _125 => _125.creation, 'optionalAccess', _126 => _126.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 = _protocol2.normalizeOpaqueDelivery.call(void 0, wire, { allowEmpty: role === "funds" });
1412
+ check3(
1413
+ typeof token === "string" && _ethers.isAddress.call(void 0, 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 <= _primitives.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
+ _primitives.decodeAddress.call(void 0, _primitives.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 _primitives.DeliveryDecryptionError) throw error;
1547
+ }
1548
+ }
1549
+ return { notes, credits };
1550
+ }
1551
+
1552
+
1553
+
1554
+
1555
+
1556
+
1557
+
1558
+
1559
+
1560
+
1561
+
1562
+
1563
+
1564
+
1565
+
1566
+
1567
+
1568
+
1569
+
1570
+
1571
+
1572
+
1573
+
1574
+
1575
+
1576
+
1577
+
1578
+
1579
+
1580
+
1581
+ exports.AddressRegistry = AddressRegistry; exports.revocationSigningRequest = revocationSigningRequest; exports.acceptRevocationSignature = acceptRevocationSignature; exports.creditReservationKey = creditReservationKey; exports.inputFacts = inputFacts; exports.operationSources = operationSources; exports.getOperationGasReference = getOperationGasReference; exports.getDocumentedGasReference = _protocol2.getDocumentedGasReference; exports.publicProof = publicProof; exports.sameStatement = sameStatement; exports.encodeOperation = encodeOperation; exports.witnessFor = witnessFor; exports.fundingTypedData = fundingTypedData; exports.proveOperation = proveOperation; exports.signOperationFunding = signOperationFunding; exports.walletSigningRequest = walletSigningRequest; exports.acceptWalletSignature = acceptWalletSignature; exports.fundingSigningRequest = fundingSigningRequest; exports.acceptFundingSignature = acceptFundingSignature; exports.operationPreview = operationPreview; exports.PreparedTransaction = PreparedTransaction; exports.configureTransactionInfrastructure = configureTransactionInfrastructure; exports.validateTransactionInfrastructure = validateTransactionInfrastructure; exports.Invisi = Invisi; exports.decodeProtocolEvent = decodeProtocolEvent; exports.readProtocolLogs = readProtocolLogs; exports.extractDeliveryCandidates = extractDeliveryCandidates; exports.decryptCandidates = decryptCandidates;
1582
+ //# sourceMappingURL=chunk-NKYHYIRP.cjs.map