@midnightntwrk/midnight-js-protocol 0.0.0-stage → 5.0.1

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 (61) hide show
  1. package/README.md +291 -2
  2. package/dist/compact-js-v8-effect.d.ts +1 -0
  3. package/dist/compact-js-v8-effect.js +2 -0
  4. package/dist/compact-js-v8-effect.js.map +1 -0
  5. package/dist/engine.d.ts +420 -0
  6. package/dist/engine.js +832 -0
  7. package/dist/engine.js.map +1 -0
  8. package/dist/errors.d.ts +601 -0
  9. package/dist/errors.js +810 -0
  10. package/dist/errors.js.map +1 -0
  11. package/dist/index.d.ts +1471 -0
  12. package/dist/index.js +799 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/platform-effect-configuration.d.ts +1 -0
  15. package/dist/platform-effect-configuration.js +2 -0
  16. package/dist/platform-effect-configuration.js.map +1 -0
  17. package/dist/platform-effect-contract-address.d.ts +1 -0
  18. package/dist/platform-effect-contract-address.js +2 -0
  19. package/dist/platform-effect-contract-address.js.map +1 -0
  20. package/dist/platform.d.ts +1 -0
  21. package/dist/platform.js +2 -0
  22. package/dist/platform.js.map +1 -0
  23. package/dist/prove.d.ts +45 -0
  24. package/dist/prove.js +61 -0
  25. package/dist/prove.js.map +1 -0
  26. package/dist/shared/compose-options-BFA09u9q.js +468 -0
  27. package/dist/shared/compose-options-BFA09u9q.js.map +1 -0
  28. package/dist/shared/ledger-transaction-DQP8J8tv.js +134 -0
  29. package/dist/shared/ledger-transaction-DQP8J8tv.js.map +1 -0
  30. package/dist/shared/load-BMVWoBo6.js +49 -0
  31. package/dist/shared/load-BMVWoBo6.js.map +1 -0
  32. package/dist/shared/transaction-tags-I3J_Hh8r.js +82 -0
  33. package/dist/shared/transaction-tags-I3J_Hh8r.js.map +1 -0
  34. package/dist/transaction.d.ts +92 -0
  35. package/dist/transaction.js +6 -0
  36. package/dist/transaction.js.map +1 -0
  37. package/dist/v8.d.ts +1 -0
  38. package/dist/v8.js +3 -0
  39. package/dist/v8.js.map +1 -0
  40. package/dist/v9-compact-js-effect-contract.d.ts +1 -0
  41. package/dist/v9-compact-js-effect-contract.js +2 -0
  42. package/dist/v9-compact-js-effect-contract.js.map +1 -0
  43. package/dist/v9-compact-js-effect.d.ts +1 -0
  44. package/dist/v9-compact-js-effect.js +2 -0
  45. package/dist/v9-compact-js-effect.js.map +1 -0
  46. package/dist/v9-compact-js.d.ts +1 -0
  47. package/dist/v9-compact-js.js +2 -0
  48. package/dist/v9-compact-js.js.map +1 -0
  49. package/dist/v9-compact-runtime.d.ts +1 -0
  50. package/dist/v9-compact-runtime.js +2 -0
  51. package/dist/v9-compact-runtime.js.map +1 -0
  52. package/dist/v9-onchain-runtime.d.ts +1 -0
  53. package/dist/v9-onchain-runtime.js +2 -0
  54. package/dist/v9-onchain-runtime.js.map +1 -0
  55. package/dist/v9.d.ts +1 -0
  56. package/dist/v9.js +2 -0
  57. package/dist/v9.js.map +1 -0
  58. package/dist/version.d.ts +173 -0
  59. package/dist/version.js +125 -0
  60. package/dist/version.js.map +1 -0
  61. package/package.json +122 -3
