@midnightntwrk/midnight-js-utils 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.
package/dist/index.js ADDED
@@ -0,0 +1,1886 @@
1
+ import { MIDNIGHT_JS_ERROR_CATEGORIES, COMMON_ERROR_CODES, PROTOCOL_ERROR_CODES, PROTOCOL_ERROR_CATEGORIES, COMMON_ERROR_CATEGORIES, InvalidArgumentError, MidnightJsError, InvariantViolationError, UnknownLedgerEraError, ConfigurationError } from '@midnightntwrk/midnight-js-protocol/errors';
2
+ export { MIDNIGHT_JS_ERROR_CATEGORIES } from '@midnightntwrk/midnight-js-protocol/errors';
3
+ import { PROVIDER_ERROR_CODES, PROVIDER_ERROR_CATEGORIES } from '@midnightntwrk/midnight-js-types/errors';
4
+ export { PROVIDER_ERROR_CATEGORIES, PROVIDER_ERROR_CODES } from '@midnightntwrk/midnight-js-types/errors';
5
+ import { LEDGER_ERAS, LEDGER_STATE_TAGS } from '@midnightntwrk/midnight-js-protocol/version';
6
+ import { ContractState, ZswapChainState, LedgerParameters, StateValue } from '@midnightntwrk/midnight-js-protocol/v9';
7
+ import { ContractState as ContractState$1 } from '@midnightntwrk/midnight-js-protocol/v9/compact-runtime';
8
+ import { LedgerTransaction } from '@midnightntwrk/midnight-js-types';
9
+ import { MidnightBech32m, ShieldedCoinPublicKey, ShieldedEncryptionPublicKey } from '@midnightntwrk/wallet-sdk-address-format';
10
+ import { Buffer } from 'buffer';
11
+ import { sha256 } from '@noble/hashes/sha2.js';
12
+ import { bytesToHex } from '@noble/hashes/utils.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
+ // Imported from the `./errors` leaf subpath rather than the package root:
29
+ // the root barrel re-exports the ledger/compact-js/onchain-runtime/platform
30
+ // namespaces too, and pulling those into every `utils` consumer just to read
31
+ // a handful of error-code strings would be a needless dependency footprint.
32
+ // Declared here, above the package that throws them, because the no-argument
33
+ // `hasErrorCode` needs a COMPLETE registry. That form is called from `contracts`
34
+ // (`internal/ledger8-entry.ts`, `internal/transaction.ts`), and the registry
35
+ // itself is read by `src/test/troubleshooting-coverage.test.ts`. All three sit
36
+ // at or above `utils`, so the registry cannot move up with them. Every other
37
+ // group is imported from its owner. Add a constant here in the same change that
38
+ // first throws with it.
39
+ const CONTRACTS_ERROR_CODES = Object.freeze({
40
+ ERA_INVARIANT_VIOLATION: 'MIDNIGHT_JS_C_ERA_INVARIANT_VIOLATION',
41
+ ERA_MISMATCH: 'MIDNIGHT_JS_C_ERA_MISMATCH',
42
+ TX_FAILED: 'MIDNIGHT_JS_C_TX_FAILED',
43
+ NETWORK_VERSION_STATE_MISMATCH: 'MIDNIGHT_JS_C_NETWORK_VERSION_STATE_MISMATCH',
44
+ INDEXER_INCONSISTENCY: 'MIDNIGHT_JS_C_INDEXER_INCONSISTENCY',
45
+ PUBLIC_STATES_ERA_MISMATCH: 'MIDNIGHT_JS_C_PUBLIC_STATES_ERA_MISMATCH',
46
+ BLANK_VERIFIER_KEY_SLOT: 'MIDNIGHT_JS_C_BLANK_VERIFIER_KEY_SLOT',
47
+ VERIFIER_KEY_MISMATCH: 'MIDNIGHT_JS_C_VERIFIER_KEY_MISMATCH',
48
+ PROVIDER_FAILED: 'MIDNIGHT_JS_C_PROVIDER_FAILED',
49
+ FORK_CROSSED_DURING_OPERATION: 'MIDNIGHT_JS_C_FORK_CROSSED_DURING_OPERATION',
50
+ SUBMIT_REJECTION_UNDIAGNOSED: 'MIDNIGHT_JS_C_SUBMIT_REJECTION_UNDIAGNOSED',
51
+ LEDGER_PARAMETERS_UNSERVED: 'MIDNIGHT_JS_C_LEDGER_PARAMETERS_UNSERVED',
52
+ CONTRACT_TYPE_MISMATCH: 'MIDNIGHT_JS_C_CONTRACT_TYPE_MISMATCH',
53
+ INCOMPLETE_CALL_TX_PRIVATE_STATE_CONFIG: 'MIDNIGHT_JS_C_INCOMPLETE_CALL_TX_PRIVATE_STATE_CONFIG',
54
+ INCOMPLETE_DEPLOY_PRIVATE_STATE_CONFIG: 'MIDNIGHT_JS_C_INCOMPLETE_DEPLOY_PRIVATE_STATE_CONFIG',
55
+ INCOMPLETE_FIND_PRIVATE_STATE_CONFIG: 'MIDNIGHT_JS_C_INCOMPLETE_FIND_PRIVATE_STATE_CONFIG',
56
+ SCOPED_TRANSACTION_IDENTITY_MISMATCH: 'MIDNIGHT_JS_C_SCOPED_TRANSACTION_IDENTITY_MISMATCH',
57
+ LEDGER8_AMBIGUOUS_ENTRY_POINT: 'MIDNIGHT_JS_C_LEDGER8_AMBIGUOUS_ENTRY_POINT',
58
+ LEDGER8_SIGNING_KEY: 'MIDNIGHT_JS_C_LEDGER8_SIGNING_KEY',
59
+ LEDGER8_UNCONFIRMED: 'MIDNIGHT_JS_C_LEDGER8_UNCONFIRMED',
60
+ LEDGER8_NOT_STORED: 'MIDNIGHT_JS_C_LEDGER8_NOT_STORED',
61
+ LEDGER8_CALL_UNSUPPORTED: 'MIDNIGHT_JS_C_LEDGER8_CALL_UNSUPPORTED',
62
+ NETWORK_VERSION_READ_FAILED: 'MIDNIGHT_JS_C_NETWORK_VERSION_READ_FAILED',
63
+ ZSWAP_OUTPUT_UNRESOLVED: 'MIDNIGHT_JS_C_ZSWAP_OUTPUT_UNRESOLVED',
64
+ CONTRACT_NOT_FOUND: 'MIDNIGHT_JS_C_CONTRACT_NOT_FOUND',
65
+ PRIVATE_STATE_NOT_FOUND: 'MIDNIGHT_JS_C_PRIVATE_STATE_NOT_FOUND'
66
+ });
67
+ const UTILS_ERROR_CODES = Object.freeze({
68
+ TAG_PARSE_FAILED: 'MIDNIGHT_JS_U_TAG_PARSE_FAILED',
69
+ UNHANDLED_UNION_MEMBER: 'MIDNIGHT_JS_U_UNHANDLED_UNION_MEMBER',
70
+ ZK_ARTIFACT_INTEGRITY_FAILED: 'MIDNIGHT_JS_U_ZK_ARTIFACT_INTEGRITY_FAILED',
71
+ ZK_ARTIFACT_CONTRACT_INFO_INVALID: 'MIDNIGHT_JS_U_ZK_ARTIFACT_CONTRACT_INFO_INVALID',
72
+ PASSWORD_INVALID: 'MIDNIGHT_JS_U_PASSWORD_INVALID',
73
+ DESERIALIZATION_FAILED: 'MIDNIGHT_JS_U_DESERIALIZATION_FAILED'
74
+ });
75
+ const { USAGE, ENVIRONMENT, TRANSIENT, REJECTED, UNCERTAIN, INTEGRITY, INTERNAL } = MIDNIGHT_JS_ERROR_CATEGORIES;
76
+ const CONTRACTS_ERROR_CATEGORIES = Object.freeze({
77
+ [CONTRACTS_ERROR_CODES.ERA_INVARIANT_VIOLATION]: INTERNAL,
78
+ [CONTRACTS_ERROR_CODES.ERA_MISMATCH]: USAGE,
79
+ [CONTRACTS_ERROR_CODES.TX_FAILED]: REJECTED,
80
+ [CONTRACTS_ERROR_CODES.NETWORK_VERSION_STATE_MISMATCH]: TRANSIENT,
81
+ [CONTRACTS_ERROR_CODES.INDEXER_INCONSISTENCY]: INTEGRITY,
82
+ [CONTRACTS_ERROR_CODES.PUBLIC_STATES_ERA_MISMATCH]: INTEGRITY,
83
+ [CONTRACTS_ERROR_CODES.BLANK_VERIFIER_KEY_SLOT]: INTEGRITY,
84
+ [CONTRACTS_ERROR_CODES.VERIFIER_KEY_MISMATCH]: INTEGRITY,
85
+ [CONTRACTS_ERROR_CODES.PROVIDER_FAILED]: ENVIRONMENT,
86
+ [CONTRACTS_ERROR_CODES.FORK_CROSSED_DURING_OPERATION]: UNCERTAIN,
87
+ [CONTRACTS_ERROR_CODES.SUBMIT_REJECTION_UNDIAGNOSED]: UNCERTAIN,
88
+ [CONTRACTS_ERROR_CODES.LEDGER_PARAMETERS_UNSERVED]: ENVIRONMENT,
89
+ [CONTRACTS_ERROR_CODES.CONTRACT_TYPE_MISMATCH]: USAGE,
90
+ [CONTRACTS_ERROR_CODES.INCOMPLETE_CALL_TX_PRIVATE_STATE_CONFIG]: USAGE,
91
+ [CONTRACTS_ERROR_CODES.INCOMPLETE_DEPLOY_PRIVATE_STATE_CONFIG]: USAGE,
92
+ [CONTRACTS_ERROR_CODES.INCOMPLETE_FIND_PRIVATE_STATE_CONFIG]: USAGE,
93
+ [CONTRACTS_ERROR_CODES.SCOPED_TRANSACTION_IDENTITY_MISMATCH]: USAGE,
94
+ [CONTRACTS_ERROR_CODES.LEDGER8_AMBIGUOUS_ENTRY_POINT]: INTEGRITY,
95
+ [CONTRACTS_ERROR_CODES.LEDGER8_SIGNING_KEY]: USAGE,
96
+ [CONTRACTS_ERROR_CODES.LEDGER8_UNCONFIRMED]: UNCERTAIN,
97
+ [CONTRACTS_ERROR_CODES.LEDGER8_NOT_STORED]: ENVIRONMENT,
98
+ [CONTRACTS_ERROR_CODES.LEDGER8_CALL_UNSUPPORTED]: USAGE,
99
+ [CONTRACTS_ERROR_CODES.NETWORK_VERSION_READ_FAILED]: TRANSIENT,
100
+ [CONTRACTS_ERROR_CODES.ZSWAP_OUTPUT_UNRESOLVED]: USAGE,
101
+ [CONTRACTS_ERROR_CODES.CONTRACT_NOT_FOUND]: USAGE,
102
+ [CONTRACTS_ERROR_CODES.PRIVATE_STATE_NOT_FOUND]: USAGE
103
+ });
104
+ const UTILS_ERROR_CATEGORIES = Object.freeze({
105
+ [UTILS_ERROR_CODES.TAG_PARSE_FAILED]: INTEGRITY,
106
+ [UTILS_ERROR_CODES.UNHANDLED_UNION_MEMBER]: INTERNAL,
107
+ [UTILS_ERROR_CODES.ZK_ARTIFACT_INTEGRITY_FAILED]: INTEGRITY,
108
+ [UTILS_ERROR_CODES.ZK_ARTIFACT_CONTRACT_INFO_INVALID]: INTEGRITY,
109
+ [UTILS_ERROR_CODES.PASSWORD_INVALID]: USAGE,
110
+ [UTILS_ERROR_CODES.DESERIALIZATION_FAILED]: INTEGRITY
111
+ });
112
+ const MIDNIGHT_JS_ERROR_CODES = Object.freeze([
113
+ ...Object.values(COMMON_ERROR_CODES),
114
+ ...Object.values(PROTOCOL_ERROR_CODES),
115
+ ...Object.values(CONTRACTS_ERROR_CODES),
116
+ ...Object.values(PROVIDER_ERROR_CODES),
117
+ ...Object.values(UTILS_ERROR_CODES)
118
+ ]);
119
+ const MIDNIGHT_JS_ERROR_CATEGORY_BY_CODE = Object.freeze({
120
+ ...COMMON_ERROR_CATEGORIES,
121
+ ...PROTOCOL_ERROR_CATEGORIES,
122
+ ...CONTRACTS_ERROR_CATEGORIES,
123
+ ...PROVIDER_ERROR_CATEGORIES,
124
+ ...UTILS_ERROR_CATEGORIES
125
+ });
126
+ const MIDNIGHT_JS_ERROR_CODE_SET = new Set(MIDNIGHT_JS_ERROR_CODES);
127
+ const isCodedError = (e) => e instanceof Error && 'code' in e && typeof e.code === 'string';
128
+ // The prefix every code in MIDNIGHT_JS_ERROR_CODES carries, pinned by
129
+ // `src/test/error-codes.test.ts`. `hasForeignErrorCode` screens on it rather
130
+ // than on registry membership, because a MISSPELLED framework code is absent
131
+ // from the registry too — and that is the case worth catching.
132
+ const OWN_CODE_PREFIX = 'MIDNIGHT_JS_';
133
+ function hasErrorCode(e, code) {
134
+ if (!isCodedError(e)) {
135
+ return false;
136
+ }
137
+ if (code === undefined) {
138
+ return MIDNIGHT_JS_ERROR_CODE_SET.has(e.code);
139
+ }
140
+ return e.code === code;
141
+ }
142
+ /**
143
+ * True when `e` is an error midnight-js threw. Reads `e.code`, so it also recognises an error built by
144
+ * another installed copy of a midnight-js package, which `instanceof MidnightJsError` would not.
145
+ *
146
+ * Narrows to `Error & { code }`, not to `MidnightJsError`: an error from another copy may lack the
147
+ * class's other members. Read the category with {@link errorCategory}, not `e.category`.
148
+ */
149
+ const isMidnightJsError = (e) => hasErrorCode(e);
150
+ /** What the caller should do about `e`, or `undefined` when `e` is not a midnight-js error. */
151
+ const errorCategory = (e) => hasErrorCode(e) ? MIDNIGHT_JS_ERROR_CATEGORY_BY_CODE[e.code] : undefined;
152
+ function hasForeignErrorCode(e, code) {
153
+ if (code.startsWith(OWN_CODE_PREFIX)) {
154
+ throw new InvalidArgumentError(`hasForeignErrorCode was given '${code}', which uses this framework's own ` +
155
+ `${OWN_CODE_PREFIX} prefix. Use hasErrorCode with a member of MidnightJsErrorCode. ` +
156
+ `If you believe '${code}' is a real midnight-js code, it is misspelled or was never ` +
157
+ `registered — check MIDNIGHT_JS_ERROR_CODES.`);
158
+ }
159
+ return isCodedError(e) && e.code === code;
160
+ }
161
+
162
+ /*
163
+ * This file is part of midnight-js.
164
+ * Copyright (C) Midnight Foundation
165
+ * SPDX-License-Identifier: Apache-2.0
166
+ * Licensed under the Apache License, Version 2.0 (the "License");
167
+ * You may not use this file except in compliance with the License.
168
+ * You may obtain a copy of the License at
169
+ * http://www.apache.org/licenses/LICENSE-2.0
170
+ * Unless required by applicable law or agreed to in writing, software
171
+ * distributed under the License is distributed on an "AS IS" BASIS,
172
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
173
+ * See the License for the specific language governing permissions and
174
+ * limitations under the License.
175
+ */
176
+ /**
177
+ * Asserts that the given value is non-nullable.
178
+ *
179
+ * @param value The value to test for nullability.
180
+ * @param message The error message to use if an error is thrown.
181
+ *
182
+ * @throws InvariantViolationError If the value is nullable.
183
+ */
184
+ function assertDefined(value, message) {
185
+ if (value === null || value === undefined) {
186
+ throw new InvariantViolationError(message ?? 'Expected value to be defined');
187
+ }
188
+ }
189
+ /**
190
+ * Asserts that the given value is null or undefined.
191
+ *
192
+ * @param value The value to test for nullability.
193
+ * @param message The error message to use if an error is thrown.
194
+ *
195
+ * @throws InvariantViolationError If the value is not undefined or null
196
+ */
197
+ function assertUndefined(value, message) {
198
+ if (value !== null && value !== undefined) {
199
+ throw new InvariantViolationError(message ?? 'Expected value to be null or undefined');
200
+ }
201
+ }
202
+ /**
203
+ * Raised by {@link assertNever} when a value the compiler ruled out arrives
204
+ * anyway, which happens when a payload is decoded from outside the build.
205
+ */
206
+ class UnhandledUnionMemberError extends MidnightJsError {
207
+ context;
208
+ code = UTILS_ERROR_CODES.UNHANDLED_UNION_MEMBER;
209
+ category = UTILS_ERROR_CATEGORIES[UTILS_ERROR_CODES.UNHANDLED_UNION_MEMBER];
210
+ constructor(context) {
211
+ super(`Unhandled union member in ${context}: the union grew and this switch was not updated`);
212
+ this.context = context;
213
+ this.name = 'UnhandledUnionMemberError';
214
+ }
215
+ }
216
+ /**
217
+ * Asserts that every member of a union has already been handled.
218
+ *
219
+ * Put it in the `default` case of a `switch` over a discriminated union. While
220
+ * the switch is exhaustive the compiler narrows `value` to `never` and the call
221
+ * type-checks; add a member to the union and the same call stops compiling,
222
+ * pointing at every switch that has to change.
223
+ *
224
+ * The thrown message never includes `value`; `context` is what locates the throw.
225
+ *
226
+ * @param value The narrowed value, which must be `never` for the call to compile.
227
+ * @param context Names the switch, so the runtime throw says where it came from.
228
+ *
229
+ * @throws UnhandledUnionMemberError Always.
230
+ *
231
+ * @example
232
+ * ```ts
233
+ * switch (record.era) {
234
+ * case 'v8': return readRetained(record);
235
+ * case 'v9': return readNative(record);
236
+ * default: return assertNever(record, 'readContractRecord');
237
+ * }
238
+ * ```
239
+ */
240
+ function assertNever(value, context) {
241
+ throw new UnhandledUnionMemberError(context);
242
+ }
243
+
244
+ /*
245
+ * This file is part of midnight-js.
246
+ * Copyright (C) Midnight Foundation
247
+ * SPDX-License-Identifier: Apache-2.0
248
+ * Licensed under the Apache License, Version 2.0 (the "License");
249
+ * You may not use this file except in compliance with the License.
250
+ * You may obtain a copy of the License at
251
+ * http://www.apache.org/licenses/LICENSE-2.0
252
+ * Unless required by applicable law or agreed to in writing, software
253
+ * distributed under the License is distributed on an "AS IS" BASIS,
254
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
255
+ * See the License for the specific language governing permissions and
256
+ * limitations under the License.
257
+ */
258
+ // A serialized value may carry a `namespace:version:` prefix ahead of its
259
+ // binary body (e.g. `midnight:v8:<bytes>`). This tag is a defence-in-depth
260
+ // discriminant only: it is attacker-controlled input, never an authority on
261
+ // the decoded body — the node re-validates the body itself regardless of
262
+ // what this prefix claims.
263
+ const MAX_TAG_PREFIX_BYTES = 64;
264
+ const COLON = 0x3a;
265
+ // Square brackets are part of the real wire format: the ledger runtimes
266
+ // write versions like `contract-state[v8]` and
267
+ // `transaction[v12](signature[v2],proof,pedersen-schnorr[v1])`. They are
268
+ // printable, non-control characters, so accepting them does not reopen the
269
+ // log-injection hole the pattern exists to close.
270
+ const SEGMENT_PATTERN = /^[a-z0-9_[\](),-]+$/i;
271
+ const DEFENCE_IN_DEPTH_NOTE = 'The tag is a defence-in-depth discriminant only — it is attacker-controlled ' +
272
+ 'input and is never the authority on the body; the node remains the sole authority on the decoded body.';
273
+ const NEXT_STEP_NOTE = "Expected a '<namespace>:<version>:' prefix — verify the payload came from a sanctioned serialization source " +
274
+ '(wallet balance response, proof request, or raw contract-state query).';
275
+ class TagParseError extends MidnightJsError {
276
+ code = UTILS_ERROR_CODES.TAG_PARSE_FAILED;
277
+ category = UTILS_ERROR_CATEGORIES[UTILS_ERROR_CODES.TAG_PARSE_FAILED];
278
+ constructor(message, options) {
279
+ super(message, options);
280
+ this.name = 'TagParseError';
281
+ }
282
+ }
283
+ const findSecondColon = (bytes) => {
284
+ const scanLimit = Math.min(bytes.length, MAX_TAG_PREFIX_BYTES);
285
+ let colonsSeen = 0;
286
+ for (let i = 0; i < scanLimit; i += 1) {
287
+ if (bytes[i] === COLON) {
288
+ colonsSeen += 1;
289
+ if (colonsSeen === 2) {
290
+ return i;
291
+ }
292
+ }
293
+ }
294
+ return -1;
295
+ };
296
+ const malformedTagError = (detail) => new TagParseError(`${detail} ${DEFENCE_IN_DEPTH_NOTE} ${NEXT_STEP_NOTE}`);
297
+ /**
298
+ * Parses the `namespace:version:` prefix off the front of a serialized
299
+ * value's raw bytes.
300
+ *
301
+ * Only the first {@link MAX_TAG_PREFIX_BYTES} (64) bytes are ever scanned —
302
+ * this throws {@link TagParseError} without reading further into the buffer
303
+ * if no well-formed prefix is found there, so an attacker cannot force a
304
+ * full-buffer scan by omitting the tag. Both `namespace` and `version` must
305
+ * be non-empty and match `/^[a-z0-9_[\](),-]+$/i` — the character set the
306
+ * ledger runtimes actually emit, brackets and parentheses included. Anything
307
+ * else (whitespace, and control characters, which could otherwise be used to
308
+ * inject fake log lines) throws {@link TagParseError}. `body` is a `.slice()` copy, so it is
309
+ * isolated from the input buffer the caller passed in.
310
+ */
311
+ const parseSerializedTag = (bytes) => {
312
+ const secondColonIndex = findSecondColon(bytes);
313
+ if (secondColonIndex === -1) {
314
+ throw malformedTagError(`Unable to locate a well-formed 'namespace:version:' tag prefix within the first ${MAX_TAG_PREFIX_BYTES} bytes.`);
315
+ }
316
+ let prefixText;
317
+ try {
318
+ prefixText = new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, secondColonIndex));
319
+ }
320
+ catch (cause) {
321
+ throw new TagParseError(`Tag prefix is not valid UTF-8. ${DEFENCE_IN_DEPTH_NOTE} ${NEXT_STEP_NOTE}`, { cause });
322
+ }
323
+ const firstColonIndex = prefixText.indexOf(':');
324
+ const namespace = prefixText.slice(0, firstColonIndex);
325
+ const version = prefixText.slice(firstColonIndex + 1);
326
+ if (!SEGMENT_PATTERN.test(namespace) || !SEGMENT_PATTERN.test(version)) {
327
+ // Deliberately does not echo the raw namespace/version text back into the
328
+ // message: they are attacker-controlled and unvalidated at this point, so
329
+ // embedding them verbatim would let a crafted tag inject arbitrary
330
+ // content (e.g. control characters, fake log lines) into this error's
331
+ // message — the exact risk this validation exists to close off.
332
+ throw malformedTagError("Malformed 'namespace:version:' tag prefix — namespace and version must each be non-empty and match " +
333
+ '/^[a-z0-9_[\\](),-]+$/i.');
334
+ }
335
+ return {
336
+ namespace,
337
+ version,
338
+ tag: `${namespace}:${version}`,
339
+ body: bytes.subarray(secondColonIndex + 1).slice()
340
+ };
341
+ };
342
+
343
+ /*
344
+ * This file is part of midnight-js.
345
+ * Copyright (C) Midnight Foundation
346
+ * SPDX-License-Identifier: Apache-2.0
347
+ * Licensed under the Apache License, Version 2.0 (the "License");
348
+ * You may not use this file except in compliance with the License.
349
+ * You may obtain a copy of the License at
350
+ * http://www.apache.org/licenses/LICENSE-2.0
351
+ * Unless required by applicable law or agreed to in writing, software
352
+ * distributed under the License is distributed on an "AS IS" BASIS,
353
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
354
+ * See the License for the specific language governing permissions and
355
+ * limitations under the License.
356
+ */
357
+ // The `./version` leaf subpath, not the package root: the root barrel re-exports the
358
+ // ledger/compact-js/onchain-runtime namespaces, which every `utils` consumer would then pull in.
359
+ // The tags are `LEDGER_STATE_TAGS` from `protocol`, the one table every package reads. The lookup is
360
+ // keyed by era and searched, never keyed by the network-supplied tag, so an unexpected tag cannot
361
+ // resolve through `Object.prototype`.
362
+ /**
363
+ * Reads which ledger runtime wrote a serialized contract state, from the version tag in front of
364
+ * the state body — without deserializing the body.
365
+ *
366
+ * The tag is attacker-controlled input and is never the authority on the body; the node remains the
367
+ * sole authority on what the bytes decode to. What this check buys is a cheap, early rejection of
368
+ * anything that is not a contract state from a supported runtime, before those bytes reach a
369
+ * decoder — and, for a caller that holds two runtimes, the answer to which one to hand them to.
370
+ *
371
+ * Supported public API, deliberately: a caller reading raw contract state from an indexer needs to
372
+ * know which era's decoder to hand the bytes to before it hands them over.
373
+ *
374
+ * @param raw The serialized contract state, as the network returned it.
375
+ * @returns The ledger era whose runtime wrote `raw`.
376
+ * @throws TagParseError when there is no well-formed `namespace:version:` tag prefix in the first
377
+ * 64 bytes, or when the tag is not one of the supported contract-state version tags.
378
+ */
379
+ const ledgerVersionOfContractState = (raw) => {
380
+ const { tag } = parseSerializedTag(raw);
381
+ const ledgerVersion = LEDGER_ERAS.find((era) => LEDGER_STATE_TAGS.ContractState[era] === tag);
382
+ if (ledgerVersion === undefined) {
383
+ // Never echo the observed tag: it is attacker-controlled and validated only against a
384
+ // character set, so embedding it verbatim puts arbitrary text into this message.
385
+ throw new TagParseError('The serialized state does not start with a contract-state version tag from a supported ledger runtime. ' +
386
+ 'Verify the payload came from a contract-state query and not from another serialized type.');
387
+ }
388
+ return ledgerVersion;
389
+ };
390
+
391
+ /*
392
+ * This file is part of midnight-js.
393
+ * Copyright (C) Midnight Foundation
394
+ * SPDX-License-Identifier: Apache-2.0
395
+ * Licensed under the Apache License, Version 2.0 (the "License");
396
+ * You may not use this file except in compliance with the License.
397
+ * You may obtain a copy of the License at
398
+ * http://www.apache.org/licenses/LICENSE-2.0
399
+ * Unless required by applicable law or agreed to in writing, software
400
+ * distributed under the License is distributed on an "AS IS" BASIS,
401
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
402
+ * See the License for the specific language governing permissions and
403
+ * limitations under the License.
404
+ */
405
+ const ttlOneHour = () => new Date(Date.now() + 60 * 60 * 1000);
406
+
407
+ /*
408
+ * This file is part of midnight-js.
409
+ * Copyright (C) Midnight Foundation
410
+ * SPDX-License-Identifier: Apache-2.0
411
+ * Licensed under the Apache License, Version 2.0 (the "License");
412
+ * You may not use this file except in compliance with the License.
413
+ * You may obtain a copy of the License at
414
+ * http://www.apache.org/licenses/LICENSE-2.0
415
+ * Unless required by applicable law or agreed to in writing, software
416
+ * distributed under the License is distributed on an "AS IS" BASIS,
417
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
418
+ * See the License for the specific language governing permissions and
419
+ * limitations under the License.
420
+ */
421
+ /**
422
+ * Secondary regex applied to the `got` capture group of Pattern #1.
423
+ * Parses the well-formed `<type-name>[vN]:` shape when present.
424
+ * Real ledger errors often produce empty, garbage, or truncated `got` values
425
+ * (verified against ledger-v8@8.1.0) — this secondary match is opportunistic
426
+ * and only used to infer direction.
427
+ */
428
+ // Trailing `-` is a literal hyphen (no escape needed when last in class).
429
+ const GOT_SUBPATTERN = /^(?<gotType>[A-Za-z:-]+)\[v(?<gotVersion>\d+)\]/;
430
+ const pattern1Direction = (match) => {
431
+ const got = match.groups?.got ?? '';
432
+ const sec = GOT_SUBPATTERN.exec(got);
433
+ if (sec === null)
434
+ return undefined;
435
+ const expVer = Number(match.groups?.expectedVersion);
436
+ const gotVer = Number(sec.groups?.gotVersion);
437
+ if (!Number.isFinite(expVer) || !Number.isFinite(gotVer))
438
+ return undefined;
439
+ if (gotVer < expVer)
440
+ return 'data-older-than-code';
441
+ if (gotVer > expVer)
442
+ return 'data-newer-than-code';
443
+ return undefined;
444
+ };
445
+ const pattern1Extract = (match) => {
446
+ const got = match.groups?.got ?? '';
447
+ const sec = GOT_SUBPATTERN.exec(got);
448
+ const expRaw = match.groups?.expectedVersion;
449
+ const gotRaw = sec?.groups?.gotVersion;
450
+ const info = {};
451
+ if (match.groups?.what !== undefined)
452
+ info.dataType = match.groups.what;
453
+ if (expRaw !== undefined)
454
+ info.expectedVersion = Number(expRaw);
455
+ if (gotRaw !== undefined)
456
+ info.receivedVersion = Number(gotRaw);
457
+ return info;
458
+ };
459
+ /**
460
+ * Shared pattern table across all three sources (ledger / compact-runtime / onchain-runtime).
461
+ * Sources share the same `serialize` Rust crate, so error message formats are identical.
462
+ * Order matters — more specific patterns come first; first match wins.
463
+ *
464
+ * Patterns sourced from `midnight-ledger` repo audit (spec §7.1):
465
+ * - `serialize/src/deserializable.rs`, `serialize/src/util.rs`
466
+ * - `serialize-macros/src/lib.rs`
467
+ * - `ledger/src/structure.rs`, `ledger/src/error.rs`
468
+ * - `ledger-wasm/src/conversions.rs`, `onchain-runtime-wasm/src/lib.rs`
469
+ */
470
+ const PATTERNS = [
471
+ // #1 — primary version mismatch (tag header). Permissive on `got` so empty/
472
+ // garbage/truncated incoming tags still classify as version-mismatch;
473
+ // a secondary regex on `got` extracts the received version when present.
474
+ {
475
+ regex: /(?:Unable to deserialize (?<what>[A-Za-z]+)\. Error: )?expected header tag '(?<expectedType>[A-Za-z:-]+)\[v(?<expectedVersion>\d+)\](?:\([^)]+\))?:', got '(?<got>[^']*)'/,
476
+ classification: 'version-mismatch',
477
+ inferDirection: pattern1Direction,
478
+ extract: pattern1Extract
479
+ },
480
+ // #2 — versioned enum old discriminant → data is older
481
+ {
482
+ regex: /invalid old discriminant/i,
483
+ classification: 'version-mismatch',
484
+ inferDirection: () => 'data-older-than-code'
485
+ },
486
+ // #3 — versioned enum unknown discriminant → data is newer
487
+ {
488
+ regex: /unknown discriminant/i,
489
+ classification: 'version-mismatch',
490
+ inferDirection: () => 'data-newer-than-code'
491
+ },
492
+ // #4 — auto-derived enum extension (serialize-macros)
493
+ {
494
+ regex: /unrecognised discriminant/i,
495
+ classification: 'version-mismatch'
496
+ },
497
+ // #5 — explicit unsupported version at higher layer
498
+ {
499
+ regex: /unsupported (?:proof|guaranteed transcript|fallible transcript) version/i,
500
+ classification: 'version-mismatch'
501
+ },
502
+ // #6 — over-read
503
+ {
504
+ regex: /Not all bytes read/,
505
+ classification: 'format-mismatch'
506
+ },
507
+ // #7 — recursion overflow
508
+ {
509
+ regex: /exceeded recursion depth/,
510
+ classification: 'format-mismatch'
511
+ },
512
+ // #8 — scale encoding violation
513
+ {
514
+ regex: /non-canonical scale encoding/,
515
+ classification: 'format-mismatch'
516
+ },
517
+ // #9 — integer range
518
+ {
519
+ regex: /out of range for /,
520
+ classification: 'format-mismatch'
521
+ },
522
+ // #10 — bool decode
523
+ {
524
+ regex: /cannot deserialize \S+ as bool/,
525
+ classification: 'format-mismatch'
526
+ },
527
+ // #11 — Option discriminant (case-sensitive to distinguish from #2/#3)
528
+ {
529
+ regex: /Invalid discriminant: /,
530
+ classification: 'format-mismatch'
531
+ },
532
+ // #12 — Rust std UnexpectedEof
533
+ {
534
+ regex: /failed to fill whole buffer/,
535
+ classification: 'format-mismatch'
536
+ }
537
+ ];
538
+
539
+ /*
540
+ * This file is part of midnight-js.
541
+ * Copyright (C) Midnight Foundation
542
+ * SPDX-License-Identifier: Apache-2.0
543
+ * Licensed under the Apache License, Version 2.0 (the "License");
544
+ * You may not use this file except in compliance with the License.
545
+ * You may obtain a copy of the License at
546
+ * http://www.apache.org/licenses/LICENSE-2.0
547
+ * Unless required by applicable law or agreed to in writing, software
548
+ * distributed under the License is distributed on an "AS IS" BASIS,
549
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
550
+ * See the License for the specific language governing permissions and
551
+ * limitations under the License.
552
+ */
553
+ /**
554
+ * The npm package families that produce the deserialization errors this
555
+ * module wraps. The major-version suffix (e.g. `-v8`, `-v3`) is intentionally
556
+ * omitted — error messages reference the family and rely on the structural
557
+ * version tag carried inside the error itself (e.g. `contract-state[v6]`)
558
+ * for the actual version context.
559
+ *
560
+ * This avoids hardcoded `v8`/`v3` strings that would go stale silently when
561
+ * the underlying package is bumped.
562
+ */
563
+ const SOURCE_PACKAGES = {
564
+ ledger: '@midnight-ntwrk/ledger',
565
+ compactRuntime: '@midnight-ntwrk/compact-runtime',
566
+ onchainRuntime: '@midnight-ntwrk/onchain-runtime'
567
+ };
568
+
569
+ /*
570
+ * This file is part of midnight-js.
571
+ * Copyright (C) Midnight Foundation
572
+ * SPDX-License-Identifier: Apache-2.0
573
+ * Licensed under the Apache License, Version 2.0 (the "License");
574
+ * You may not use this file except in compliance with the License.
575
+ * You may obtain a copy of the License at
576
+ * http://www.apache.org/licenses/LICENSE-2.0
577
+ * Unless required by applicable law or agreed to in writing, software
578
+ * distributed under the License is distributed on an "AS IS" BASIS,
579
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
580
+ * See the License for the specific language governing permissions and
581
+ * limitations under the License.
582
+ */
583
+ const versionMismatchBaseline = () => [
584
+ `Inspect the structural tag in this error (e.g. "expected ... got ..."). It identifies which ` +
585
+ `ledger/compact-runtime/onchain-runtime type your code expects and the version of the incoming data.`,
586
+ `Align the version of ${SOURCE_PACKAGES.ledger}-vN / ${SOURCE_PACKAGES.compactRuntime} / ` +
587
+ `${SOURCE_PACKAGES.onchainRuntime}-vN your dApp pulls in with the protocol version of the network ` +
588
+ `and indexer you are connecting to.`
589
+ ];
590
+ const formatMismatchBaseline = () => [
591
+ 'This error indicates malformed or truncated bytes — not necessarily a version mismatch.',
592
+ 'Verify the source produces canonical encoding (no double-encoding, no trailing bytes, no truncation).',
593
+ 'Check intermediate transports (HTTP gateways, GraphQL serialization) for byte corruption.'
594
+ ];
595
+ const unknownBaseline = () => [
596
+ 'Classification could not be determined from the error message.',
597
+ 'Inspect the underlying error (Caused by:) for context.',
598
+ 'If the cause looks version-related, align the underlying ledger / compact-runtime / onchain-runtime package versions across your dApp, the network, and the indexer.'
599
+ ];
600
+ const PER_SOURCE_HINT = {
601
+ ledger: `Each ledger type has a structural version tag (e.g. "contract-state[v6]") embedded in the serialized ` +
602
+ `payload. The dApp's installed ${SOURCE_PACKAGES.ledger}-vN binding expects a specific tag; ` +
603
+ `the data source produced a different one. Resolve by aligning the version on either end.`,
604
+ 'compact-runtime': `${SOURCE_PACKAGES.compactRuntime} depends on ${SOURCE_PACKAGES.onchainRuntime}-vN — ` +
605
+ `version drift in either propagates here. Verify the compactc compiler version used to build the ` +
606
+ `contract matches the runtime your dApp uses.`,
607
+ 'onchain-runtime': `Confirm ${SOURCE_PACKAGES.onchainRuntime}-vN installed in your dApp matches the contract operations ` +
608
+ `runtime in the target network. Structural tags (e.g. "state-value[vN]") may diverge from the npm major-version suffix.`
609
+ };
610
+ const buildMitigation = (classification, source) => {
611
+ switch (classification) {
612
+ case 'version-mismatch':
613
+ return [...versionMismatchBaseline(), PER_SOURCE_HINT[source]];
614
+ case 'format-mismatch':
615
+ return formatMismatchBaseline();
616
+ case 'unknown':
617
+ return [...unknownBaseline(), PER_SOURCE_HINT[source]];
618
+ }
619
+ };
620
+ /**
621
+ * Classify a deserialization error against the shared pattern table.
622
+ * Returns a fully-populated `DeserializationContext` ready to attach to a
623
+ * `DeserializationError`.
624
+ *
625
+ * Rules (spec §7.1):
626
+ * - First matching pattern wins.
627
+ * - `extracted.dataType` (when populated by a pattern) overrides `callSite.dataType`.
628
+ * - Mitigation is dispatched on `(classification, source)` (D12).
629
+ * - `extracted` is `undefined` (not `{}`) when no pattern populated it.
630
+ */
631
+ const classify = (callSite, cause) => {
632
+ const message = cause.message;
633
+ for (const entry of PATTERNS) {
634
+ const match = entry.regex.exec(message);
635
+ if (match === null)
636
+ continue;
637
+ const classification = entry.classification;
638
+ const direction = entry.inferDirection?.(match);
639
+ const extracted = entry.extract?.(match);
640
+ const dataType = extracted?.dataType ?? callSite.dataType;
641
+ const mitigation = buildMitigation(classification, callSite.source);
642
+ // Conditional spread: omit `extracted` from the resulting object when no
643
+ // pattern populated it. Avoids `extracted: undefined` (would break under
644
+ // exactOptionalPropertyTypes if ever enabled).
645
+ return {
646
+ dataType,
647
+ source: callSite.source,
648
+ caller: callSite.caller,
649
+ classification,
650
+ direction,
651
+ mitigation,
652
+ ...(callSite.details !== undefined ? { details: callSite.details } : {}),
653
+ ...(extracted !== undefined ? { extracted } : {})
654
+ };
655
+ }
656
+ return {
657
+ dataType: callSite.dataType,
658
+ source: callSite.source,
659
+ caller: callSite.caller,
660
+ classification: 'unknown',
661
+ ...(callSite.details !== undefined ? { details: callSite.details } : {}),
662
+ mitigation: buildMitigation('unknown', callSite.source)
663
+ };
664
+ };
665
+
666
+ /*
667
+ * This file is part of midnight-js.
668
+ * Copyright (C) Midnight Foundation
669
+ * SPDX-License-Identifier: Apache-2.0
670
+ * Licensed under the Apache License, Version 2.0 (the "License");
671
+ * You may not use this file except in compliance with the License.
672
+ * You may obtain a copy of the License at
673
+ * http://www.apache.org/licenses/LICENSE-2.0
674
+ * Unless required by applicable law or agreed to in writing, software
675
+ * distributed under the License is distributed on an "AS IS" BASIS,
676
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
677
+ * See the License for the specific language governing permissions and
678
+ * limitations under the License.
679
+ */
680
+ const formatExtracted = (e) => {
681
+ const parts = [];
682
+ if (e.dataType !== undefined)
683
+ parts.push(`dataType=${e.dataType}`);
684
+ if (e.expectedVersion !== undefined)
685
+ parts.push(`expected=${e.expectedVersion}`);
686
+ if (e.receivedVersion !== undefined)
687
+ parts.push(`got=${e.receivedVersion}`);
688
+ return parts.join(', ');
689
+ };
690
+ const formatMessage = (ctx) => {
691
+ const classificationLine = ` Classification: ${ctx.classification}` +
692
+ (ctx.direction !== undefined ? ` (direction: ${ctx.direction})` : '');
693
+ const lines = [
694
+ `Failed to deserialize ${ctx.dataType} (${ctx.source}).`,
695
+ ` Call site: ${ctx.caller}`,
696
+ classificationLine
697
+ ];
698
+ if (ctx.details !== undefined) {
699
+ const rendered = Object.entries(ctx.details).map(([key, value]) => `${key}=${value}`);
700
+ if (rendered.length > 0) {
701
+ lines.push(` Read: ${rendered.join(', ')}`);
702
+ }
703
+ }
704
+ if (ctx.extracted !== undefined) {
705
+ lines.push(` Extracted: ${formatExtracted(ctx.extracted)}`);
706
+ }
707
+ if (ctx.mitigation.length === 0) {
708
+ lines.push(' Mitigation: (none)');
709
+ }
710
+ else {
711
+ lines.push(' Mitigation:');
712
+ for (const hint of ctx.mitigation) {
713
+ lines.push(` - ${hint}`);
714
+ }
715
+ }
716
+ return lines.join('\n');
717
+ };
718
+ /**
719
+ * An error thrown by the deserialization wrappers when a ledger /
720
+ * compact-runtime / onchain-runtime `.deserialize`/`.decode` call fails.
721
+ * Carries structured context for diagnosis: data type, call site,
722
+ * classification, direction, mitigation.
723
+ */
724
+ class DeserializationError extends MidnightJsError {
725
+ code = UTILS_ERROR_CODES.DESERIALIZATION_FAILED;
726
+ category = UTILS_ERROR_CATEGORIES[UTILS_ERROR_CODES.DESERIALIZATION_FAILED];
727
+ context;
728
+ /**
729
+ * @param context Structured diagnostic context.
730
+ * @param cause Underlying error. Typed as `unknown` to match the
731
+ * `Error.cause` ECMA spec. Primary call sites (typed wrappers) always
732
+ * pass an `Error` via `withDeserializationContext`.
733
+ */
734
+ constructor(context, cause) {
735
+ super(formatMessage(context), cause === undefined ? undefined : { cause });
736
+ this.name = 'DeserializationError';
737
+ this.context = context;
738
+ }
739
+ }
740
+ /** Type guard for `DeserializationError`. */
741
+ const isDeserializationError = (e) => e instanceof DeserializationError;
742
+
743
+ /*
744
+ * This file is part of midnight-js.
745
+ * Copyright (C) Midnight Foundation
746
+ * SPDX-License-Identifier: Apache-2.0
747
+ * Licensed under the Apache License, Version 2.0 (the "License");
748
+ * You may not use this file except in compliance with the License.
749
+ * You may obtain a copy of the License at
750
+ * http://www.apache.org/licenses/LICENSE-2.0
751
+ * Unless required by applicable law or agreed to in writing, software
752
+ * distributed under the License is distributed on an "AS IS" BASIS,
753
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
754
+ * See the License for the specific language governing permissions and
755
+ * limitations under the License.
756
+ */
757
+ /**
758
+ * Wraps a synchronous deserialization call. Whatever `fn()` throws, the
759
+ * wrapper classifies it and re-throws a `DeserializationError` carrying
760
+ * structured context, with the original value on `cause`.
761
+ *
762
+ * A non-`Error` throw is classified on its string form rather than escaping
763
+ * unwrapped.
764
+ *
765
+ * SYNC-ONLY BY CONTRACT: if `fn()` returns a thenable the wrapper throws an
766
+ * `InvalidArgumentError`. The typed wrappers in `./typed-wrappers.ts` are the primary API;
767
+ * use this HOF directly only for ad-hoc deserialization sites not covered there.
768
+ *
769
+ * @throws {DeserializationError} When `fn()` throws anything at all.
770
+ * @throws {InvalidArgumentError} When `fn()` returns a thenable (sync-only violation).
771
+ *
772
+ * @see {@link ErrorVocabulary} for why a bare string throw is classified rather
773
+ * than re-thrown, and what the thenable check prevents.
774
+ *
775
+ * @example
776
+ * ```ts
777
+ * // Inside a typed wrapper:
778
+ * deserializeLedger9ContractState(buf, ctx) =>
779
+ * withDeserializationContext(callSite, () => LedgerContractState.deserialize(buf));
780
+ * ```
781
+ */
782
+ const withDeserializationContext = (callSite, fn) => {
783
+ let result;
784
+ try {
785
+ result = fn();
786
+ }
787
+ catch (cause) {
788
+ const classifiable = cause instanceof Error ? cause : new Error(String(cause));
789
+ throw new DeserializationError(classify(callSite, classifiable), cause);
790
+ }
791
+ if (result !== null &&
792
+ typeof result === 'object' &&
793
+ typeof result.then === 'function') {
794
+ throw new InvalidArgumentError(`withDeserializationContext is sync-only; received a thenable from ${callSite.caller}.`);
795
+ }
796
+ return result;
797
+ };
798
+
799
+ /*
800
+ * This file is part of midnight-js.
801
+ * Copyright (C) Midnight Foundation
802
+ * SPDX-License-Identifier: Apache-2.0
803
+ * Licensed under the Apache License, Version 2.0 (the "License");
804
+ * You may not use this file except in compliance with the License.
805
+ * You may obtain a copy of the License at
806
+ * http://www.apache.org/licenses/LICENSE-2.0
807
+ * Unless required by applicable law or agreed to in writing, software
808
+ * distributed under the License is distributed on an "AS IS" BASIS,
809
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
810
+ * See the License for the specific language governing permissions and
811
+ * limitations under the License.
812
+ */
813
+ /**
814
+ * Deserialize a ledger {@link LedgerContractState} from raw bytes.
815
+ *
816
+ * @throws {DeserializationError} On any underlying ledger deserialization
817
+ * failure. The error carries classification, direction inference, and
818
+ * actionable mitigation hints.
819
+ *
820
+ * @example
821
+ * ```ts
822
+ * const state = deserializeLedger9ContractState(buf, {
823
+ * caller: '@midnightntwrk/midnight-js-indexer-public-data-provider:queryContractState'
824
+ * });
825
+ * ```
826
+ *
827
+ * The `caller` should be fully qualified (`@scope/package:function`) — this
828
+ * convention is enforced across the codebase and surfaces in the rendered
829
+ * error message.
830
+ */
831
+ const deserializeLedger9ContractState = (bytes, ctx) => withDeserializationContext({
832
+ dataType: 'ContractState',
833
+ source: 'ledger',
834
+ caller: ctx.caller,
835
+ details: ctx.details
836
+ }, () => ContractState.deserialize(bytes));
837
+ /**
838
+ * Deserialize a compact-runtime {@link CompactContractState} from raw bytes.
839
+ *
840
+ * @throws {DeserializationError} On any underlying compact-runtime
841
+ * deserialization failure.
842
+ */
843
+ const deserializeLedger9CompactContractState = (bytes, ctx) => withDeserializationContext({
844
+ dataType: 'ContractState',
845
+ source: 'compact-runtime',
846
+ caller: ctx.caller,
847
+ details: ctx.details
848
+ }, () => ContractState$1.deserialize(bytes));
849
+ /**
850
+ * Deserialize a ledger {@link ZswapChainState} from raw bytes.
851
+ *
852
+ * @throws {DeserializationError} On any underlying ledger deserialization
853
+ * failure.
854
+ */
855
+ const deserializeLedger9ZswapChainState = (bytes, ctx) => withDeserializationContext({
856
+ dataType: 'ZswapChainState',
857
+ source: 'ledger',
858
+ caller: ctx.caller,
859
+ details: ctx.details
860
+ }, () => ZswapChainState.deserialize(bytes));
861
+ /**
862
+ * Wraps the bytes of a finalized ledger transaction of the given era in a
863
+ * {@link LedgerTransaction} handle of that era. Only the header is checked;
864
+ * the caller decodes the handle with its own ledger copy, so reading a v8
865
+ * record does not load the v8 runtime.
866
+ *
867
+ * @param era The ledger era that wrote the bytes. Never derived from the bytes.
868
+ * @param bytes The serialized finalized transaction.
869
+ * @param ctx The call site, named on a refusal.
870
+ * @returns A finalized handle of `era`.
871
+ * @throws {DeserializationError} If the bytes do not start with the header the
872
+ * ledger of `era` writes for a finalized transaction, including bytes written
873
+ * by the other era.
874
+ * @throws {UnknownLedgerEraError} If `era` is not a ledger era.
875
+ */
876
+ const deserializeLedgerTransaction = async (era, bytes, ctx) => {
877
+ if (!LEDGER_ERAS.includes(era)) {
878
+ throw new UnknownLedgerEraError(era);
879
+ }
880
+ return withDeserializationContext({
881
+ dataType: 'LedgerTransaction',
882
+ source: 'ledger',
883
+ caller: ctx.caller,
884
+ details: ctx.details
885
+ }, () => LedgerTransaction.fromBytes(era, 'Finalized', bytes));
886
+ };
887
+ /**
888
+ * Deserialize ledger {@link LedgerParameters} from raw bytes.
889
+ *
890
+ * @throws {DeserializationError} On any underlying ledger deserialization
891
+ * failure.
892
+ */
893
+ const deserializeLedger9Parameters = (bytes, ctx) => withDeserializationContext({
894
+ dataType: 'LedgerParameters',
895
+ source: 'ledger',
896
+ caller: ctx.caller,
897
+ details: ctx.details
898
+ }, () => LedgerParameters.deserialize(bytes));
899
+ /**
900
+ * Decode an onchain-runtime {@link LedgerStateValue} from its
901
+ * {@link EncodedStateValue} representation (a tagged union, NOT a byte
902
+ * buffer — `StateValue.decode` operates on the structured encoding produced
903
+ * by `StateValue.encode()`).
904
+ *
905
+ * Source attribution is `onchain-runtime` (per D8) even though the type
906
+ * is re-exported through the `ledger` sub-path — mitigation hints point
907
+ * to the underlying runtime package.
908
+ *
909
+ * @throws {DeserializationError} On any underlying onchain-runtime decode
910
+ * failure.
911
+ */
912
+ const decodeLedger9StateValue = (encoded, ctx) => withDeserializationContext({
913
+ dataType: 'StateValue',
914
+ source: 'onchain-runtime',
915
+ caller: ctx.caller,
916
+ details: ctx.details
917
+ }, () => StateValue.decode(encoded));
918
+
919
+ /*
920
+ * This file is part of midnight-js.
921
+ * Copyright (C) Midnight Foundation
922
+ * SPDX-License-Identifier: Apache-2.0
923
+ * Licensed under the Apache License, Version 2.0 (the "License");
924
+ * You may not use this file except in compliance with the License.
925
+ * You may obtain a copy of the License at
926
+ * http://www.apache.org/licenses/LICENSE-2.0
927
+ * Unless required by applicable law or agreed to in writing, software
928
+ * distributed under the License is distributed on an "AS IS" BASIS,
929
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
930
+ * See the License for the specific language governing permissions and
931
+ * limitations under the License.
932
+ */
933
+ /**
934
+ * A regular expression that captures a hex-encoded string.
935
+ *
936
+ * @remarks
937
+ * The regular expression captures characters from the source string sequentially, and will build a
938
+ * `RegExpExecArray` object with captured groups described by {@link ParsedHexString}. These
939
+ * groups capture the running sequence of _whole_ bytes (i.e., two valid hexadecimal characters),
940
+ * and then any remaining sequence of characters that are not valid hexadecimal characters, or
941
+ * incomplete bytes.
942
+ *
943
+ * @internal
944
+ */
945
+ const HEX_STRING_REGEXP = /^(?<prefix>(0x)?)(?<byteChars>([0-9A-Fa-f]{2})*)(?<incompleteChars>.*)$/;
946
+ /**
947
+ * Parses a string as a hex-encoded string.
948
+ *
949
+ * @param source The source string to parse.
950
+ * @returns A {@link ParsedHexString} describing the parsed elements of `source`.
951
+ *
952
+ * @example
953
+ * parseHex('Hello') =>
954
+ * {
955
+ * hasPrefix: false,
956
+ * incompleteChars: 'Hello'
957
+ * }
958
+ *
959
+ * @example
960
+ * parseHex('ab12e') =>
961
+ * {
962
+ * hasPrefix: false,
963
+ * byteChars: 'ab12'
964
+ * incompleteChars: 'e'
965
+ * }
966
+ *
967
+ * @example
968
+ * parseHex('0xab12') =>
969
+ * {
970
+ * hasPrefix: true,
971
+ * byteChars: 'ab12'
972
+ * incompleteChars: ''
973
+ * }
974
+ */
975
+ const parseHex = (source) => {
976
+ const groups = HEX_STRING_REGEXP.exec(source)?.groups;
977
+ return {
978
+ hasPrefix: groups.prefix === '0x',
979
+ byteChars: groups.byteChars,
980
+ incompleteChars: groups.incompleteChars
981
+ };
982
+ };
983
+ /**
984
+ * Converts a byte string into a hex string.
985
+ *
986
+ * @param bytes The byte string to encode.
987
+ */
988
+ const toHex = (bytes) => Buffer.from(bytes).toString('hex');
989
+ /**
990
+ * Converts a hex string into a byte string.
991
+ *
992
+ * @param str The hex string to decode.
993
+ */
994
+ const fromHex = (str) => Buffer.from(str, 'hex');
995
+ /**
996
+ * Determines if a string represents a hex-encoded sequence of bytes.
997
+ *
998
+ * @param source The source string.
999
+ * @param byteLen An optional number of bytes that `source` should represent. If not specified
1000
+ * then any number of bytes can be represented by `source`.
1001
+ * @returns `true` if the `source` string is parsable as a hex-string, of non-zero length, and
1002
+ * of the optional byte length of `byteLen`; otherwise `false`.
1003
+ */
1004
+ const isHex = (source, byteLen) => {
1005
+ if (!source || (byteLen !== undefined && byteLen <= 0)) {
1006
+ return false;
1007
+ }
1008
+ const parsedHex = parseHex(source);
1009
+ const validByteLen = byteLen
1010
+ ? parsedHex.byteChars.length / 2 === byteLen // `byteLen` number of bytes
1011
+ : parsedHex.byteChars.length > 0; // any number of bytes
1012
+ return validByteLen && !parsedHex.incompleteChars;
1013
+ };
1014
+ /**
1015
+ * Asserts that a string represents a hex-encoded sequence of bytes.
1016
+ *
1017
+ * @param source The source string.
1018
+ * @param byteLen An optional number of bytes that `source` should represent. If not specified
1019
+ * then any number of bytes can be represented by `source`.
1020
+ *
1021
+ * @throws `InvalidArgumentError`
1022
+ * `byteLen` is \<= zero. Valid hex-strings will be required to have at least one byte.
1023
+ * @throws `InvalidArgumentError`
1024
+ * `source` is not a hex-encoded string because it:
1025
+ * - is empty,
1026
+ * - contains invalid or incomplete characters, or
1027
+ * - does not represent `byteLen` bytes.
1028
+ */
1029
+ function assertIsHex(source, byteLen) {
1030
+ if (!source) {
1031
+ throw new InvalidArgumentError('Input string must have non-zero length.');
1032
+ }
1033
+ if (byteLen !== undefined && byteLen <= 0) {
1034
+ throw new InvalidArgumentError('Expected byte length must be greater than zero.');
1035
+ }
1036
+ const parsedHex = parseHex(source);
1037
+ if (parsedHex.incompleteChars) {
1038
+ if (parsedHex.incompleteChars.length % 2 > 0) {
1039
+ throw new InvalidArgumentError(`The last byte of input string '${source}' is incomplete.`);
1040
+ }
1041
+ const invalidCharPos = parsedHex.byteChars.length + (parsedHex.hasPrefix ? 2 : 0);
1042
+ throw new InvalidArgumentError(`Invalid hex-digit '${source[invalidCharPos]}' found in input string at index ${invalidCharPos}.`);
1043
+ }
1044
+ if (!parsedHex.byteChars) {
1045
+ throw new InvalidArgumentError(`Input string '${source}' is not a valid hex-string.`);
1046
+ }
1047
+ if (byteLen) {
1048
+ const actualByteLen = parsedHex.byteChars.length / 2;
1049
+ if (byteLen !== actualByteLen) {
1050
+ throw new InvalidArgumentError(`Expected an input string with byte length of ${byteLen}, got ${actualByteLen}.`);
1051
+ }
1052
+ }
1053
+ }
1054
+ /**
1055
+ * Parses a coin public key (in Bech32m format or hex) into a hex formatted string.
1056
+ *
1057
+ * @param possibleBech32 The input string, which can be a Bech32m-encoded coin public key or a hex string.
1058
+ * @param zswapNetworkId The network ID used for decoding the Bech32m formatted string.
1059
+ * @returns The hex string representation of the coin public key.
1060
+ *
1061
+ * @throws `Error`
1062
+ * If the input string is not a valid hex string or a valid Bech32m-encoded coin public key.
1063
+ */
1064
+ const parseCoinPublicKeyToHex = (possibleBech32, zswapNetworkId) => {
1065
+ if (isHex(possibleBech32))
1066
+ return possibleBech32;
1067
+ const parsedBech32 = MidnightBech32m.parse(possibleBech32); // Ensure compatibility
1068
+ const decoded = ShieldedCoinPublicKey.codec.decode(zswapNetworkId, parsedBech32);
1069
+ return Buffer.from(decoded.data).toString('hex');
1070
+ };
1071
+ /**
1072
+ * Parses an encryption public key (in Bech32m or hex format) into a hex formatted string.
1073
+ *
1074
+ * @param possibleBech32 The input string, which can be a Bech32m-encoded encryption public key or a hex string.
1075
+ * @param zswapNetworkId The network ID used for decoding the Bech32m formatted string.
1076
+ * @returns The hex string representation of the encryption public key.
1077
+ *
1078
+ * @throws `Error`
1079
+ * If the input string is not a valid hex string or a valid Bech32m-encoded encryption public key.
1080
+ */
1081
+ const parseEncPublicKeyToHex = (possibleBech32, zswapNetworkId) => {
1082
+ if (isHex(possibleBech32))
1083
+ return possibleBech32;
1084
+ const parsedBech32 = MidnightBech32m.parse(possibleBech32);
1085
+ const decoded = ShieldedEncryptionPublicKey.codec.decode(zswapNetworkId, parsedBech32);
1086
+ return Buffer.from(decoded.data).toString('hex');
1087
+ };
1088
+
1089
+ /*
1090
+ * This file is part of midnight-js.
1091
+ * Copyright (C) Midnight Foundation
1092
+ * SPDX-License-Identifier: Apache-2.0
1093
+ * Licensed under the Apache License, Version 2.0 (the "License");
1094
+ * You may not use this file except in compliance with the License.
1095
+ * You may obtain a copy of the License at
1096
+ * http://www.apache.org/licenses/LICENSE-2.0
1097
+ * Unless required by applicable law or agreed to in writing, software
1098
+ * distributed under the License is distributed on an "AS IS" BASIS,
1099
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1100
+ * See the License for the specific language governing permissions and
1101
+ * limitations under the License.
1102
+ */
1103
+ // The `./version` leaf subpath, not the package root: the root barrel re-exports the
1104
+ // ledger/compact-js/onchain-runtime namespaces, which every `utils` consumer would then pull in.
1105
+ // The tags are `LEDGER_STATE_TAGS` from `protocol`, the one table every package reads. The lookup is
1106
+ // keyed by era and searched, never keyed by the network-supplied tag, so an unexpected tag cannot
1107
+ // resolve through `Object.prototype`.
1108
+ /**
1109
+ * Reads which ledger runtime wrote a serialized set of ledger parameters, from the version tag in
1110
+ * front of the body — without deserializing the body.
1111
+ *
1112
+ * The sibling of {@link ledgerVersionOfContractState}, and it exists for the same reason: the
1113
+ * indexer serves ledger parameters PER BLOCK, they are era-tagged, and each era's deserializer
1114
+ * refuses the other era's bytes on the header tag. A reader that decodes them with a fixed era's
1115
+ * runtime therefore works on one side of a fork and fails on the other — with a raw deserialization
1116
+ * failure that names neither the era nor the field.
1117
+ *
1118
+ * The tag is network-supplied input and is never the authority on the body; the node remains the
1119
+ * sole authority on what the bytes decode to. What this check buys is a cheap, early rejection of
1120
+ * anything that is not a parameter set from a supported runtime, before those bytes reach a
1121
+ * decoder — and, for a caller that holds two runtimes, the answer to which one to hand them to.
1122
+ *
1123
+ * Supported public API, deliberately: a caller refused a pre-fork block's parameters by an era-fixed
1124
+ * read path has to decode them itself, and needs this to pick the runtime to decode them with.
1125
+ *
1126
+ * @param raw The serialized ledger parameters, as the network returned it.
1127
+ * @returns The ledger era whose runtime wrote `raw`.
1128
+ * @throws TagParseError when there is no well-formed `namespace:version:` tag prefix in the first
1129
+ * 64 bytes, or when the tag is not one of the supported ledger-parameters version tags.
1130
+ */
1131
+ const ledgerVersionOfLedgerParameters = (raw) => {
1132
+ const { tag } = parseSerializedTag(raw);
1133
+ const ledgerVersion = LEDGER_ERAS.find((era) => LEDGER_STATE_TAGS.LedgerParameters[era] === tag);
1134
+ if (ledgerVersion === undefined) {
1135
+ // Never echo the observed tag: it is network-supplied and validated only against a character
1136
+ // set, so embedding it verbatim puts arbitrary text into this message.
1137
+ throw new TagParseError('The serialized value does not start with a ledger-parameters version tag from a supported ledger runtime. ' +
1138
+ 'Verify the payload came from the `ledgerParameters` field of a block and not from another serialized type.');
1139
+ }
1140
+ return ledgerVersion;
1141
+ };
1142
+
1143
+ /*
1144
+ * This file is part of midnight-js.
1145
+ * Copyright (C) Midnight Foundation
1146
+ * SPDX-License-Identifier: Apache-2.0
1147
+ * Licensed under the Apache License, Version 2.0 (the "License");
1148
+ * You may not use this file except in compliance with the License.
1149
+ * You may obtain a copy of the License at
1150
+ * http://www.apache.org/licenses/LICENSE-2.0
1151
+ * Unless required by applicable law or agreed to in writing, software
1152
+ * distributed under the License is distributed on an "AS IS" BASIS,
1153
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1154
+ * See the License for the specific language governing permissions and
1155
+ * limitations under the License.
1156
+ */
1157
+ const show = (value) => {
1158
+ if (typeof value === 'string')
1159
+ return JSON.stringify(value);
1160
+ if (typeof value === 'object' && value !== null)
1161
+ return 'an object';
1162
+ return String(value);
1163
+ };
1164
+ /**
1165
+ * Checks a {@link MidnightConfig} before any work is done with it.
1166
+ *
1167
+ * @param config The config to check; `undefined` or `null` when a caller did not pass one.
1168
+ * @param source Where the config was read from, named in the error.
1169
+ * @throws ConfigurationError If `config` is missing.
1170
+ * @throws InvalidArgumentError If `config.networkId` is not a non-empty string
1171
+ * without surrounding whitespace, or if `config.ttlSeconds` is not a positive whole number, or is too large for the
1172
+ * expiry to be a valid `Date`.
1173
+ */
1174
+ function assertValidMidnightConfig(config, source = 'providers.config') {
1175
+ if (typeof config !== 'object' || config === null) {
1176
+ throw new ConfigurationError(`${source} is missing. Pass { networkId, ttlSeconds } as ${source}.`);
1177
+ }
1178
+ const { networkId, ttlSeconds } = config;
1179
+ if (typeof networkId !== 'string' || networkId.length === 0 || networkId.trim() !== networkId) {
1180
+ throw new InvalidArgumentError(`${source}.networkId must be a non-empty string without surrounding whitespace, got ${show(networkId)}.`);
1181
+ }
1182
+ if (!Number.isSafeInteger(ttlSeconds) ||
1183
+ ttlSeconds < 1 ||
1184
+ Number.isNaN(new Date(Date.now() + ttlSeconds * 1000).getTime())) {
1185
+ throw new InvalidArgumentError(`${source}.ttlSeconds must be a positive whole number of seconds, got ${show(ttlSeconds)}.`);
1186
+ }
1187
+ }
1188
+ /**
1189
+ * The expiry for an intent built now: the current time plus `config.ttlSeconds`.
1190
+ *
1191
+ * @param config The config whose `ttlSeconds` is applied.
1192
+ * @throws ConfigurationError, InvalidArgumentError As {@link assertValidMidnightConfig}.
1193
+ */
1194
+ const intentTtl = (config) => {
1195
+ assertValidMidnightConfig(config);
1196
+ return new Date(Date.now() + config.ttlSeconds * 1000);
1197
+ };
1198
+
1199
+ /*
1200
+ * This file is part of midnight-js.
1201
+ * Copyright (C) Midnight Foundation
1202
+ * SPDX-License-Identifier: Apache-2.0
1203
+ * Licensed under the Apache License, Version 2.0 (the "License");
1204
+ * You may not use this file except in compliance with the License.
1205
+ * You may obtain a copy of the License at
1206
+ * http://www.apache.org/licenses/LICENSE-2.0
1207
+ * Unless required by applicable law or agreed to in writing, software
1208
+ * distributed under the License is distributed on an "AS IS" BASIS,
1209
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1210
+ * See the License for the specific language governing permissions and
1211
+ * limitations under the License.
1212
+ */
1213
+ const REQUIRED_PROVIDERS = [
1214
+ 'privateStateProvider',
1215
+ 'publicDataProvider',
1216
+ 'zkConfigProvider',
1217
+ 'proofProvider',
1218
+ 'walletProvider',
1219
+ 'midnightProvider'
1220
+ ];
1221
+ /**
1222
+ * Checks a provider set the dApp built and returns it unchanged, so a broken set fails at
1223
+ * application start instead of at the first operation.
1224
+ *
1225
+ * @param providers The provider set to check.
1226
+ * @returns The same `providers` object.
1227
+ * @throws ConfigurationError If a required provider is missing, or as {@link assertValidMidnightConfig}.
1228
+ * @throws InvalidArgumentError As {@link assertValidMidnightConfig}.
1229
+ */
1230
+ const createMidnightProviders = (providers) => {
1231
+ for (const key of REQUIRED_PROVIDERS) {
1232
+ if (typeof providers[key] !== 'object' || providers[key] === null) {
1233
+ throw new ConfigurationError(`providers.${key} is missing.`);
1234
+ }
1235
+ }
1236
+ assertValidMidnightConfig(providers.config);
1237
+ return providers;
1238
+ };
1239
+
1240
+ /*
1241
+ * This file is part of midnight-js.
1242
+ * Copyright (C) Midnight Foundation
1243
+ * SPDX-License-Identifier: Apache-2.0
1244
+ * Licensed under the Apache License, Version 2.0 (the "License");
1245
+ * You may not use this file except in compliance with the License.
1246
+ * You may obtain a copy of the License at
1247
+ * http://www.apache.org/licenses/LICENSE-2.0
1248
+ * Unless required by applicable law or agreed to in writing, software
1249
+ * distributed under the License is distributed on an "AS IS" BASIS,
1250
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1251
+ * See the License for the specific language governing permissions and
1252
+ * limitations under the License.
1253
+ */
1254
+ const withProjectId = (url, projectId) => `${url}?project_id=${encodeURIComponent(projectId)}`;
1255
+ const blockfrostNetwork = (networkId, projectId, urls) => {
1256
+ const trimmed = projectId.trim();
1257
+ if (trimmed === '' || trimmed !== projectId) {
1258
+ const got = trimmed === '' ? 'an empty string' : 'a token with whitespace around it';
1259
+ throw new InvalidArgumentError(`The ${networkId} endpoints need a Blockfrost project token for a Midnight ${networkId} project, got ${got}.`);
1260
+ }
1261
+ return {
1262
+ networkId,
1263
+ indexer: {
1264
+ queryURL: withProjectId(urls.queryURL, projectId),
1265
+ subscriptionURL: withProjectId(urls.subscriptionURL, projectId)
1266
+ },
1267
+ nodeURL: withProjectId(urls.nodeURL, projectId),
1268
+ nodeWsURL: withProjectId(urls.nodeWsURL, projectId)
1269
+ };
1270
+ };
1271
+ /**
1272
+ * Public endpoints of the Midnight networks. Call the network to get its {@link MidnightNetwork}.
1273
+ *
1274
+ * `preview` is hosted by Midnight. `preprod` and `mainnet` are served by Blockfrost, so they take
1275
+ * a Blockfrost project token for that network and put it on every URL as `?project_id=<token>`.
1276
+ * The URLs then carry the token: remove it before you log them.
1277
+ *
1278
+ * These are defaults that can change between releases. To use other endpoints, pass your own
1279
+ * {@link MidnightNetwork}. A browser dApp with a DApp Connector wallet takes its endpoints from the wallet
1280
+ * with `dappConnectorNetwork` from `@midnightntwrk/midnight-js-dapp-connector-proof-provider`.
1281
+ *
1282
+ * @example
1283
+ * ```typescript
1284
+ * const preview = networks.preview();
1285
+ * const mainnet = networks.mainnet(blockfrostMainnetProjectId);
1286
+ * ```
1287
+ */
1288
+ const networks = {
1289
+ preview: () => ({
1290
+ networkId: 'preview',
1291
+ indexer: {
1292
+ queryURL: 'https://indexer.preview.midnight.network/api/v4/graphql',
1293
+ subscriptionURL: 'wss://indexer.preview.midnight.network/api/v4/graphql/ws'
1294
+ },
1295
+ nodeURL: 'https://rpc.preview.midnight.network',
1296
+ nodeWsURL: 'wss://rpc.preview.midnight.network'
1297
+ }),
1298
+ /**
1299
+ * @throws InvalidArgumentError If `blockfrostProjectId` is empty or has whitespace around it.
1300
+ */
1301
+ preprod: (blockfrostProjectId) => blockfrostNetwork('preprod', blockfrostProjectId, {
1302
+ queryURL: 'https://midnight-preprod.blockfrost.io/api/v0',
1303
+ subscriptionURL: 'wss://midnight-preprod.blockfrost.io/api/v0/ws',
1304
+ nodeURL: 'https://rpc.midnight-preprod.blockfrost.io',
1305
+ nodeWsURL: 'wss://rpc.midnight-preprod.blockfrost.io'
1306
+ }),
1307
+ /**
1308
+ * @throws InvalidArgumentError If `blockfrostProjectId` is empty or has whitespace around it.
1309
+ */
1310
+ mainnet: (blockfrostProjectId) => blockfrostNetwork('mainnet', blockfrostProjectId, {
1311
+ queryURL: 'https://midnight-mainnet.blockfrost.io/api/v0',
1312
+ subscriptionURL: 'wss://midnight-mainnet.blockfrost.io/api/v0/ws',
1313
+ nodeURL: 'https://rpc.midnight-mainnet.blockfrost.io',
1314
+ nodeWsURL: 'wss://rpc.midnight-mainnet.blockfrost.io'
1315
+ })
1316
+ };
1317
+
1318
+ /*
1319
+ * This file is part of midnight-js.
1320
+ * Copyright (C) Midnight Foundation
1321
+ * SPDX-License-Identifier: Apache-2.0
1322
+ * Licensed under the Apache License, Version 2.0 (the "License");
1323
+ * You may not use this file except in compliance with the License.
1324
+ * You may obtain a copy of the License at
1325
+ * http://www.apache.org/licenses/LICENSE-2.0
1326
+ * Unless required by applicable law or agreed to in writing, software
1327
+ * distributed under the License is distributed on an "AS IS" BASIS,
1328
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1329
+ * See the License for the specific language governing permissions and
1330
+ * limitations under the License.
1331
+ */
1332
+ const MIN_PASSWORD_LENGTH = 16;
1333
+ const MIN_CHARACTER_CLASSES = 3;
1334
+ const MAX_CONSECUTIVE_REPEATED = 3;
1335
+ const MIN_SEQUENTIAL_LENGTH = 4;
1336
+ /**
1337
+ * Thrown when a password does not satisfy the strength policy applied to
1338
+ * private storage and export/import operations.
1339
+ */
1340
+ class PasswordValidationError extends MidnightJsError {
1341
+ reason;
1342
+ code = UTILS_ERROR_CODES.PASSWORD_INVALID;
1343
+ category = UTILS_ERROR_CATEGORIES[UTILS_ERROR_CODES.PASSWORD_INVALID];
1344
+ constructor(message, reason) {
1345
+ super(message);
1346
+ this.reason = reason;
1347
+ this.name = 'PasswordValidationError';
1348
+ }
1349
+ }
1350
+ const countCharacterClasses = (password) => {
1351
+ let count = 0;
1352
+ if (/[a-z]/.test(password))
1353
+ count++;
1354
+ if (/[A-Z]/.test(password))
1355
+ count++;
1356
+ if (/[0-9]/.test(password))
1357
+ count++;
1358
+ if (/[^a-zA-Z0-9]/.test(password))
1359
+ count++;
1360
+ return count;
1361
+ };
1362
+ const hasRepeatedCharacters = (password) => {
1363
+ let consecutiveCount = 1;
1364
+ for (let i = 1; i < password.length; i++) {
1365
+ if (password[i] === password[i - 1]) {
1366
+ consecutiveCount++;
1367
+ if (consecutiveCount > MAX_CONSECUTIVE_REPEATED) {
1368
+ return true;
1369
+ }
1370
+ }
1371
+ else {
1372
+ consecutiveCount = 1;
1373
+ }
1374
+ }
1375
+ return false;
1376
+ };
1377
+ const hasSequentialPattern = (password) => {
1378
+ const lowerPassword = password.toLowerCase();
1379
+ for (let i = 0; i <= lowerPassword.length - MIN_SEQUENTIAL_LENGTH; i++) {
1380
+ let ascendingCount = 1;
1381
+ let descendingCount = 1;
1382
+ for (let j = 1; j < MIN_SEQUENTIAL_LENGTH; j++) {
1383
+ const currentCode = lowerPassword.charCodeAt(i + j);
1384
+ const prevCode = lowerPassword.charCodeAt(i + j - 1);
1385
+ if (currentCode === prevCode + 1) {
1386
+ ascendingCount++;
1387
+ }
1388
+ else {
1389
+ ascendingCount = 1;
1390
+ }
1391
+ if (currentCode === prevCode - 1) {
1392
+ descendingCount++;
1393
+ }
1394
+ else {
1395
+ descendingCount = 1;
1396
+ }
1397
+ if (ascendingCount >= MIN_SEQUENTIAL_LENGTH || descendingCount >= MIN_SEQUENTIAL_LENGTH) {
1398
+ return true;
1399
+ }
1400
+ }
1401
+ }
1402
+ return false;
1403
+ };
1404
+ /**
1405
+ * Shared password strength policy for private storage and export/import operations.
1406
+ * Throws {@link PasswordValidationError} on the first violated rule.
1407
+ */
1408
+ const validatePassword = (password) => {
1409
+ if (!password) {
1410
+ throw new PasswordValidationError('Password is required for private state encryption.\n' +
1411
+ 'Please provide a password via privateStoragePasswordProvider in the configuration.', 'missing');
1412
+ }
1413
+ if (password.length < MIN_PASSWORD_LENGTH) {
1414
+ throw new PasswordValidationError(`Password is shorter than ${MIN_PASSWORD_LENGTH} characters`, 'too_short');
1415
+ }
1416
+ if (hasRepeatedCharacters(password)) {
1417
+ throw new PasswordValidationError(`Password contains too many repeated characters (more than ${MAX_CONSECUTIVE_REPEATED} identical in a row)`, 'repeated_characters');
1418
+ }
1419
+ const characterClasses = countCharacterClasses(password);
1420
+ if (characterClasses < MIN_CHARACTER_CLASSES) {
1421
+ throw new PasswordValidationError(`Password must contain at least ${MIN_CHARACTER_CLASSES} of: uppercase letters, lowercase letters, digits, special characters. Found: ${characterClasses}`, 'insufficient_classes');
1422
+ }
1423
+ if (hasSequentialPattern(password)) {
1424
+ throw new PasswordValidationError("Password contains sequential patterns (e.g., '1234', 'abcd'). Use a more random password", 'sequential_pattern');
1425
+ }
1426
+ };
1427
+
1428
+ /*
1429
+ * This file is part of midnight-js.
1430
+ * Copyright (C) Midnight Foundation
1431
+ * SPDX-License-Identifier: Apache-2.0
1432
+ * Licensed under the Apache License, Version 2.0 (the "License");
1433
+ * You may not use this file except in compliance with the License.
1434
+ * You may obtain a copy of the License at
1435
+ * http://www.apache.org/licenses/LICENSE-2.0
1436
+ * Unless required by applicable law or agreed to in writing, software
1437
+ * distributed under the License is distributed on an "AS IS" BASIS,
1438
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1439
+ * See the License for the specific language governing permissions and
1440
+ * limitations under the License.
1441
+ */
1442
+ const MAX_SAFE_NAME_LENGTH = 255;
1443
+ const SAFE_NAME_PATTERN = /^[a-zA-Z0-9._-]+$/;
1444
+ const SEMVER_PATTERN = /^\d+\.\d+\.\d+(?:-[A-Za-z0-9._-]+)?$/;
1445
+ const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
1446
+ const INSECURE_SCHEMES = new Set(['http:', 'ws:']);
1447
+ /**
1448
+ * Asserts that `name` is safe to use as a single path segment or URL path
1449
+ * component. Rejects traversal payloads (`.`, `..`, separators), URL-encoded
1450
+ * characters, null bytes, whitespace, empty strings, and names longer than
1451
+ * {@link MAX_SAFE_NAME_LENGTH}.
1452
+ *
1453
+ * @param name The value to validate.
1454
+ * @param label Human-readable name of the parameter (for error messages).
1455
+ * @throws InvalidArgumentError if `name` fails validation.
1456
+ */
1457
+ function assertSafeName(name, label) {
1458
+ if (typeof name !== 'string' || name.length === 0 || name.length > MAX_SAFE_NAME_LENGTH) {
1459
+ throw new InvalidArgumentError(`Invalid ${label}: ${JSON.stringify(name)}`);
1460
+ }
1461
+ if (name === '.' || name === '..') {
1462
+ throw new InvalidArgumentError(`Invalid ${label}: ${JSON.stringify(name)}`);
1463
+ }
1464
+ if (!SAFE_NAME_PATTERN.test(name)) {
1465
+ throw new InvalidArgumentError(`Invalid ${label}: ${JSON.stringify(name)}`);
1466
+ }
1467
+ }
1468
+ /**
1469
+ * Asserts that `version` is a valid SemVer-style version string of the shape
1470
+ * `MAJOR.MINOR.PATCH` with an optional pre-release suffix
1471
+ * (`-[A-Za-z0-9._-]+`). Build metadata (`+...`) is intentionally not
1472
+ * supported because compactc releases do not use it.
1473
+ *
1474
+ * @param version The version string to validate.
1475
+ * @param label Human-readable name of the parameter (for error messages).
1476
+ * @throws InvalidArgumentError if `version` is not SemVer-shaped.
1477
+ */
1478
+ function assertSemVer(version, label) {
1479
+ if (typeof version !== 'string' || version.length === 0 || version.length > MAX_SAFE_NAME_LENGTH) {
1480
+ throw new InvalidArgumentError(`Invalid ${label}: ${JSON.stringify(version)}`);
1481
+ }
1482
+ if (!SEMVER_PATTERN.test(version)) {
1483
+ throw new InvalidArgumentError(`Invalid ${label}: ${JSON.stringify(version)}`);
1484
+ }
1485
+ }
1486
+ /**
1487
+ * Emits a `console.warn` when `url` uses an unencrypted scheme (`http:` or `ws:`)
1488
+ * targeting a non-loopback host. No-op for encrypted schemes (`https:`, `wss:`),
1489
+ * other schemes, and unparseable input.
1490
+ *
1491
+ * Intended to be called once at provider-factory construction time so
1492
+ * misconfigured remote endpoints surface immediately rather than after sensitive
1493
+ * payloads are transmitted in clear text. As a diagnostic helper it never throws —
1494
+ * an unparseable URL will produce errors through other channels (the protocol
1495
+ * checks at every call site already throw `InvalidProtocolSchemeError`), and
1496
+ * crashing the factory from a warning helper would be worse than silence.
1497
+ *
1498
+ * @param url An absolute URL string to inspect (e.g. `https://indexer.example/graphql`).
1499
+ * @param label Human-readable label used in the warning (e.g. "indexer query URL").
1500
+ */
1501
+ function warnIfInsecureRemoteUrl(url, label) {
1502
+ let parsed;
1503
+ try {
1504
+ parsed = new URL(url);
1505
+ }
1506
+ catch {
1507
+ return;
1508
+ }
1509
+ if (!INSECURE_SCHEMES.has(parsed.protocol)) {
1510
+ return;
1511
+ }
1512
+ if (LOOPBACK_HOSTNAMES.has(parsed.hostname)) {
1513
+ return;
1514
+ }
1515
+ const scheme = parsed.protocol.replace(/:$/, '');
1516
+ const secureReplacement = scheme === 'http' ? 'https://' : 'wss://';
1517
+ console.warn(`midnight-js: ${label} uses unencrypted ${scheme}:// for non-loopback host '${parsed.hostname}'; ` +
1518
+ `sensitive data may be transmitted in clear text. Use ${secureReplacement} in production.`);
1519
+ }
1520
+
1521
+ /*
1522
+ * This file is part of midnight-js.
1523
+ * Copyright (C) Midnight Foundation
1524
+ * SPDX-License-Identifier: Apache-2.0
1525
+ * Licensed under the Apache License, Version 2.0 (the "License");
1526
+ * You may not use this file except in compliance with the License.
1527
+ * You may obtain a copy of the License at
1528
+ * http://www.apache.org/licenses/LICENSE-2.0
1529
+ * Unless required by applicable law or agreed to in writing, software
1530
+ * distributed under the License is distributed on an "AS IS" BASIS,
1531
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1532
+ * See the License for the specific language governing permissions and
1533
+ * limitations under the License.
1534
+ */
1535
+ const SIGNING_KEY_HEX = /^[0-9a-fA-F]{64}$/;
1536
+ const SIGNING_KEY_KINDS = ['schnorr', 'ecdsa'];
1537
+ /**
1538
+ * Determines whether `value` is a structurally valid signing key of the shape
1539
+ * `{ tag: 'schnorr' | 'ecdsa', value: <hex> }`, where `value` is a 32-byte key
1540
+ * written as exactly 64 lowercase-or-uppercase hex characters.
1541
+ *
1542
+ * Pure predicate (never throws) so callers can attach their own domain error.
1543
+ *
1544
+ * @param value The value to validate (typically a parsed import payload entry).
1545
+ * @returns `true` if `value` matches the structured signing-key shape.
1546
+ */
1547
+ const isValidSigningKey = (value) => {
1548
+ if (typeof value !== 'object' || value === null) {
1549
+ return false;
1550
+ }
1551
+ const candidate = value;
1552
+ return typeof candidate.tag === 'string'
1553
+ && SIGNING_KEY_KINDS.includes(candidate.tag)
1554
+ && typeof candidate.value === 'string'
1555
+ && SIGNING_KEY_HEX.test(candidate.value);
1556
+ };
1557
+
1558
+ /*
1559
+ * This file is part of midnight-js.
1560
+ * Copyright (C) Midnight Foundation
1561
+ * SPDX-License-Identifier: Apache-2.0
1562
+ * Licensed under the Apache License, Version 2.0 (the "License");
1563
+ * You may not use this file except in compliance with the License.
1564
+ * You may obtain a copy of the License at
1565
+ * http://www.apache.org/licenses/LICENSE-2.0
1566
+ * Unless required by applicable law or agreed to in writing, software
1567
+ * distributed under the License is distributed on an "AS IS" BASIS,
1568
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1569
+ * See the License for the specific language governing permissions and
1570
+ * limitations under the License.
1571
+ */
1572
+ /**
1573
+ * Asserts that a string represents a hex-encoded contract address.
1574
+ *
1575
+ * @param contractAddress The source string.
1576
+ *
1577
+ * @throws `InvalidArgumentError`
1578
+ * `contractAddress` is not a correctly formatted {@link ContractAddress}.
1579
+ *
1580
+ * @internal
1581
+ */
1582
+ function assertIsContractAddress(contractAddress) {
1583
+ const CONTRACT_ADDRESS_BYTE_LENGTH = 32;
1584
+ assertIsHex(contractAddress, CONTRACT_ADDRESS_BYTE_LENGTH);
1585
+ const parsedHex = parseHex(contractAddress);
1586
+ if (parsedHex.hasPrefix) {
1587
+ throw new InvalidArgumentError(`Unexpected '0x' prefix in contract address '${contractAddress}'`);
1588
+ }
1589
+ }
1590
+
1591
+ /*
1592
+ * This file is part of midnight-js.
1593
+ * Copyright (C) Midnight Foundation
1594
+ * SPDX-License-Identifier: Apache-2.0
1595
+ * Licensed under the Apache License, Version 2.0 (the "License");
1596
+ * You may not use this file except in compliance with the License.
1597
+ * You may obtain a copy of the License at
1598
+ * http://www.apache.org/licenses/LICENSE-2.0
1599
+ * Unless required by applicable law or agreed to in writing, software
1600
+ * distributed under the License is distributed on an "AS IS" BASIS,
1601
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1602
+ * See the License for the specific language governing permissions and
1603
+ * limitations under the License.
1604
+ */
1605
+ /**
1606
+ * Whether a `JSON.parse` result is a JSON OBJECT, as opposed to an array or `null`.
1607
+ *
1608
+ * Arrays are excluded deliberately. `typeof [] === 'object'` and `[] !== null`, so a naive check
1609
+ * admits them, and a parser that admits an array then reports it as an object missing its members
1610
+ * -- which sends a caller to fix a document that is not the one they served.
1611
+ *
1612
+ * Not exported from the package barrel: it is shared between this package's own parsers, not part
1613
+ * of the published surface.
1614
+ */
1615
+ const isJsonObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
1616
+
1617
+ /*
1618
+ * This file is part of midnight-js.
1619
+ * Copyright (C) Midnight Foundation
1620
+ * SPDX-License-Identifier: Apache-2.0
1621
+ * Licensed under the Apache License, Version 2.0 (the "License");
1622
+ * You may not use this file except in compliance with the License.
1623
+ * You may obtain a copy of the License at
1624
+ * http://www.apache.org/licenses/LICENSE-2.0
1625
+ * Unless required by applicable law or agreed to in writing, software
1626
+ * distributed under the License is distributed on an "AS IS" BASIS,
1627
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1628
+ * See the License for the specific language governing permissions and
1629
+ * limitations under the License.
1630
+ */
1631
+ /** File name of the `compactc`-emitted contract description, beside the integrity manifest. */
1632
+ const ZK_CONTRACT_INFO_FILE_NAME = 'contract-info.json';
1633
+ /**
1634
+ * Thrown when a `compactc` `contract-info.json` cannot be read as one, or declares no runtime
1635
+ * version.
1636
+ *
1637
+ * Distinct from {@link ZkArtifactIntegrityError}: nothing here is a failed integrity check. The
1638
+ * file is the artifact set's own statement of which toolchain produced it, and this error says
1639
+ * that statement is missing or unreadable.
1640
+ */
1641
+ class ZkArtifactContractInfoError extends MidnightJsError {
1642
+ code = UTILS_ERROR_CODES.ZK_ARTIFACT_CONTRACT_INFO_INVALID;
1643
+ category = UTILS_ERROR_CATEGORIES[UTILS_ERROR_CODES.ZK_ARTIFACT_CONTRACT_INFO_INVALID];
1644
+ constructor(message, options) {
1645
+ super(message, options);
1646
+ this.name = 'ZkArtifactContractInfoError';
1647
+ }
1648
+ }
1649
+ /**
1650
+ * Reads the `runtime-version` a `compactc` `contract-info.json` declares.
1651
+ *
1652
+ * Only the runtime version is returned. It names the `compact-runtime` the artifact set was
1653
+ * compiled against, which is what places the artifact on the ledger-era timeline.
1654
+ *
1655
+ * FAIL-CLOSED: a missing, empty or non-string `runtime-version` throws rather than answering
1656
+ * `undefined`.
1657
+ *
1658
+ * @param rawJson The file's bytes, decoded as UTF-8 text.
1659
+ * @returns The declared runtime version, verbatim.
1660
+ * @throws ZkArtifactContractInfoError if the text is not a JSON object, or declares no usable
1661
+ * `runtime-version`.
1662
+ * @see {@link ArtifactRuntimeVersion} for why only this member is read, and why absence is a
1663
+ * refusal rather than a default.
1664
+ */
1665
+ function parseZkArtifactRuntimeVersion(rawJson) {
1666
+ let root;
1667
+ try {
1668
+ root = JSON.parse(rawJson);
1669
+ }
1670
+ catch (error) {
1671
+ throw new ZkArtifactContractInfoError(`${ZK_CONTRACT_INFO_FILE_NAME} is not valid JSON`, { cause: error });
1672
+ }
1673
+ if (!isJsonObject(root)) {
1674
+ throw new ZkArtifactContractInfoError(`${ZK_CONTRACT_INFO_FILE_NAME} must be a JSON object`);
1675
+ }
1676
+ const runtimeVersion = root['runtime-version'];
1677
+ if (runtimeVersion === undefined) {
1678
+ throw new ZkArtifactContractInfoError(`${ZK_CONTRACT_INFO_FILE_NAME} declares no "runtime-version", so the toolchain that produced ` +
1679
+ `these artifacts cannot be established. Recompile the contract with a compactc that emits it.`);
1680
+ }
1681
+ // Named rather than merely refused: a truncated or hand-edited file is otherwise indistinguishable
1682
+ // from an artifact set built by a toolchain too old to record the version, and the two have
1683
+ // different fixes.
1684
+ if (typeof runtimeVersion !== 'string' || runtimeVersion.length === 0) {
1685
+ throw new ZkArtifactContractInfoError(`${ZK_CONTRACT_INFO_FILE_NAME} declares an unusable "runtime-version": expected a non-empty ` +
1686
+ `string, got ${JSON.stringify(runtimeVersion)}`);
1687
+ }
1688
+ return runtimeVersion;
1689
+ }
1690
+
1691
+ /*
1692
+ * This file is part of midnight-js.
1693
+ * Copyright (C) Midnight Foundation
1694
+ * SPDX-License-Identifier: Apache-2.0
1695
+ * Licensed under the Apache License, Version 2.0 (the "License");
1696
+ * You may not use this file except in compliance with the License.
1697
+ * You may obtain a copy of the License at
1698
+ * http://www.apache.org/licenses/LICENSE-2.0
1699
+ * Unless required by applicable law or agreed to in writing, software
1700
+ * distributed under the License is distributed on an "AS IS" BASIS,
1701
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1702
+ * See the License for the specific language governing permissions and
1703
+ * limitations under the License.
1704
+ */
1705
+ /** Directory (relative to a provider's base location) holding the manifest. */
1706
+ const ZK_MANIFEST_DIR = 'compiler';
1707
+ /** File name of the `compactc`-emitted integrity manifest. */
1708
+ const ZK_MANIFEST_FILE_NAME = 'contract-manifest.json';
1709
+ const SUPPORTED_MANIFEST_VERSION = '1';
1710
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
1711
+ /** Thrown when a ZK artifact (or the manifest itself) fails integrity verification. */
1712
+ class ZkArtifactIntegrityError extends MidnightJsError {
1713
+ code = UTILS_ERROR_CODES.ZK_ARTIFACT_INTEGRITY_FAILED;
1714
+ category = UTILS_ERROR_CATEGORIES[UTILS_ERROR_CODES.ZK_ARTIFACT_INTEGRITY_FAILED];
1715
+ constructor(message, options) {
1716
+ super(message, options);
1717
+ this.name = 'ZkArtifactIntegrityError';
1718
+ }
1719
+ }
1720
+ const asOptionalString = (value) => typeof value === 'string' ? value : undefined;
1721
+ /** Lowercase hex SHA-256 of the given bytes. */
1722
+ const computeSha256Hex = (bytes) => bytesToHex(sha256(bytes));
1723
+ /**
1724
+ * Returns the first object key that `json` repeats within one object, comparing keys after JSON
1725
+ * string decoding. `json` must already be valid JSON: `JSON.parse` keeps only the last of repeated
1726
+ * keys, so the raw text is the only place a duplicate is still visible.
1727
+ */
1728
+ const findDuplicateKey = (json) => {
1729
+ const stack = [];
1730
+ let awaitingKey = false;
1731
+ let i = 0;
1732
+ while (i < json.length) {
1733
+ const ch = json[i];
1734
+ if (ch === '"') {
1735
+ const start = i++;
1736
+ while (json[i] !== '"') {
1737
+ i += json[i] === '\\' ? 2 : 1;
1738
+ }
1739
+ i++;
1740
+ const top = stack.at(-1);
1741
+ if (awaitingKey && top instanceof Set) {
1742
+ const key = JSON.parse(json.slice(start, i));
1743
+ if (top.has(key))
1744
+ return key;
1745
+ top.add(key);
1746
+ }
1747
+ awaitingKey = false;
1748
+ continue;
1749
+ }
1750
+ if (ch === '{') {
1751
+ stack.push(new Set());
1752
+ awaitingKey = true;
1753
+ }
1754
+ else if (ch === '[') {
1755
+ stack.push(null);
1756
+ awaitingKey = false;
1757
+ }
1758
+ else if (ch === '}' || ch === ']') {
1759
+ stack.pop();
1760
+ awaitingKey = false;
1761
+ }
1762
+ else if (ch === ',') {
1763
+ awaitingKey = stack.at(-1) instanceof Set;
1764
+ }
1765
+ else if (ch === ':') {
1766
+ awaitingKey = false;
1767
+ }
1768
+ i++;
1769
+ }
1770
+ return undefined;
1771
+ };
1772
+ /**
1773
+ * Parses a `compactc` `contract-manifest.json`. Asserts `manifest-version === '1'`, flattens exactly
1774
+ * one directory level into `"<dir>/<fileName>"` keys (nested sub-directories are ignored), validates
1775
+ * each file entry, and throws {@link ZkArtifactIntegrityError} on any structural violation. A
1776
+ * key repeated within one object also throws, so a manifest pinned by its hash cannot certify an
1777
+ * entry other than the one a reader of its text sees.
1778
+ */
1779
+ function parseZkArtifactManifest(rawJson) {
1780
+ let root;
1781
+ try {
1782
+ root = JSON.parse(rawJson);
1783
+ }
1784
+ catch (error) {
1785
+ throw new ZkArtifactIntegrityError('ZK artifact manifest is not valid JSON', { cause: error });
1786
+ }
1787
+ const duplicateKey = findDuplicateKey(rawJson);
1788
+ if (duplicateKey !== undefined) {
1789
+ throw new ZkArtifactIntegrityError(`ZK artifact manifest contains a duplicate key ${JSON.stringify(duplicateKey)}; an ambiguous manifest cannot be trusted as an integrity check`);
1790
+ }
1791
+ if (!isJsonObject(root)) {
1792
+ throw new ZkArtifactIntegrityError('ZK artifact manifest must be a JSON object');
1793
+ }
1794
+ if (root['manifest-version'] !== SUPPORTED_MANIFEST_VERSION) {
1795
+ throw new ZkArtifactIntegrityError(`Unsupported ZK artifact manifest-version: expected ${JSON.stringify(SUPPORTED_MANIFEST_VERSION)}, got ${JSON.stringify(root['manifest-version'])}`);
1796
+ }
1797
+ const files = new Map();
1798
+ for (const [dirName, dirValue] of Object.entries(root)) {
1799
+ if (!isJsonObject(dirValue) || dirValue.type !== 'directory') {
1800
+ continue;
1801
+ }
1802
+ for (const [childName, childValue] of Object.entries(dirValue)) {
1803
+ if (childName === 'type' || !isJsonObject(childValue) || childValue.type !== 'file') {
1804
+ continue; // ignore the `type` discriminator and nested sub-directories (depth > 1)
1805
+ }
1806
+ const key = `${dirName}/${childName}`;
1807
+ if (files.has(key)) {
1808
+ throw new ZkArtifactIntegrityError(`Duplicate entry "${key}" in ZK artifact manifest`);
1809
+ }
1810
+ const { size } = childValue;
1811
+ const hash = typeof childValue.hash === 'string' ? childValue.hash.toLowerCase() : undefined;
1812
+ if (typeof size !== 'number' || !Number.isInteger(size) || size < 0) {
1813
+ throw new ZkArtifactIntegrityError(`ZK artifact manifest entry "${key}" has an invalid size`);
1814
+ }
1815
+ if (hash === undefined || !SHA256_HEX.test(hash)) {
1816
+ throw new ZkArtifactIntegrityError(`ZK artifact manifest entry "${key}" has an invalid sha-256 hash`);
1817
+ }
1818
+ files.set(key, { size, hash });
1819
+ }
1820
+ }
1821
+ return {
1822
+ version: SUPPORTED_MANIFEST_VERSION,
1823
+ compilerVersion: asOptionalString(root['compiler-version']),
1824
+ languageVersion: asOptionalString(root['language-version']),
1825
+ runtimeVersion: asOptionalString(root['runtime-version']),
1826
+ files
1827
+ };
1828
+ }
1829
+ /** Verifies raw manifest bytes against a build-time pin. Throws on mismatch. */
1830
+ function assertManifestHash(rawBytes, expectedHash) {
1831
+ const actual = computeSha256Hex(rawBytes);
1832
+ const expected = expectedHash.toLowerCase();
1833
+ if (actual !== expected) {
1834
+ throw new ZkArtifactIntegrityError(`ZK artifact manifest failed integrity verification: expected sha-256 ${expected}, got ${actual}`);
1835
+ }
1836
+ }
1837
+ const defaultOnWarn = (message) => {
1838
+ console.warn(message);
1839
+ };
1840
+ /**
1841
+ * Verifies one artifact's bytes against the manifest entry for `relativePath`.
1842
+ * - `off`: no-op.
1843
+ * - no manifest at all: `require` throws, every other mode warns and returns.
1844
+ * - manifest present but no entry for the artifact: `require` and `require-if-present` throw,
1845
+ * `warn` warns and returns.
1846
+ * - length or digest mismatch: always throws (except `off`). Length is checked first as a cheap
1847
+ * pre-hash guard so a truncated artifact fails with a clear "expected N bytes" error.
1848
+ */
1849
+ function verifyZkArtifactIntegrity(params) {
1850
+ const { manifest, relativePath, bytes, mode } = params;
1851
+ if (mode === 'off') {
1852
+ return;
1853
+ }
1854
+ if (manifest === undefined) {
1855
+ if (mode === 'require') {
1856
+ throw new ZkArtifactIntegrityError(`no ZK artifact manifest (${ZK_MANIFEST_DIR}/${ZK_MANIFEST_FILE_NAME}) was found; integrity ` +
1857
+ `verification is required. Recompile with a manifest-emitting compactc, or construct the ` +
1858
+ `provider with { verify: 'require-if-present' }, { verify: 'warn' } or { verify: 'off' } to ` +
1859
+ `opt out.`);
1860
+ }
1861
+ (params.onWarn ?? defaultOnWarn)(`midnight-js: no ZK artifact manifest (${ZK_MANIFEST_DIR}/${ZK_MANIFEST_FILE_NAME}) was found; ` +
1862
+ `skipping ZK artifact integrity verification for "${relativePath}"`);
1863
+ return;
1864
+ }
1865
+ const entry = manifest.files.get(relativePath);
1866
+ if (entry === undefined) {
1867
+ if (mode === 'warn') {
1868
+ (params.onWarn ?? defaultOnWarn)(`midnight-js: ZK artifact manifest has no entry for "${relativePath}"; skipping ZK artifact ` +
1869
+ `integrity verification for it`);
1870
+ return;
1871
+ }
1872
+ throw new ZkArtifactIntegrityError(`ZK artifact manifest has no entry for "${relativePath}"; integrity verification is required. ` +
1873
+ `The manifest does not certify this artifact, so the artifact set is stale or partial. ` +
1874
+ `Construct the provider with { verify: 'warn' } or { verify: 'off' } to opt out.`);
1875
+ }
1876
+ if (bytes.length !== entry.size) {
1877
+ throw new ZkArtifactIntegrityError(`ZK artifact "${relativePath}" failed integrity verification: expected ${entry.size} bytes, got ${bytes.length}`);
1878
+ }
1879
+ const actual = computeSha256Hex(bytes);
1880
+ if (actual !== entry.hash) {
1881
+ throw new ZkArtifactIntegrityError(`ZK artifact "${relativePath}" failed integrity verification: expected sha-256 ${entry.hash}, got ${actual}`);
1882
+ }
1883
+ }
1884
+
1885
+ export { CONTRACTS_ERROR_CATEGORIES, CONTRACTS_ERROR_CODES, DeserializationError, MAX_CONSECUTIVE_REPEATED, MAX_SAFE_NAME_LENGTH, MIDNIGHT_JS_ERROR_CATEGORY_BY_CODE, MIDNIGHT_JS_ERROR_CODES, MIN_CHARACTER_CLASSES, MIN_PASSWORD_LENGTH, MIN_SEQUENTIAL_LENGTH, PATTERNS, PasswordValidationError, SOURCE_PACKAGES, TagParseError, UTILS_ERROR_CATEGORIES, UTILS_ERROR_CODES, UnhandledUnionMemberError, ZK_CONTRACT_INFO_FILE_NAME, ZK_MANIFEST_DIR, ZK_MANIFEST_FILE_NAME, ZkArtifactContractInfoError, ZkArtifactIntegrityError, assertDefined, assertIsContractAddress, assertIsHex, assertManifestHash, assertNever, assertSafeName, assertSemVer, assertUndefined, assertValidMidnightConfig, classify, computeSha256Hex, createMidnightProviders, decodeLedger9StateValue, deserializeLedger9CompactContractState, deserializeLedger9ContractState, deserializeLedger9Parameters, deserializeLedger9ZswapChainState, deserializeLedgerTransaction, errorCategory, fromHex, hasErrorCode, hasForeignErrorCode, intentTtl, isDeserializationError, isHex, isMidnightJsError, isValidSigningKey, ledgerVersionOfContractState, ledgerVersionOfLedgerParameters, networks, parseCoinPublicKeyToHex, parseEncPublicKeyToHex, parseHex, parseSerializedTag, parseZkArtifactManifest, parseZkArtifactRuntimeVersion, toHex, ttlOneHour, validatePassword, verifyZkArtifactIntegrity, warnIfInsecureRemoteUrl, withDeserializationContext };
1886
+ //# sourceMappingURL=index.js.map