package/dist/index.js ADDED
@@ -0,0 +1,799 @@
1
+ import { ComposeFailedError, ComposeOptionError, NO_CIRCUIT, StateConversionFailedError, UnknownLedgerEraError, Ledger8RuntimeInvalidError, Ledger8RuntimeMissingError } from './errors.js';
2
+ export { COMMON_ERROR_CATEGORIES, COMMON_ERROR_CODES, ConfigurationError, ContractExecutionError, EnvironmentUnsupportedError, InvalidArgumentError, InvariantViolationError, MIDNIGHT_JS_ERROR_CATEGORIES, MaintenanceAuthorityMismatchError, MidnightJsError, PROTOCOL_ERROR_CATEGORIES, PROTOCOL_ERROR_CODES, PayloadNotATransactionError, StateDecodeFailedError, StateInconsistentError, TRANSACTION_TAG_PREFIX, UnknownProtocolVersionError, findCodedCause } from './errors.js';
3
+ import * as ledgerV9 from '@midnightntwrk/ledger-v9';
4
+ import { ContractState } from '@midnightntwrk/ledger-v9';
5
+ import { b as assertComposeEnvelope, a as assembleCallPrototype, e as entryPointName, r as resolveVerifierKeyRegistrations, c as decodeContractStateWith, f as extractStateWith } from './shared/compose-options-BFA09u9q.js';
6
+ export { I as INITIAL_LEDGER_PARAMETERS } from './shared/compose-options-BFA09u9q.js';
7
+ import { l as loadLedger8Protocol } from './shared/load-BMVWoBo6.js';
8
+ export { LEDGER_STATE_KINDS, LEDGER_STATE_TAGS, latestNetworkLedgerVersion, protocolVersionToLedger, versionOfRecord } from './version.js';
9
+ import * as platformJs from '@midnight-ntwrk/platform-js';
10
+ export { platformJs as platform };
11
+ export { C as CURRENT_LEDGER_ERA, L as LEDGER_ERAS, a as LEDGER_TRANSACTION_TAGS, R as RETAINED_LEDGER_ERAS, T as TRANSACTION_STAGES } from './shared/transaction-tags-I3J_Hh8r.js';
12
+ import '@midnight-ntwrk/compact-js';
13
+
14
+ /*
15
+ * This file is part of midnight-js.
16
+ * Copyright (C) Midnight Foundation
17
+ * SPDX-License-Identifier: Apache-2.0
18
+ * Licensed under the Apache License, Version 2.0 (the "License");
19
+ * You may not use this file except in compliance with the License.
20
+ * You may obtain a copy of the License at
21
+ * http://www.apache.org/licenses/LICENSE-2.0
22
+ * Unless required by applicable law or agreed to in writing, software
23
+ * distributed under the License is distributed on an "AS IS" BASIS,
24
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25
+ * See the License for the specific language governing permissions and
26
+ * limitations under the License.
27
+ */
28
+ /**
29
+ * Reads the UTXO outputs a call's transcript claims on behalf of USERS.
30
+ *
31
+ * @param transcript One half of a call's transcript pair. Absent is the normal
32
+ * shape of a call with no fallible half, and yields no outputs.
33
+ * @param version The era every failure raised here names.
34
+ * @param circuitId The entry point every failure raised here names.
35
+ * @returns One `UtxoOutput` per user-addressed unshielded spend the transcript
36
+ * claims. Contract-addressed spends are skipped.
37
+ * @throws ComposeFailedError at stage `'call-dust-payout'` for a user-addressed
38
+ * dust spend.
39
+ * @throws ComposeFailedError at stage `'call-unsupported-payout'` for a
40
+ * user-addressed spend of any token type other than unshielded.
41
+ * @see {@link ComposeRefusalOrder}
42
+ */
43
+ const extractUserAddressedOutputs = (transcript, version, circuitId) => {
44
+ if (transcript === undefined) {
45
+ return [];
46
+ }
47
+ const outputs = [];
48
+ for (const [[tokenType, publicAddress], value] of transcript.effects.claimedUnshieldedSpends) {
49
+ if (publicAddress.tag !== 'user') {
50
+ continue;
51
+ }
52
+ if (tokenType.tag === 'dust') {
53
+ throw new ComposeFailedError(version, 'call-dust-payout', circuitId);
54
+ }
55
+ if (tokenType.tag !== 'unshielded') {
56
+ throw new ComposeFailedError(version, 'call-unsupported-payout', circuitId);
57
+ }
58
+ outputs.push({ value, owner: publicAddress.address, type: tokenType.raw });
59
+ }
60
+ return outputs;
61
+ };
62
+ /**
63
+ * Builds the one unshielded offer each segment of a transaction carries, from
64
+ * EVERY call in the tree.
65
+ *
66
+ * @typeParam TOffer The offer type `ledger.UnshieldedOffer.new` returns.
67
+ * @param calls Every call in the transaction's tree — cross-contract callees
68
+ * as well as the root call, since any of them can produce a payout.
69
+ * @param ledger The era module slice carrying `UnshieldedOffer`.
70
+ * @param version The era every failure raised here names.
71
+ * @returns The guaranteed and fallible offers. A segment with nothing to pay
72
+ * out gets no offer at all rather than an empty one.
73
+ * @throws ComposeFailedError from {@link extractUserAddressedOutputs} for a
74
+ * user-addressed spend this module cannot pay out.
75
+ * @see {@link ComposeRefusalOrder}
76
+ */
77
+ const aggregateUnshieldedOffers = (calls, ledger, version) => {
78
+ const guaranteedOutputs = calls.flatMap((call) => extractUserAddressedOutputs(call.guaranteed, version, call.circuitId));
79
+ const fallibleOutputs = calls.flatMap((call) => extractUserAddressedOutputs(call.fallible, version, call.circuitId));
80
+ return {
81
+ guaranteed: guaranteedOutputs.length > 0 ? ledger.UnshieldedOffer.new([], guaranteedOutputs, []) : undefined,
82
+ fallible: fallibleOutputs.length > 0 ? ledger.UnshieldedOffer.new([], fallibleOutputs, []) : undefined
83
+ };
84
+ };
85
+
86
+ /*
87
+ * This file is part of midnight-js.
88
+ * Copyright (C) Midnight Foundation
89
+ * SPDX-License-Identifier: Apache-2.0
90
+ * Licensed under the Apache License, Version 2.0 (the "License");
91
+ * You may not use this file except in compliance with the License.
92
+ * You may obtain a copy of the License at
93
+ * http://www.apache.org/licenses/LICENSE-2.0
94
+ * Unless required by applicable law or agreed to in writing, software
95
+ * distributed under the License is distributed on an "AS IS" BASIS,
96
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
97
+ * See the License for the specific language governing permissions and
98
+ * limitations under the License.
99
+ */
100
+ /**
101
+ * Reads a serialized Zswap offer into the v8 era, reporting bytes this era
102
+ * cannot decode as {@link ComposeOptionError}. An absent offer is the normal
103
+ * shape of a call that moved no shielded coins, and stays absent.
104
+ *
105
+ * @see {@link ComposeRefusalOrder}
106
+ */
107
+ const readZswapOffer$1 = (raw, v8, option) => {
108
+ if (raw === undefined) {
109
+ return undefined;
110
+ }
111
+ try {
112
+ return v8.ZswapOffer.deserialize('pre-proof', raw);
113
+ }
114
+ catch (cause) {
115
+ throw new ComposeOptionError('v8', option, cause);
116
+ }
117
+ };
118
+ /**
119
+ * Composes a v8-native call transaction from one call's inputs and immediately
120
+ * serializes it. The call prototype comes from {@link assembleCallPrototype}
121
+ * against the injected v8 module.
122
+ *
123
+ * Never proves the transaction: the returned bytes are an UNPROVEN,
124
+ * tag-prefixed serialization, exactly what `Transaction.serialize()` produces
125
+ * before `.prove()` is ever called.
126
+ *
127
+ * @param options The call's inputs, offers and envelope options.
128
+ * @param v8 The v8 ledger module, as handed over by `loadLedger8Protocol`
129
+ * (`./load.ts`).
130
+ * @returns The UNPROVEN, serialized call transaction and the call's partition.
131
+ * @throws ComposeOptionError If `networkId` is empty, `ttl` is not a valid
132
+ * instant, or the factory answered with offer bytes this era cannot read.
133
+ * @throws ComposeFailedError If `contractState` has no registered operation for
134
+ * `circuitId` (stage `'call-operation'`), or the operation it does have
135
+ * carries no verifier key (stage `'call-verifier-key'`), plus every stage
136
+ * {@link assembleCallPrototype} and {@link aggregateUnshieldedOffers} raise.
137
+ * @see {@link ComposeRefusalOrder}
138
+ */
139
+ const composeLedger8CallTx = (options, v8) => {
140
+ const { contractAddress, contractState, networkId, ttl, zswapOffer } = options;
141
+ assertComposeEnvelope(options, 'v8');
142
+ const { prototype, partition } = assembleCallPrototype(v8, {
143
+ circuitId: options.circuitId,
144
+ contractAddress,
145
+ transcript: options.transcript,
146
+ privateTranscriptOutputs: options.privateTranscriptOutputs,
147
+ input: options.input,
148
+ output: options.output,
149
+ communicationCommitmentRandomness: options.communicationCommitmentRandomness,
150
+ ledgerParametersBytes: options.ledgerParametersBytes,
151
+ operations: contractState,
152
+ stage: 'call-operation',
153
+ version: 'v8'
154
+ });
155
+ const intent = v8.Intent.new(ttl).addCall(prototype);
156
+ // Read the partitioned pair back off the intent rather than re-deriving it,
157
+ // and attach the payout on this era too -- see ComposeRefusalOrder.
158
+ const unshielded = aggregateUnshieldedOffers(intent.actions
159
+ .filter((action) => action instanceof v8.ContractCall)
160
+ .map((call) => ({
161
+ circuitId: entryPointName(call.entryPoint),
162
+ guaranteed: call.guaranteedTranscript,
163
+ fallible: call.fallibleTranscript
164
+ })), v8, 'v8');
165
+ if (unshielded.guaranteed !== undefined) {
166
+ intent.guaranteedUnshieldedOffer = unshielded.guaranteed;
167
+ }
168
+ if (unshielded.fallible !== undefined) {
169
+ intent.fallibleUnshieldedOffer = unshielded.fallible;
170
+ }
171
+ // Built only once the call is split, which is the whole point of taking a
172
+ // factory -- see ComposeRefusalOrder.
173
+ const offers = zswapOffer?.([partition]);
174
+ const guaranteedOffer = readZswapOffer$1(offers?.guaranteedBytes, v8, 'zswapOffer');
175
+ const fallibleOffer = readZswapOffer$1(offers?.fallibleBytes, v8, 'zswapOffer');
176
+ return {
177
+ txBytes: v8.Transaction.fromPartsRandomized(networkId, guaranteedOffer, fallibleOffer, intent).serialize(),
178
+ partitions: [partition]
179
+ };
180
+ };
181
+
182
+ /*
183
+ * This file is part of midnight-js.
184
+ * Copyright (C) Midnight Foundation
185
+ * SPDX-License-Identifier: Apache-2.0
186
+ * Licensed under the Apache License, Version 2.0 (the "License");
187
+ * You may not use this file except in compliance with the License.
188
+ * You may obtain a copy of the License at
189
+ * http://www.apache.org/licenses/LICENSE-2.0
190
+ * Unless required by applicable law or agreed to in writing, software
191
+ * distributed under the License is distributed on an "AS IS" BASIS,
192
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
193
+ * See the License for the specific language governing permissions and
194
+ * limitations under the License.
195
+ */
196
+ /**
197
+ * Bridges a pre-fork contract state into the v8 era by bytes, reporting a
198
+ * rejected envelope as {@link ComposeOptionError} rather than letting a raw
199
+ * decoder failure escape.
200
+ */
201
+ const bridgeContractState = (contractState, v8) => {
202
+ try {
203
+ return v8.ContractState.deserialize(contractState);
204
+ }
205
+ catch (error) {
206
+ throw new ComposeOptionError('v8', 'contractStateBytes', error);
207
+ }
208
+ };
209
+ /**
210
+ * Registers one verifier key, reporting bytes the ledger rejects as
211
+ * {@link ComposeFailedError} (stage `'deploy-verifier-key-blob'`) so the
212
+ * failure names the entry point it belongs to.
213
+ */
214
+ const registerVerifierKey = (ledgerContractState, entryPoint, circuitId, verifierKey, v8) => {
215
+ const operation = new v8.ContractOperation();
216
+ try {
217
+ operation.verifierKey = verifierKey;
218
+ }
219
+ catch (error) {
220
+ throw new ComposeFailedError('v8', 'deploy-verifier-key-blob', circuitId, error);
221
+ }
222
+ ledgerContractState.setOperation(entryPoint, operation);
223
+ };
224
+ /**
225
+ * Composes a v8-native deploy transaction from a {@link ConstructorResultPojo}'s
226
+ * `contractState` and immediately serializes it: bridge the constructor's
227
+ * pre-fork state into a v8-native one, register a verifier key for every entry
228
+ * point it declares, then wrap it in a `ContractDeploy` / `Intent` /
229
+ * `Transaction`.
230
+ *
231
+ * The verifier-key map is validated against the state's declared entry points
232
+ * BEFORE anything is registered, by {@link resolveVerifierKeyRegistrations} —
233
+ * the resolver both eras' deploy legs share.
234
+ *
235
+ * Never proves the transaction: the returned bytes are an UNPROVEN,
236
+ * tag-prefixed serialization, exactly what `Transaction.serialize()` produces
237
+ * before `.prove()` is ever called.
238
+ *
239
+ * @param options The state bytes, the verifier-key map, the envelope options
240
+ * and an optional Zswap offer.
241
+ * @param v8 The v8 ledger module, as handed over by `loadLedger8Protocol`
242
+ * (`./load.ts`).
243
+ * @returns The UNPROVEN, serialized transaction, the address the deployment
244
+ * will have, and the registered initial state. A deploy mints a fresh nonce,
245
+ * so the address is not a function of the state a caller passed in and cannot
246
+ * be recomputed from it — and the state the address was derived from is the
247
+ * one a caller stores and later dispatches calls against.
248
+ * @throws ComposeOptionError If `networkId` is empty or `ttl` is not a valid
249
+ * instant, or the state bytes cannot be read.
250
+ * @throws ComposeFailedError If the map and the state's declared entry points
251
+ * do not agree (stages `'deploy-ambiguous-circuit'`,
252
+ * `'deploy-unknown-circuit'`, `'deploy-verifier-key'`), or the ledger itself
253
+ * rejects a key blob (stage `'deploy-verifier-key-blob'`, with the ledger's
254
+ * own failure on `cause`).
255
+ * @see {@link VerifierKeys}
256
+ * @see {@link ComposeRefusalOrder}
257
+ */
258
+ const composeLedger8DeployTx = (options, v8) => {
259
+ const { contractStateBytes, verifierKeys, networkId, ttl, guaranteedZswapOffer } = options;
260
+ assertComposeEnvelope(options, 'v8');
261
+ const ledgerContractState = bridgeContractState(contractStateBytes, v8);
262
+ for (const { entryPoint, circuitId, verifierKey } of resolveVerifierKeyRegistrations(ledgerContractState.operations(), verifierKeys, 'v8')) {
263
+ registerVerifierKey(ledgerContractState, entryPoint, circuitId, verifierKey, v8);
264
+ }
265
+ const deploy = new v8.ContractDeploy(ledgerContractState);
266
+ const intent = v8.Intent.new(ttl).addDeploy(deploy);
267
+ return {
268
+ txBytes: v8.Transaction.fromParts(networkId, guaranteedZswapOffer, undefined, intent).serialize(),
269
+ contractAddress: deploy.address,
270
+ initialContractStateBytes: deploy.initialState.serialize()
271
+ };
272
+ };
273
+
274
+ /*
275
+ * This file is part of midnight-js.
276
+ * Copyright (C) Midnight Foundation
277
+ * SPDX-License-Identifier: Apache-2.0
278
+ * Licensed under the Apache License, Version 2.0 (the "License");
279
+ * You may not use this file except in compliance with the License.
280
+ * You may obtain a copy of the License at
281
+ * http://www.apache.org/licenses/LICENSE-2.0
282
+ * Unless required by applicable law or agreed to in writing, software
283
+ * distributed under the License is distributed on an "AS IS" BASIS,
284
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
285
+ * See the License for the specific language governing permissions and
286
+ * limitations under the License.
287
+ */
288
+ /**
289
+ * Bridges a raw, serialized contract state into the v8 era, reporting a
290
+ * rejected envelope as {@link ComposeOptionError} rather than letting a raw
291
+ * decoder failure escape.
292
+ */
293
+ const readContractState$1 = (raw, v8) => {
294
+ try {
295
+ return v8.ContractState.deserialize(raw);
296
+ }
297
+ catch (cause) {
298
+ throw new ComposeOptionError('v8', 'contractStateBytes', cause);
299
+ }
300
+ };
301
+ /**
302
+ * Maps the era-facade's call options onto the v8-native composition leg
303
+ * (`./compose.ts`).
304
+ *
305
+ * This era composes exactly one call: a `calls` tree with more than one entry
306
+ * is refused rather than silently narrowed. A Zswap offer is NOT refused.
307
+ *
308
+ * @param options The era-facade call options.
309
+ * @param v8 The v8 ledger module, as handed over by `loadLedger8Protocol`
310
+ * (`./load.ts`).
311
+ * @returns The UNPROVEN, serialized call transaction and the call's partition.
312
+ * @throws ComposeOptionError If an option cannot be used: a malformed envelope
313
+ * option, unreadable offer or contract-state bytes, or more than one entry in
314
+ * `calls`.
315
+ * @throws ComposeFailedError If `calls` is empty (stage `'call-empty'`), and
316
+ * for every stage the composition leg this delegates to can raise.
317
+ * @see {@link ComposeRefusalOrder}
318
+ * @see {@link EraBoundary}
319
+ */
320
+ const composeEraLedger8CallTx = (options, v8) => {
321
+ const { calls, networkId, ttl, zswapOffer } = options;
322
+ // Checked here, not left to the inner leg, so both eras refuse in the same
323
+ // order; the re-check in the leg is idempotent -- see ComposeRefusalOrder.
324
+ assertComposeEnvelope(options, 'v8');
325
+ if (calls.length === 0) {
326
+ throw new ComposeFailedError('v8', 'call-empty', NO_CIRCUIT);
327
+ }
328
+ if (calls.length > 1) {
329
+ throw new ComposeOptionError('v8', 'calls');
330
+ }
331
+ const [call] = calls;
332
+ return composeLedger8CallTx({
333
+ circuitId: call.circuitId,
334
+ contractAddress: call.contractAddress,
335
+ contractState: readContractState$1(call.contractStateBytes, v8),
336
+ transcript: call.transcript,
337
+ privateTranscriptOutputs: call.privateTranscriptOutputs,
338
+ input: call.input,
339
+ output: call.output,
340
+ communicationCommitmentRandomness: call.communicationCommitmentRandomness,
341
+ // Carried across the adapter, not dropped. Without this the retained-native path silently
342
+ // partitions against this era's INITIAL parameters while the caller believed it had supplied
343
+ // the chain's -- the same defect this option exists to close, one layer down.
344
+ ledgerParametersBytes: call.ledgerParametersBytes,
345
+ networkId,
346
+ ttl,
347
+ zswapOffer
348
+ }, v8);
349
+ };
350
+ /**
351
+ * Maps the era-facade's deploy options onto the v8-native deploy leg
352
+ * (`./deploy.ts`).
353
+ *
354
+ * `verifierKeys` is optional on the facade but required here: this era's deploy
355
+ * leg registers the compiled contract's keys onto the initial state itself, so
356
+ * the omission is reported as {@link ComposeOptionError}.
357
+ *
358
+ * The contract state crosses into the leg by BYTES, which is what that leg
359
+ * takes: it deserializes into its own era rather than accepting a handle.
360
+ *
361
+ * @param options The era-facade deploy options.
362
+ * @param v8 The v8 ledger module, as handed over by `loadLedger8Protocol`
363
+ * (`./load.ts`).
364
+ * @returns The UNPROVEN, serialized deploy transaction, the address it deploys
365
+ * at, and the registered initial state.
366
+ * @throws ComposeOptionError If an option cannot be used: a malformed envelope
367
+ * option, unreadable offer bytes, or an omitted `verifierKeys` map.
368
+ * @throws ComposeFailedError For every stage the deploy leg this delegates to
369
+ * can raise.
370
+ * @see {@link VerifierKeys}
371
+ * @see {@link ComposeRefusalOrder}
372
+ * @see {@link EraBoundary}
373
+ */
374
+ const composeEraLedger8DeployTx = (options, v8) => {
375
+ const { contractStateBytes, verifierKeys, networkId, ttl, guaranteedZswapOfferBytes } = options;
376
+ // See `composeEraLedger8CallTx` — hoisted so both eras refuse the envelope first.
377
+ assertComposeEnvelope(options, 'v8');
378
+ const guaranteedOffer = readZswapOffer$1(guaranteedZswapOfferBytes, v8, 'guaranteedZswapOfferBytes');
379
+ if (verifierKeys === undefined) {
380
+ throw new ComposeOptionError('v8', 'verifierKeys');
381
+ }
382
+ return composeLedger8DeployTx({ contractStateBytes, verifierKeys, networkId, ttl, guaranteedZswapOffer: guaranteedOffer }, v8);
383
+ };
384
+
385
+ /*
386
+ * This file is part of midnight-js.
387
+ * Copyright (C) Midnight Foundation
388
+ * SPDX-License-Identifier: Apache-2.0
389
+ * Licensed under the Apache License, Version 2.0 (the "License");
390
+ * You may not use this file except in compliance with the License.
391
+ * You may obtain a copy of the License at
392
+ * http://www.apache.org/licenses/LICENSE-2.0
393
+ * Unless required by applicable law or agreed to in writing, software
394
+ * distributed under the License is distributed on an "AS IS" BASIS,
395
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
396
+ * See the License for the specific language governing permissions and
397
+ * limitations under the License.
398
+ */
399
+ /**
400
+ * Bridges a raw, serialized contract state into the v9 era, reporting a
401
+ * rejected envelope as {@link ComposeOptionError} -- see ComposeRefusalOrder.
402
+ */
403
+ const readContractState = (raw) => {
404
+ try {
405
+ return ledgerV9.ContractState.deserialize(raw);
406
+ }
407
+ catch (cause) {
408
+ throw new ComposeOptionError('v9', 'contractStateBytes', cause);
409
+ }
410
+ };
411
+ /**
412
+ * Reads a serialized Zswap offer, reporting bytes this era cannot decode as
413
+ * {@link ComposeOptionError}. An absent offer is the normal shape of a call
414
+ * that moved no shielded coins, and stays absent.
415
+ */
416
+ const readZswapOffer = (raw, option) => {
417
+ if (raw === undefined) {
418
+ return undefined;
419
+ }
420
+ try {
421
+ return ledgerV9.ZswapOffer.deserialize('pre-proof', raw);
422
+ }
423
+ catch (cause) {
424
+ throw new ComposeOptionError('v9', option, cause);
425
+ }
426
+ };
427
+ /**
428
+ * Composes a v9-native call transaction from one or more contract calls and
429
+ * immediately serializes it.
430
+ *
431
+ * Never proves the transaction: the returned bytes are an UNPROVEN,
432
+ * tag-prefixed serialization, exactly what `Transaction.serialize()` produces
433
+ * before `.prove()` is ever called.
434
+ *
435
+ * @param options The calls to compose and the transaction-wide envelope.
436
+ * @returns The serialized UNPROVEN transaction and each call's partition.
437
+ * @throws ComposeFailedError if the call list is empty (stage `'call-empty'`)
438
+ * or a call cannot be assembled; `stage` names which step refused it.
439
+ * @throws ComposeOptionError if the network id, the ttl, a Zswap offer or a
440
+ * call's contract state is unusable.
441
+ * @see {@link ComposeRefusalOrder}
442
+ */
443
+ const composeLedger9CallTx = (options) => {
444
+ const { calls, networkId, ttl, zswapOffer } = options;
445
+ assertComposeEnvelope(options, 'v9');
446
+ if (calls.length === 0) {
447
+ throw new ComposeFailedError('v9', 'call-empty', NO_CIRCUIT);
448
+ }
449
+ let intent = ledgerV9.Intent.new(ttl);
450
+ const partitions = [];
451
+ for (const call of calls) {
452
+ const { prototype, partition } = assembleCallPrototype(ledgerV9, {
453
+ circuitId: call.circuitId,
454
+ contractAddress: call.contractAddress,
455
+ transcript: call.transcript,
456
+ privateTranscriptOutputs: call.privateTranscriptOutputs,
457
+ input: call.input,
458
+ output: call.output,
459
+ communicationCommitmentRandomness: call.communicationCommitmentRandomness,
460
+ ledgerParametersBytes: call.ledgerParametersBytes,
461
+ operations: readContractState(call.contractStateBytes),
462
+ stage: 'call-operation',
463
+ version: 'v9'
464
+ });
465
+ partitions.push(partition);
466
+ intent = intent.addCall(prototype);
467
+ }
468
+ // Read the partitioned pairs back off the intent rather than re-deriving
469
+ // them -- see ComposeRefusalOrder.
470
+ const unshielded = aggregateUnshieldedOffers(intent.actions
471
+ .filter((action) => action instanceof ledgerV9.ContractCall)
472
+ .map((call) => ({
473
+ circuitId: entryPointName(call.entryPoint),
474
+ guaranteed: call.guaranteedTranscript,
475
+ fallible: call.fallibleTranscript
476
+ })), ledgerV9, 'v9');
477
+ if (unshielded.guaranteed !== undefined) {
478
+ intent.guaranteedUnshieldedOffer = unshielded.guaranteed;
479
+ }
480
+ if (unshielded.fallible !== undefined) {
481
+ intent.fallibleUnshieldedOffer = unshielded.fallible;
482
+ }
483
+ // LAST, after the unshielded payout has been aggregated off the assembled
484
+ // intent, because both steps refuse and both eras must refuse in one order --
485
+ // see ComposeRefusalOrder. Built only once every call is split, which is the
486
+ // whole point of taking a factory.
487
+ const offers = zswapOffer?.(partitions);
488
+ const guaranteedOffer = readZswapOffer(offers?.guaranteedBytes, 'zswapOffer');
489
+ const fallibleOffer = readZswapOffer(offers?.fallibleBytes, 'zswapOffer');
490
+ return {
491
+ txBytes: ledgerV9.Transaction.fromPartsRandomized(networkId, guaranteedOffer, fallibleOffer, intent).serialize(),
492
+ partitions
493
+ };
494
+ };
495
+ /**
496
+ * Registers a verifier key for every entry point the state declares, against
497
+ * the map validated by {@link resolveVerifierKeyRegistrations} -- see
498
+ * VerifierKeys.
499
+ */
500
+ const registerVerifierKeys = (contractState, verifierKeys) => {
501
+ for (const { entryPoint, circuitId, verifierKey } of resolveVerifierKeyRegistrations(contractState.operations(), verifierKeys, 'v9')) {
502
+ const operation = new ledgerV9.ContractOperation();
503
+ try {
504
+ operation.verifierKey = verifierKey;
505
+ }
506
+ catch (cause) {
507
+ throw new ComposeFailedError('v9', 'deploy-verifier-key-blob', circuitId, cause);
508
+ }
509
+ contractState.setOperation(entryPoint, operation);
510
+ }
511
+ };
512
+ /**
513
+ * Refuses a state that still declares an entry point with a blank verifier key
514
+ * when no key map was supplied -- see VerifierKeys.
515
+ */
516
+ const assertStateCarriesKeys = (contractState) => {
517
+ for (const entryPoint of contractState.operations()) {
518
+ // `?.` is deliberate here, unlike in `../shared/contract-state.ts`, and so
519
+ // is raising the OPTION error rather than the `'deploy-verifier-key'` stage
520
+ // -- see VerifierKeys.
521
+ if (contractState.operation(entryPoint)?.verifierKey === undefined) {
522
+ throw new ComposeOptionError('v9', 'verifierKeys');
523
+ }
524
+ }
525
+ };
526
+ /**
527
+ * Composes a v9-native deploy transaction from a serialized initial contract
528
+ * state and immediately serializes it, returning the transaction together with
529
+ * the address the deployment will have and the initial state that address is
530
+ * derived from.
531
+ *
532
+ * Never proves the transaction: the returned bytes are an UNPROVEN,
533
+ * tag-prefixed serialization, exactly what `Transaction.serialize()` produces
534
+ * before `.prove()` is ever called.
535
+ *
536
+ * With `verifierKeys` supplied, every declared entry point is registered before
537
+ * the address is derived. Without it, the state is deployed exactly as given —
538
+ * which is checked rather than assumed, see {@link assertStateCarriesKeys}.
539
+ *
540
+ * @param options The serialized initial state, its verifier keys, and the
541
+ * transaction-wide envelope.
542
+ * @returns The serialized UNPROVEN transaction, the address the deployment
543
+ * will have, and the initial state that address was derived from.
544
+ * @throws ComposeFailedError if the supplied keys do not match the state's
545
+ * declared entry points, or if the ledger rejects a key blob; `stage` names
546
+ * which check refused it.
547
+ * @throws ComposeOptionError if the network id, the ttl, the Zswap offer or
548
+ * the state bytes are unusable, or if `verifierKeys` was omitted for a state
549
+ * that still declares a blank key.
550
+ * @see {@link VerifierKeys}
551
+ * @see {@link ComposeRefusalOrder}
552
+ */
553
+ const composeLedger9DeployTx = (options) => {
554
+ const { contractStateBytes, verifierKeys, networkId, ttl, guaranteedZswapOfferBytes } = options;
555
+ assertComposeEnvelope(options, 'v9');
556
+ const guaranteedOffer = readZswapOffer(guaranteedZswapOfferBytes, 'guaranteedZswapOfferBytes');
557
+ const state = readContractState(contractStateBytes);
558
+ if (verifierKeys === undefined) {
559
+ assertStateCarriesKeys(state);
560
+ }
561
+ else {
562
+ registerVerifierKeys(state, verifierKeys);
563
+ }
564
+ const deploy = new ledgerV9.ContractDeploy(state);
565
+ const intent = ledgerV9.Intent.new(ttl).addDeploy(deploy);
566
+ return {
567
+ txBytes: ledgerV9.Transaction.fromParts(networkId, guaranteedOffer, undefined, intent).serialize(),
568
+ contractAddress: deploy.address,
569
+ initialContractStateBytes: deploy.initialState.serialize()
570
+ };
571
+ };
572
+
573
+ /*
574
+ * This file is part of midnight-js.
575
+ * Copyright (C) Midnight Foundation
576
+ * SPDX-License-Identifier: Apache-2.0
577
+ * Licensed under the Apache License, Version 2.0 (the "License");
578
+ * You may not use this file except in compliance with the License.
579
+ * You may obtain a copy of the License at
580
+ * http://www.apache.org/licenses/LICENSE-2.0
581
+ * Unless required by applicable law or agreed to in writing, software
582
+ * distributed under the License is distributed on an "AS IS" BASIS,
583
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
584
+ * See the License for the specific language governing permissions and
585
+ * limitations under the License.
586
+ */
587
+ /**
588
+ * Reads the primary {@link EncodedStateValue} out of a raw, serialized
589
+ * post-fork contract state, tagged `contract-state[v8]`.
590
+ *
591
+ * Reachable without a pre-fork runtime, unlike {@link extractEncodedStateValue},
592
+ * which requires one for every era.
593
+ *
594
+ * @param raw The serialized `contract-state[v8]` state.
595
+ * @returns The primary state read out of the serialized state.
596
+ * @throws StateConversionFailedError at stage `'v9 state read'` if the
597
+ * state is malformed, truncated, over-long, or tagged for the other era,
598
+ * carrying the runtime's own diagnosis on `cause`.
599
+ * @see {@link FailClosedDecoding}
600
+ */
601
+ const extractLedger9EncodedStateValue = (raw) => {
602
+ try {
603
+ return ContractState.deserialize(raw).data.state.encode();
604
+ }
605
+ catch (cause) {
606
+ throw new StateConversionFailedError('v9 state read', cause);
607
+ }
608
+ };
609
+ /**
610
+ * One decoder per {@link LedgerEra}:
611
+ *
612
+ * - `v9` — a post-fork `contract-state[v8]`-tagged state, read via
613
+ * `@midnightntwrk/ledger-v9`.
614
+ * - `v8` — a pre-fork `contract-state[v6]`-tagged state, read via
615
+ * onchain-runtime-v3, the same codec that produced it.
616
+ *
617
+ * A total `Record`, built on a null prototype and frozen -- see the
618
+ * SharedTableDiscipline document.
619
+ */
620
+ const ENVELOPE_DECODERS = Object.freeze(Object.assign(Object.create(null), {
621
+ v8: (raw, ledger8ContractState) => ledger8ContractState.deserialize(raw).data.state.encode(),
622
+ // A reference to the standalone decoder, not a second copy of the same
623
+ // read -- see FailClosedDecoding.
624
+ v9: extractLedger9EncodedStateValue
625
+ }));
626
+ /**
627
+ * Extracts the primary {@link EncodedStateValue} out of a raw, serialized
628
+ * `ContractState`, using the decoder that matches `version`.
629
+ *
630
+ * @param raw The serialized contract state.
631
+ * @param version The era whose decoder reads `raw`. Validated at runtime, not
632
+ * merely type-checked.
633
+ * @param ledger8ContractState The pre-fork `ContractState` statics. Required
634
+ * for every `version`, not just `'v8'`, and checked before any decoding
635
+ * happens.
636
+ * @returns The primary state read out of the serialized state — never a silently
637
+ * empty or partial one.
638
+ * @throws UnknownLedgerEraError if `version` is not a member of
639
+ * `LEDGER_ERAS`.
640
+ * @throws Ledger8RuntimeInvalidError if `ledger8ContractState` does not carry
641
+ * `deserialize`.
642
+ * @throws StateConversionFailedError at stage `'v8 state read'` or
643
+ * `'v9 state read'` if the state cannot be decoded, carrying the
644
+ * runtime's own diagnosis on `cause`.
645
+ * @see {@link FailClosedDecoding}
646
+ * @see {@link SharedTableDiscipline}
647
+ */
648
+ const extractEncodedStateValue = (raw, version, ledger8ContractState) => {
649
+ const decoder = ENVELOPE_DECODERS[version];
650
+ if (typeof decoder !== 'function') {
651
+ throw new UnknownLedgerEraError(version);
652
+ }
653
+ if (typeof ledger8ContractState?.deserialize !== 'function') {
654
+ throw new Ledger8RuntimeInvalidError('ContractState.deserialize');
655
+ }
656
+ try {
657
+ return decoder(raw, ledger8ContractState);
658
+ }
659
+ catch (cause) {
660
+ // THE STAGE IS CHECKED, not just the class: a decoder is injectable, so one
661
+ // that wrapped at a different stage must not pass through -- see
662
+ // FailClosedDecoding.
663
+ const stage = `${version} state read`;
664
+ throw cause instanceof StateConversionFailedError && cause.stage === stage
665
+ ? cause
666
+ : new StateConversionFailedError(stage, cause);
667
+ }
668
+ };
669
+
670
+ /*
671
+ * This file is part of midnight-js.
672
+ * Copyright (C) Midnight Foundation
673
+ * SPDX-License-Identifier: Apache-2.0
674
+ * Licensed under the Apache License, Version 2.0 (the "License");
675
+ * You may not use this file except in compliance with the License.
676
+ * You may obtain a copy of the License at
677
+ * http://www.apache.org/licenses/LICENSE-2.0
678
+ * Unless required by applicable law or agreed to in writing, software
679
+ * distributed under the License is distributed on an "AS IS" BASIS,
680
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
681
+ * See the License for the specific language governing permissions and
682
+ * limitations under the License.
683
+ */
684
+ // One memo slot per era, never one shared slot, and both era objects are frozen --
685
+ // see SharedTableDiscipline and EraBoundary.
686
+ let ledger8EraPromise;
687
+ let ledger9EraPromise;
688
+ /** The v9 era. Wholly synchronous -- see the EraBoundary document. */
689
+ const createLedger9Era = () => {
690
+ const era = {
691
+ version: 'v9',
692
+ extractState: (raw) => extractStateWith(raw, 'v9', extractLedger9EncodedStateValue),
693
+ decodeContractState: (raw) => decodeContractStateWith(raw, 'v9', ledgerV9),
694
+ composeCallTx: composeLedger9CallTx,
695
+ composeDeployTx: composeLedger9DeployTx
696
+ };
697
+ return Object.freeze(era);
698
+ };
699
+ /**
700
+ * The v8 era. Acquires the retained pre-fork ledger and binds it into closure,
701
+ * so the era's own methods stay synchronous -- see the EraBoundary document for why
702
+ * the acquisition is hoisted here.
703
+ */
704
+ const createLedger8Era = async () => {
705
+ const v8 = await loadLedger8Protocol();
706
+ const era = {
707
+ version: 'v8',
708
+ extractState: (raw) => extractStateWith(raw, 'v8', (bytes) => extractEncodedStateValue(bytes, 'v8', v8.ContractState)),
709
+ decodeContractState: (raw) => decodeContractStateWith(raw, 'v8', v8),
710
+ composeCallTx: (options) => composeEraLedger8CallTx(options, v8),
711
+ composeDeployTx: (options) => composeEraLedger8DeployTx(options, v8)
712
+ };
713
+ return Object.freeze(era);
714
+ };
715
+ /**
716
+ * Resolves one ledger era to a {@link LedgerEraFacade} bound to it.
717
+ *
718
+ * This is the only sanctioned way to reach either era's operations. Pass the
719
+ * version resolved from a record or from the network's latest block (see
720
+ * `protocolVersionToLedger` in `../../version.ts`) rather than a string chosen
721
+ * by hand.
722
+ *
723
+ * Memoised per era, so the retained pre-fork WASM is instantiated at most once
724
+ * per process. A FAILED v8 acquisition is not memoised: the next call retries.
725
+ *
726
+ * @param version The era to resolve.
727
+ * @returns The era facade bound to `version`. The same object on every call
728
+ * for that era, and frozen.
729
+ * @throws UnknownLedgerEraError — as a rejection — if `version` is not a
730
+ * member of `LEDGER_ERAS`.
731
+ * @throws Ledger8RuntimeMissingError — as a rejection — if the retained
732
+ * pre-fork runtime cannot be acquired. It propagates unchanged, carrying the
733
+ * underlying cause.
734
+ * @see {@link EraBoundary}
735
+ * @see {@link SharedTableDiscipline}
736
+ */
737
+ const loadLedgerEra = (version) => {
738
+ switch (version) {
739
+ case 'v9':
740
+ return (ledger9EraPromise ??= Promise.resolve(createLedger9Era()));
741
+ case 'v8':
742
+ return (ledger8EraPromise ??= createLedger8Era().catch((error) => {
743
+ ledger8EraPromise = undefined;
744
+ throw error;
745
+ }));
746
+ default: {
747
+ // `const unhandled: never` is a compile-time exhaustiveness gate, and the
748
+ // runtime rejection is not redundant with it -- see SharedTableDiscipline.
749
+ const unhandled = version;
750
+ return Promise.reject(new UnknownLedgerEraError(unhandled));
751
+ }
752
+ }
753
+ };
754
+
755
+ /*
756
+ * This file is part of midnight-js.
757
+ * Copyright (C) Midnight Foundation
758
+ * SPDX-License-Identifier: Apache-2.0
759
+ * Licensed under the Apache License, Version 2.0 (the "License");
760
+ * You may not use this file except in compliance with the License.
761
+ * You may obtain a copy of the License at
762
+ * http://www.apache.org/licenses/LICENSE-2.0
763
+ * Unless required by applicable law or agreed to in writing, software
764
+ * distributed under the License is distributed on an "AS IS" BASIS,
765
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
766
+ * See the License for the specific language governing permissions and
767
+ * limitations under the License.
768
+ */
769
+ let enginePromise;
770
+ /**
771
+ * The only sanctioned runtime path to the engine's public surface.
772
+ *
773
+ * The retained `compact-runtime@0.16` glue and
774
+ * `@midnight-ntwrk/onchain-runtime-v3` WASM load only on the first call — never
775
+ * as a side effect of importing the package root.
776
+ *
777
+ * A failed load is not memoised: the next call retries the import. A
778
+ * {@link Ledger8RuntimeMissingError} from the retained-runtime acquisition
779
+ * propagates unchanged. Every other failure is wrapped in
780
+ * {@link Ledger8RuntimeMissingError}, including the coded
781
+ * `Ledger8RuntimeInvalidError` the envelope decoder raises for an incomplete
782
+ * runtime, and a raw module-resolution error on the engine chunk itself.
783
+ *
784
+ * @returns The engine's public surface, memoised after the first successful
785
+ * load.
786
+ * @throws Ledger8RuntimeMissingError If the retained runtime, or the `./v8/engine`
787
+ * chunk itself, cannot be acquired.
788
+ * @see {@link ModuleGraphAndLazyLoading}
789
+ * @see {@link EraBoundary}
790
+ */
791
+ const loadLedger8Engine = () => (enginePromise ??= import('./engine.js')
792
+ .then((engineModule) => engineModule.createLedger8Engine())
793
+ .catch((error) => {
794
+ enginePromise = undefined;
795
+ throw error instanceof Ledger8RuntimeMissingError ? error : new Ledger8RuntimeMissingError('/v8/engine', error);
796
+ }));
797
+
798
+ export { ComposeFailedError, ComposeOptionError, Ledger8RuntimeInvalidError, Ledger8RuntimeMissingError, NO_CIRCUIT, StateConversionFailedError, UnknownLedgerEraError, loadLedger8Engine, loadLedger8Protocol, loadLedgerEra };
799
+ //# sourceMappingURL=index.js.map