@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/README.md +234 -2
- package/dist/index.d.ts +865 -0
- package/dist/index.js +1886 -0
- package/dist/index.js.map +1 -0
- package/package.json +45 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,865 @@
|
|
|
1
|
+
import * as _midnightntwrk_midnight_js_protocol_errors from '@midnightntwrk/midnight-js-protocol/errors';
|
|
2
|
+
import { MidnightJsError, MidnightJsErrorCategory, CommonErrorCode, ProtocolErrorCode } from '@midnightntwrk/midnight-js-protocol/errors';
|
|
3
|
+
export { MIDNIGHT_JS_ERROR_CATEGORIES, MidnightJsErrorCategory } from '@midnightntwrk/midnight-js-protocol/errors';
|
|
4
|
+
import { LedgerEra } from '@midnightntwrk/midnight-js-protocol/version';
|
|
5
|
+
import { EncodedStateValue, StateValue, ContractState as ContractState$1, LedgerParameters, ZswapChainState } from '@midnightntwrk/midnight-js-protocol/v9';
|
|
6
|
+
import { ContractState, SigningKey, ContractAddress } from '@midnightntwrk/midnight-js-protocol/v9/compact-runtime';
|
|
7
|
+
import { LedgerTransaction, NetworkId, MidnightConfig, MidnightProviders } from '@midnightntwrk/midnight-js-types';
|
|
8
|
+
import { ProviderErrorCode } from '@midnightntwrk/midnight-js-types/errors';
|
|
9
|
+
export { PROVIDER_ERROR_CATEGORIES, PROVIDER_ERROR_CODES, ProviderErrorCode } from '@midnightntwrk/midnight-js-types/errors';
|
|
10
|
+
import { Buffer } from 'buffer';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Asserts that the given value is non-nullable.
|
|
14
|
+
*
|
|
15
|
+
* @param value The value to test for nullability.
|
|
16
|
+
* @param message The error message to use if an error is thrown.
|
|
17
|
+
*
|
|
18
|
+
* @throws InvariantViolationError If the value is nullable.
|
|
19
|
+
*/
|
|
20
|
+
declare function assertDefined<A>(value: A | null | undefined, message?: string): asserts value is NonNullable<A>;
|
|
21
|
+
/**
|
|
22
|
+
* Asserts that the given value is null or undefined.
|
|
23
|
+
*
|
|
24
|
+
* @param value The value to test for nullability.
|
|
25
|
+
* @param message The error message to use if an error is thrown.
|
|
26
|
+
*
|
|
27
|
+
* @throws InvariantViolationError If the value is not undefined or null
|
|
28
|
+
*/
|
|
29
|
+
declare function assertUndefined<A>(value: A | null | undefined, message?: string): asserts value is undefined | null;
|
|
30
|
+
/**
|
|
31
|
+
* Raised by {@link assertNever} when a value the compiler ruled out arrives
|
|
32
|
+
* anyway, which happens when a payload is decoded from outside the build.
|
|
33
|
+
*/
|
|
34
|
+
declare class UnhandledUnionMemberError extends MidnightJsError {
|
|
35
|
+
readonly context: string;
|
|
36
|
+
readonly code: "MIDNIGHT_JS_U_UNHANDLED_UNION_MEMBER";
|
|
37
|
+
readonly category: _midnightntwrk_midnight_js_protocol_errors.MidnightJsErrorCategory;
|
|
38
|
+
constructor(context: string);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Asserts that every member of a union has already been handled.
|
|
42
|
+
*
|
|
43
|
+
* Put it in the `default` case of a `switch` over a discriminated union. While
|
|
44
|
+
* the switch is exhaustive the compiler narrows `value` to `never` and the call
|
|
45
|
+
* type-checks; add a member to the union and the same call stops compiling,
|
|
46
|
+
* pointing at every switch that has to change.
|
|
47
|
+
*
|
|
48
|
+
* The thrown message never includes `value`; `context` is what locates the throw.
|
|
49
|
+
*
|
|
50
|
+
* @param value The narrowed value, which must be `never` for the call to compile.
|
|
51
|
+
* @param context Names the switch, so the runtime throw says where it came from.
|
|
52
|
+
*
|
|
53
|
+
* @throws UnhandledUnionMemberError Always.
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```ts
|
|
57
|
+
* switch (record.era) {
|
|
58
|
+
* case 'v8': return readRetained(record);
|
|
59
|
+
* case 'v9': return readNative(record);
|
|
60
|
+
* default: return assertNever(record, 'readContractRecord');
|
|
61
|
+
* }
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
declare function assertNever(value: never, context: string): never;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Reads which ledger runtime wrote a serialized contract state, from the version tag in front of
|
|
68
|
+
* the state body — without deserializing the body.
|
|
69
|
+
*
|
|
70
|
+
* The tag is attacker-controlled input and is never the authority on the body; the node remains the
|
|
71
|
+
* sole authority on what the bytes decode to. What this check buys is a cheap, early rejection of
|
|
72
|
+
* anything that is not a contract state from a supported runtime, before those bytes reach a
|
|
73
|
+
* decoder — and, for a caller that holds two runtimes, the answer to which one to hand them to.
|
|
74
|
+
*
|
|
75
|
+
* Supported public API, deliberately: a caller reading raw contract state from an indexer needs to
|
|
76
|
+
* know which era's decoder to hand the bytes to before it hands them over.
|
|
77
|
+
*
|
|
78
|
+
* @param raw The serialized contract state, as the network returned it.
|
|
79
|
+
* @returns The ledger era whose runtime wrote `raw`.
|
|
80
|
+
* @throws TagParseError when there is no well-formed `namespace:version:` tag prefix in the first
|
|
81
|
+
* 64 bytes, or when the tag is not one of the supported contract-state version tags.
|
|
82
|
+
*/
|
|
83
|
+
declare const ledgerVersionOfContractState: (raw: Uint8Array) => LedgerEra;
|
|
84
|
+
|
|
85
|
+
declare const ttlOneHour: () => Date;
|
|
86
|
+
|
|
87
|
+
/** Underlying library that produced the deserialization error. */
|
|
88
|
+
type SourceLibrary = 'ledger' | 'compact-runtime' | 'onchain-runtime';
|
|
89
|
+
/** How the classifier categorized the error. */
|
|
90
|
+
type Classification = 'version-mismatch' | 'format-mismatch' | 'unknown';
|
|
91
|
+
/** Direction of incompatibility when inferable from the error message. */
|
|
92
|
+
type Direction = 'data-newer-than-code' | 'data-older-than-code';
|
|
93
|
+
/**
|
|
94
|
+
* Structured fields extracted from the underlying ledger/runtime error message.
|
|
95
|
+
* Populated by patterns whose `extract` callback succeeded.
|
|
96
|
+
*/
|
|
97
|
+
interface ExtractedInfo {
|
|
98
|
+
readonly dataType?: string;
|
|
99
|
+
readonly expectedVersion?: number;
|
|
100
|
+
readonly receivedVersion?: number;
|
|
101
|
+
}
|
|
102
|
+
/** Pattern entry in the classifier table. */
|
|
103
|
+
interface PatternEntry {
|
|
104
|
+
readonly regex: RegExp;
|
|
105
|
+
readonly classification: Classification;
|
|
106
|
+
readonly inferDirection?: (match: RegExpExecArray) => Direction | undefined;
|
|
107
|
+
readonly extract?: (match: RegExpExecArray) => ExtractedInfo;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Minimal context the caller of a deserialization wrapper must supply.
|
|
111
|
+
* `dataType` may be overridden by the classifier if the error message
|
|
112
|
+
* contains an extractable struct name.
|
|
113
|
+
*/
|
|
114
|
+
interface DeserializationCallSite {
|
|
115
|
+
readonly dataType: string;
|
|
116
|
+
readonly source: SourceLibrary;
|
|
117
|
+
readonly caller: string;
|
|
118
|
+
/**
|
|
119
|
+
* Facts identifying the particular read that failed, supplied by the caller
|
|
120
|
+
* and rendered verbatim. For diagnosis only: nothing here changes the
|
|
121
|
+
* classification or the mitigation.
|
|
122
|
+
*/
|
|
123
|
+
readonly details?: Readonly<Record<string, string | number>>;
|
|
124
|
+
}
|
|
125
|
+
/** Fully-classified context attached to a `DeserializationError`. */
|
|
126
|
+
interface DeserializationContext extends DeserializationCallSite {
|
|
127
|
+
readonly classification: Classification;
|
|
128
|
+
readonly direction?: Direction;
|
|
129
|
+
readonly mitigation: readonly string[];
|
|
130
|
+
readonly extracted?: ExtractedInfo;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* An error thrown by the deserialization wrappers when a ledger /
|
|
134
|
+
* compact-runtime / onchain-runtime `.deserialize`/`.decode` call fails.
|
|
135
|
+
* Carries structured context for diagnosis: data type, call site,
|
|
136
|
+
* classification, direction, mitigation.
|
|
137
|
+
*/
|
|
138
|
+
declare class DeserializationError extends MidnightJsError {
|
|
139
|
+
readonly code: "MIDNIGHT_JS_U_DESERIALIZATION_FAILED";
|
|
140
|
+
readonly category: _midnightntwrk_midnight_js_protocol_errors.MidnightJsErrorCategory;
|
|
141
|
+
readonly context: DeserializationContext;
|
|
142
|
+
/**
|
|
143
|
+
* @param context Structured diagnostic context.
|
|
144
|
+
* @param cause Underlying error. Typed as `unknown` to match the
|
|
145
|
+
* `Error.cause` ECMA spec. Primary call sites (typed wrappers) always
|
|
146
|
+
* pass an `Error` via `withDeserializationContext`.
|
|
147
|
+
*/
|
|
148
|
+
constructor(context: DeserializationContext, cause?: unknown);
|
|
149
|
+
}
|
|
150
|
+
/** Type guard for `DeserializationError`. */
|
|
151
|
+
declare const isDeserializationError: (e: unknown) => e is DeserializationError;
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Classify a deserialization error against the shared pattern table.
|
|
155
|
+
* Returns a fully-populated `DeserializationContext` ready to attach to a
|
|
156
|
+
* `DeserializationError`.
|
|
157
|
+
*
|
|
158
|
+
* Rules (spec §7.1):
|
|
159
|
+
* - First matching pattern wins.
|
|
160
|
+
* - `extracted.dataType` (when populated by a pattern) overrides `callSite.dataType`.
|
|
161
|
+
* - Mitigation is dispatched on `(classification, source)` (D12).
|
|
162
|
+
* - `extracted` is `undefined` (not `{}`) when no pattern populated it.
|
|
163
|
+
*/
|
|
164
|
+
declare const classify: (callSite: DeserializationCallSite, cause: Error) => DeserializationContext;
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Shared pattern table across all three sources (ledger / compact-runtime / onchain-runtime).
|
|
168
|
+
* Sources share the same `serialize` Rust crate, so error message formats are identical.
|
|
169
|
+
* Order matters — more specific patterns come first; first match wins.
|
|
170
|
+
*
|
|
171
|
+
* Patterns sourced from `midnight-ledger` repo audit (spec §7.1):
|
|
172
|
+
* - `serialize/src/deserializable.rs`, `serialize/src/util.rs`
|
|
173
|
+
* - `serialize-macros/src/lib.rs`
|
|
174
|
+
* - `ledger/src/structure.rs`, `ledger/src/error.rs`
|
|
175
|
+
* - `ledger-wasm/src/conversions.rs`, `onchain-runtime-wasm/src/lib.rs`
|
|
176
|
+
*/
|
|
177
|
+
declare const PATTERNS: readonly PatternEntry[];
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Minimal context the caller of a typed deserialization wrapper must supply.
|
|
181
|
+
* The `dataType` and `source` are baked into each wrapper.
|
|
182
|
+
*/
|
|
183
|
+
interface CallSiteContext {
|
|
184
|
+
readonly caller: string;
|
|
185
|
+
/**
|
|
186
|
+
* Facts identifying the particular read that failed, rendered on the error
|
|
187
|
+
* and kept on its `context`. Diagnosis only: nothing here changes the
|
|
188
|
+
* classification or the mitigation.
|
|
189
|
+
*/
|
|
190
|
+
readonly details?: Readonly<Record<string, string | number>>;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Deserialize a ledger {@link LedgerContractState} from raw bytes.
|
|
194
|
+
*
|
|
195
|
+
* @throws {DeserializationError} On any underlying ledger deserialization
|
|
196
|
+
* failure. The error carries classification, direction inference, and
|
|
197
|
+
* actionable mitigation hints.
|
|
198
|
+
*
|
|
199
|
+
* @example
|
|
200
|
+
* ```ts
|
|
201
|
+
* const state = deserializeLedger9ContractState(buf, {
|
|
202
|
+
* caller: '@midnightntwrk/midnight-js-indexer-public-data-provider:queryContractState'
|
|
203
|
+
* });
|
|
204
|
+
* ```
|
|
205
|
+
*
|
|
206
|
+
* The `caller` should be fully qualified (`@scope/package:function`) — this
|
|
207
|
+
* convention is enforced across the codebase and surfaces in the rendered
|
|
208
|
+
* error message.
|
|
209
|
+
*/
|
|
210
|
+
declare const deserializeLedger9ContractState: (bytes: Uint8Array, ctx: CallSiteContext) => ContractState$1;
|
|
211
|
+
/**
|
|
212
|
+
* Deserialize a compact-runtime {@link CompactContractState} from raw bytes.
|
|
213
|
+
*
|
|
214
|
+
* @throws {DeserializationError} On any underlying compact-runtime
|
|
215
|
+
* deserialization failure.
|
|
216
|
+
*/
|
|
217
|
+
declare const deserializeLedger9CompactContractState: (bytes: Uint8Array, ctx: CallSiteContext) => ContractState;
|
|
218
|
+
/**
|
|
219
|
+
* Deserialize a ledger {@link ZswapChainState} from raw bytes.
|
|
220
|
+
*
|
|
221
|
+
* @throws {DeserializationError} On any underlying ledger deserialization
|
|
222
|
+
* failure.
|
|
223
|
+
*/
|
|
224
|
+
declare const deserializeLedger9ZswapChainState: (bytes: Uint8Array, ctx: CallSiteContext) => ZswapChainState;
|
|
225
|
+
/**
|
|
226
|
+
* Wraps the bytes of a finalized ledger transaction of the given era in a
|
|
227
|
+
* {@link LedgerTransaction} handle of that era. Only the header is checked;
|
|
228
|
+
* the caller decodes the handle with its own ledger copy, so reading a v8
|
|
229
|
+
* record does not load the v8 runtime.
|
|
230
|
+
*
|
|
231
|
+
* @param era The ledger era that wrote the bytes. Never derived from the bytes.
|
|
232
|
+
* @param bytes The serialized finalized transaction.
|
|
233
|
+
* @param ctx The call site, named on a refusal.
|
|
234
|
+
* @returns A finalized handle of `era`.
|
|
235
|
+
* @throws {DeserializationError} If the bytes do not start with the header the
|
|
236
|
+
* ledger of `era` writes for a finalized transaction, including bytes written
|
|
237
|
+
* by the other era.
|
|
238
|
+
* @throws {UnknownLedgerEraError} If `era` is not a ledger era.
|
|
239
|
+
*/
|
|
240
|
+
declare const deserializeLedgerTransaction: <E extends LedgerEra>(era: E, bytes: Uint8Array, ctx: CallSiteContext) => Promise<LedgerTransaction<"Finalized", E>>;
|
|
241
|
+
/**
|
|
242
|
+
* Deserialize ledger {@link LedgerParameters} from raw bytes.
|
|
243
|
+
*
|
|
244
|
+
* @throws {DeserializationError} On any underlying ledger deserialization
|
|
245
|
+
* failure.
|
|
246
|
+
*/
|
|
247
|
+
declare const deserializeLedger9Parameters: (bytes: Uint8Array, ctx: CallSiteContext) => LedgerParameters;
|
|
248
|
+
/**
|
|
249
|
+
* Decode an onchain-runtime {@link LedgerStateValue} from its
|
|
250
|
+
* {@link EncodedStateValue} representation (a tagged union, NOT a byte
|
|
251
|
+
* buffer — `StateValue.decode` operates on the structured encoding produced
|
|
252
|
+
* by `StateValue.encode()`).
|
|
253
|
+
*
|
|
254
|
+
* Source attribution is `onchain-runtime` (per D8) even though the type
|
|
255
|
+
* is re-exported through the `ledger` sub-path — mitigation hints point
|
|
256
|
+
* to the underlying runtime package.
|
|
257
|
+
*
|
|
258
|
+
* @throws {DeserializationError} On any underlying onchain-runtime decode
|
|
259
|
+
* failure.
|
|
260
|
+
*/
|
|
261
|
+
declare const decodeLedger9StateValue: (encoded: EncodedStateValue, ctx: CallSiteContext) => StateValue;
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* The npm package families that produce the deserialization errors this
|
|
265
|
+
* module wraps. The major-version suffix (e.g. `-v8`, `-v3`) is intentionally
|
|
266
|
+
* omitted — error messages reference the family and rely on the structural
|
|
267
|
+
* version tag carried inside the error itself (e.g. `contract-state[v6]`)
|
|
268
|
+
* for the actual version context.
|
|
269
|
+
*
|
|
270
|
+
* This avoids hardcoded `v8`/`v3` strings that would go stale silently when
|
|
271
|
+
* the underlying package is bumped.
|
|
272
|
+
*/
|
|
273
|
+
declare const SOURCE_PACKAGES: {
|
|
274
|
+
readonly ledger: "@midnight-ntwrk/ledger";
|
|
275
|
+
readonly compactRuntime: "@midnight-ntwrk/compact-runtime";
|
|
276
|
+
readonly onchainRuntime: "@midnight-ntwrk/onchain-runtime";
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Wraps a synchronous deserialization call. Whatever `fn()` throws, the
|
|
281
|
+
* wrapper classifies it and re-throws a `DeserializationError` carrying
|
|
282
|
+
* structured context, with the original value on `cause`.
|
|
283
|
+
*
|
|
284
|
+
* A non-`Error` throw is classified on its string form rather than escaping
|
|
285
|
+
* unwrapped.
|
|
286
|
+
*
|
|
287
|
+
* SYNC-ONLY BY CONTRACT: if `fn()` returns a thenable the wrapper throws an
|
|
288
|
+
* `InvalidArgumentError`. The typed wrappers in `./typed-wrappers.ts` are the primary API;
|
|
289
|
+
* use this HOF directly only for ad-hoc deserialization sites not covered there.
|
|
290
|
+
*
|
|
291
|
+
* @throws {DeserializationError} When `fn()` throws anything at all.
|
|
292
|
+
* @throws {InvalidArgumentError} When `fn()` returns a thenable (sync-only violation).
|
|
293
|
+
*
|
|
294
|
+
* @see {@link ErrorVocabulary} for why a bare string throw is classified rather
|
|
295
|
+
* than re-thrown, and what the thenable check prevents.
|
|
296
|
+
*
|
|
297
|
+
* @example
|
|
298
|
+
* ```ts
|
|
299
|
+
* // Inside a typed wrapper:
|
|
300
|
+
* deserializeLedger9ContractState(buf, ctx) =>
|
|
301
|
+
* withDeserializationContext(callSite, () => LedgerContractState.deserialize(buf));
|
|
302
|
+
* ```
|
|
303
|
+
*/
|
|
304
|
+
declare const withDeserializationContext: <T>(callSite: DeserializationCallSite, fn: () => T) => T;
|
|
305
|
+
|
|
306
|
+
declare const CONTRACTS_ERROR_CODES: Readonly<{
|
|
307
|
+
readonly ERA_INVARIANT_VIOLATION: "MIDNIGHT_JS_C_ERA_INVARIANT_VIOLATION";
|
|
308
|
+
readonly ERA_MISMATCH: "MIDNIGHT_JS_C_ERA_MISMATCH";
|
|
309
|
+
readonly TX_FAILED: "MIDNIGHT_JS_C_TX_FAILED";
|
|
310
|
+
readonly NETWORK_VERSION_STATE_MISMATCH: "MIDNIGHT_JS_C_NETWORK_VERSION_STATE_MISMATCH";
|
|
311
|
+
readonly INDEXER_INCONSISTENCY: "MIDNIGHT_JS_C_INDEXER_INCONSISTENCY";
|
|
312
|
+
readonly PUBLIC_STATES_ERA_MISMATCH: "MIDNIGHT_JS_C_PUBLIC_STATES_ERA_MISMATCH";
|
|
313
|
+
readonly BLANK_VERIFIER_KEY_SLOT: "MIDNIGHT_JS_C_BLANK_VERIFIER_KEY_SLOT";
|
|
314
|
+
readonly VERIFIER_KEY_MISMATCH: "MIDNIGHT_JS_C_VERIFIER_KEY_MISMATCH";
|
|
315
|
+
readonly PROVIDER_FAILED: "MIDNIGHT_JS_C_PROVIDER_FAILED";
|
|
316
|
+
readonly FORK_CROSSED_DURING_OPERATION: "MIDNIGHT_JS_C_FORK_CROSSED_DURING_OPERATION";
|
|
317
|
+
readonly SUBMIT_REJECTION_UNDIAGNOSED: "MIDNIGHT_JS_C_SUBMIT_REJECTION_UNDIAGNOSED";
|
|
318
|
+
readonly LEDGER_PARAMETERS_UNSERVED: "MIDNIGHT_JS_C_LEDGER_PARAMETERS_UNSERVED";
|
|
319
|
+
readonly CONTRACT_TYPE_MISMATCH: "MIDNIGHT_JS_C_CONTRACT_TYPE_MISMATCH";
|
|
320
|
+
readonly INCOMPLETE_CALL_TX_PRIVATE_STATE_CONFIG: "MIDNIGHT_JS_C_INCOMPLETE_CALL_TX_PRIVATE_STATE_CONFIG";
|
|
321
|
+
readonly INCOMPLETE_DEPLOY_PRIVATE_STATE_CONFIG: "MIDNIGHT_JS_C_INCOMPLETE_DEPLOY_PRIVATE_STATE_CONFIG";
|
|
322
|
+
readonly INCOMPLETE_FIND_PRIVATE_STATE_CONFIG: "MIDNIGHT_JS_C_INCOMPLETE_FIND_PRIVATE_STATE_CONFIG";
|
|
323
|
+
readonly SCOPED_TRANSACTION_IDENTITY_MISMATCH: "MIDNIGHT_JS_C_SCOPED_TRANSACTION_IDENTITY_MISMATCH";
|
|
324
|
+
readonly LEDGER8_AMBIGUOUS_ENTRY_POINT: "MIDNIGHT_JS_C_LEDGER8_AMBIGUOUS_ENTRY_POINT";
|
|
325
|
+
readonly LEDGER8_SIGNING_KEY: "MIDNIGHT_JS_C_LEDGER8_SIGNING_KEY";
|
|
326
|
+
readonly LEDGER8_UNCONFIRMED: "MIDNIGHT_JS_C_LEDGER8_UNCONFIRMED";
|
|
327
|
+
readonly LEDGER8_NOT_STORED: "MIDNIGHT_JS_C_LEDGER8_NOT_STORED";
|
|
328
|
+
readonly LEDGER8_CALL_UNSUPPORTED: "MIDNIGHT_JS_C_LEDGER8_CALL_UNSUPPORTED";
|
|
329
|
+
readonly NETWORK_VERSION_READ_FAILED: "MIDNIGHT_JS_C_NETWORK_VERSION_READ_FAILED";
|
|
330
|
+
readonly ZSWAP_OUTPUT_UNRESOLVED: "MIDNIGHT_JS_C_ZSWAP_OUTPUT_UNRESOLVED";
|
|
331
|
+
readonly CONTRACT_NOT_FOUND: "MIDNIGHT_JS_C_CONTRACT_NOT_FOUND";
|
|
332
|
+
readonly PRIVATE_STATE_NOT_FOUND: "MIDNIGHT_JS_C_PRIVATE_STATE_NOT_FOUND";
|
|
333
|
+
}>;
|
|
334
|
+
type ContractsErrorCode = (typeof CONTRACTS_ERROR_CODES)[keyof typeof CONTRACTS_ERROR_CODES];
|
|
335
|
+
|
|
336
|
+
declare const UTILS_ERROR_CODES: Readonly<{
|
|
337
|
+
readonly TAG_PARSE_FAILED: "MIDNIGHT_JS_U_TAG_PARSE_FAILED";
|
|
338
|
+
readonly UNHANDLED_UNION_MEMBER: "MIDNIGHT_JS_U_UNHANDLED_UNION_MEMBER";
|
|
339
|
+
readonly ZK_ARTIFACT_INTEGRITY_FAILED: "MIDNIGHT_JS_U_ZK_ARTIFACT_INTEGRITY_FAILED";
|
|
340
|
+
readonly ZK_ARTIFACT_CONTRACT_INFO_INVALID: "MIDNIGHT_JS_U_ZK_ARTIFACT_CONTRACT_INFO_INVALID";
|
|
341
|
+
readonly PASSWORD_INVALID: "MIDNIGHT_JS_U_PASSWORD_INVALID";
|
|
342
|
+
readonly DESERIALIZATION_FAILED: "MIDNIGHT_JS_U_DESERIALIZATION_FAILED";
|
|
343
|
+
}>;
|
|
344
|
+
type UtilsErrorCode = (typeof UTILS_ERROR_CODES)[keyof typeof UTILS_ERROR_CODES];
|
|
345
|
+
declare const CONTRACTS_ERROR_CATEGORIES: Readonly<Record<ContractsErrorCode, MidnightJsErrorCategory>>;
|
|
346
|
+
declare const UTILS_ERROR_CATEGORIES: Readonly<Record<UtilsErrorCode, MidnightJsErrorCategory>>;
|
|
347
|
+
/**
|
|
348
|
+
* Union of every error code carried by a *coded* midnight-js error.
|
|
349
|
+
*
|
|
350
|
+
* Every error midnight-js raises itself carries a code. `hasErrorCode(e) === false` means the error
|
|
351
|
+
* came from a dependency, the platform or user code and was passed through unchanged, or from another
|
|
352
|
+
* installed midnight-js copy using a code this copy does not know.
|
|
353
|
+
*/
|
|
354
|
+
type MidnightJsErrorCode = CommonErrorCode | ProtocolErrorCode | ContractsErrorCode | ProviderErrorCode | UtilsErrorCode;
|
|
355
|
+
declare const MIDNIGHT_JS_ERROR_CODES: readonly MidnightJsErrorCode[];
|
|
356
|
+
declare const MIDNIGHT_JS_ERROR_CATEGORY_BY_CODE: Readonly<Record<MidnightJsErrorCode, MidnightJsErrorCategory>>;
|
|
357
|
+
/**
|
|
358
|
+
* A code this framework does not own. Resolves to `never` for a member of
|
|
359
|
+
* {@link MidnightJsErrorCode}, so passing one is a compile error. A value typed
|
|
360
|
+
* merely as `string` still satisfies it: at that point the literal is unknown,
|
|
361
|
+
* and the runtime screen in {@link hasForeignErrorCode} is what remains.
|
|
362
|
+
*/
|
|
363
|
+
type ForeignErrorCode<C extends string> = C extends MidnightJsErrorCode ? never : C;
|
|
364
|
+
/**
|
|
365
|
+
* Type guard for "this is one of midnight-js's own coded errors" — narrows
|
|
366
|
+
* to `Error & { code: MidnightJsErrorCode }` only when `e.code` is present
|
|
367
|
+
* in the {@link MIDNIGHT_JS_ERROR_CODES} registry. A foreign coded error
|
|
368
|
+
* (e.g. Node's `ECONNREFUSED`) returns `false`.
|
|
369
|
+
*/
|
|
370
|
+
declare function hasErrorCode(e: unknown): e is Error & {
|
|
371
|
+
code: MidnightJsErrorCode;
|
|
372
|
+
};
|
|
373
|
+
/**
|
|
374
|
+
* Type guard for "this error carries exactly `code`" — narrows to
|
|
375
|
+
* `Error & { code: C }` when `e.code === code`.
|
|
376
|
+
*
|
|
377
|
+
* `code` must be one of this framework's own codes, so a typo is a compile
|
|
378
|
+
* error rather than a guard that silently never matches.
|
|
379
|
+
*
|
|
380
|
+
* If a code you believe is ours does not compile here, it is misspelled or was
|
|
381
|
+
* never registered — check {@link MIDNIGHT_JS_ERROR_CODES}. Do NOT reach for
|
|
382
|
+
* {@link hasForeignErrorCode} to get it past the compiler; that guard refuses
|
|
383
|
+
* anything carrying this framework's prefix. It is for codes belonging to
|
|
384
|
+
* someone else, such as Node's `ECONNREFUSED`.
|
|
385
|
+
*/
|
|
386
|
+
declare function hasErrorCode<C extends MidnightJsErrorCode>(e: unknown, code: C): e is Error & {
|
|
387
|
+
code: C;
|
|
388
|
+
};
|
|
389
|
+
/**
|
|
390
|
+
* True when `e` is an error midnight-js threw. Reads `e.code`, so it also recognises an error built by
|
|
391
|
+
* another installed copy of a midnight-js package, which `instanceof MidnightJsError` would not.
|
|
392
|
+
*
|
|
393
|
+
* Narrows to `Error & { code }`, not to `MidnightJsError`: an error from another copy may lack the
|
|
394
|
+
* class's other members. Read the category with {@link errorCategory}, not `e.category`.
|
|
395
|
+
*/
|
|
396
|
+
declare const isMidnightJsError: (e: unknown) => e is Error & {
|
|
397
|
+
code: MidnightJsErrorCode;
|
|
398
|
+
};
|
|
399
|
+
/** What the caller should do about `e`, or `undefined` when `e` is not a midnight-js error. */
|
|
400
|
+
declare const errorCategory: (e: unknown) => MidnightJsErrorCategory | undefined;
|
|
401
|
+
/**
|
|
402
|
+
* Type guard for "this error carries exactly `code`", where `code` belongs to
|
|
403
|
+
* someone else — Node's `ECONNREFUSED`, a driver's own vocabulary, anything
|
|
404
|
+
* outside {@link MidnightJsErrorCode}.
|
|
405
|
+
*
|
|
406
|
+
* Separate from {@link hasErrorCode} so that reaching outside this framework's
|
|
407
|
+
* codes is deliberate and visible at the call site. Foreignness is enforced
|
|
408
|
+
* twice: by the compiler via {@link ForeignErrorCode}, and at run time by prefix.
|
|
409
|
+
*
|
|
410
|
+
* @throws InvalidArgumentError if `code` carries this framework's own `MIDNIGHT_JS_` prefix.
|
|
411
|
+
* That is a mistake at the call site, not a property of `e`, so it is raised
|
|
412
|
+
* rather than reported as a non-match.
|
|
413
|
+
* @see {@link ErrorVocabulary} for why the two guards are separate, and why one
|
|
414
|
+
* gate cannot cover both cases.
|
|
415
|
+
*/
|
|
416
|
+
declare function hasForeignErrorCode<C extends string>(e: unknown, code: ForeignErrorCode<C>): e is Error & {
|
|
417
|
+
code: C;
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* The result of parsing a string as a hex-encoded string.
|
|
422
|
+
*/
|
|
423
|
+
type ParsedHexString = {
|
|
424
|
+
/** A flag indicating if the hex-string has a `'0x'` prefix. */
|
|
425
|
+
readonly hasPrefix: boolean;
|
|
426
|
+
/** The captured sequence of _whole_ bytes found in the source string. */
|
|
427
|
+
readonly byteChars: string;
|
|
428
|
+
/** The remaining characters of incomplete bytes and/or the non hexadecimal characters found
|
|
429
|
+
* in the source string. */
|
|
430
|
+
readonly incompleteChars: string;
|
|
431
|
+
};
|
|
432
|
+
/**
|
|
433
|
+
* Parses a string as a hex-encoded string.
|
|
434
|
+
*
|
|
435
|
+
* @param source The source string to parse.
|
|
436
|
+
* @returns A {@link ParsedHexString} describing the parsed elements of `source`.
|
|
437
|
+
*
|
|
438
|
+
* @example
|
|
439
|
+
* parseHex('Hello') =>
|
|
440
|
+
* {
|
|
441
|
+
* hasPrefix: false,
|
|
442
|
+
* incompleteChars: 'Hello'
|
|
443
|
+
* }
|
|
444
|
+
*
|
|
445
|
+
* @example
|
|
446
|
+
* parseHex('ab12e') =>
|
|
447
|
+
* {
|
|
448
|
+
* hasPrefix: false,
|
|
449
|
+
* byteChars: 'ab12'
|
|
450
|
+
* incompleteChars: 'e'
|
|
451
|
+
* }
|
|
452
|
+
*
|
|
453
|
+
* @example
|
|
454
|
+
* parseHex('0xab12') =>
|
|
455
|
+
* {
|
|
456
|
+
* hasPrefix: true,
|
|
457
|
+
* byteChars: 'ab12'
|
|
458
|
+
* incompleteChars: ''
|
|
459
|
+
* }
|
|
460
|
+
*/
|
|
461
|
+
declare const parseHex: (source: string) => ParsedHexString;
|
|
462
|
+
/**
|
|
463
|
+
* Converts a byte string into a hex string.
|
|
464
|
+
*
|
|
465
|
+
* @param bytes The byte string to encode.
|
|
466
|
+
*/
|
|
467
|
+
declare const toHex: (bytes: Uint8Array) => string;
|
|
468
|
+
/**
|
|
469
|
+
* Converts a hex string into a byte string.
|
|
470
|
+
*
|
|
471
|
+
* @param str The hex string to decode.
|
|
472
|
+
*/
|
|
473
|
+
declare const fromHex: (str: string) => Buffer;
|
|
474
|
+
/**
|
|
475
|
+
* Determines if a string represents a hex-encoded sequence of bytes.
|
|
476
|
+
*
|
|
477
|
+
* @param source The source string.
|
|
478
|
+
* @param byteLen An optional number of bytes that `source` should represent. If not specified
|
|
479
|
+
* then any number of bytes can be represented by `source`.
|
|
480
|
+
* @returns `true` if the `source` string is parsable as a hex-string, of non-zero length, and
|
|
481
|
+
* of the optional byte length of `byteLen`; otherwise `false`.
|
|
482
|
+
*/
|
|
483
|
+
declare const isHex: (source: string, byteLen?: number) => boolean;
|
|
484
|
+
/**
|
|
485
|
+
* Asserts that a string represents a hex-encoded sequence of bytes.
|
|
486
|
+
*
|
|
487
|
+
* @param source The source string.
|
|
488
|
+
* @param byteLen An optional number of bytes that `source` should represent. If not specified
|
|
489
|
+
* then any number of bytes can be represented by `source`.
|
|
490
|
+
*
|
|
491
|
+
* @throws `InvalidArgumentError`
|
|
492
|
+
* `byteLen` is \<= zero. Valid hex-strings will be required to have at least one byte.
|
|
493
|
+
* @throws `InvalidArgumentError`
|
|
494
|
+
* `source` is not a hex-encoded string because it:
|
|
495
|
+
* - is empty,
|
|
496
|
+
* - contains invalid or incomplete characters, or
|
|
497
|
+
* - does not represent `byteLen` bytes.
|
|
498
|
+
*/
|
|
499
|
+
declare function assertIsHex(source: string, byteLen?: number): asserts source is NonNullable<string>;
|
|
500
|
+
/**
|
|
501
|
+
* Parses a coin public key (in Bech32m format or hex) into a hex formatted string.
|
|
502
|
+
*
|
|
503
|
+
* @param possibleBech32 The input string, which can be a Bech32m-encoded coin public key or a hex string.
|
|
504
|
+
* @param zswapNetworkId The network ID used for decoding the Bech32m formatted string.
|
|
505
|
+
* @returns The hex string representation of the coin public key.
|
|
506
|
+
*
|
|
507
|
+
* @throws `Error`
|
|
508
|
+
* If the input string is not a valid hex string or a valid Bech32m-encoded coin public key.
|
|
509
|
+
*/
|
|
510
|
+
declare const parseCoinPublicKeyToHex: (possibleBech32: string, zswapNetworkId: NetworkId) => string;
|
|
511
|
+
/**
|
|
512
|
+
* Parses an encryption public key (in Bech32m or hex format) into a hex formatted string.
|
|
513
|
+
*
|
|
514
|
+
* @param possibleBech32 The input string, which can be a Bech32m-encoded encryption public key or a hex string.
|
|
515
|
+
* @param zswapNetworkId The network ID used for decoding the Bech32m formatted string.
|
|
516
|
+
* @returns The hex string representation of the encryption public key.
|
|
517
|
+
*
|
|
518
|
+
* @throws `Error`
|
|
519
|
+
* If the input string is not a valid hex string or a valid Bech32m-encoded encryption public key.
|
|
520
|
+
*/
|
|
521
|
+
declare const parseEncPublicKeyToHex: (possibleBech32: string, zswapNetworkId: NetworkId) => string;
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Reads which ledger runtime wrote a serialized set of ledger parameters, from the version tag in
|
|
525
|
+
* front of the body — without deserializing the body.
|
|
526
|
+
*
|
|
527
|
+
* The sibling of {@link ledgerVersionOfContractState}, and it exists for the same reason: the
|
|
528
|
+
* indexer serves ledger parameters PER BLOCK, they are era-tagged, and each era's deserializer
|
|
529
|
+
* refuses the other era's bytes on the header tag. A reader that decodes them with a fixed era's
|
|
530
|
+
* runtime therefore works on one side of a fork and fails on the other — with a raw deserialization
|
|
531
|
+
* failure that names neither the era nor the field.
|
|
532
|
+
*
|
|
533
|
+
* The tag is network-supplied input and is never the authority on the body; the node remains the
|
|
534
|
+
* sole authority on what the bytes decode to. What this check buys is a cheap, early rejection of
|
|
535
|
+
* anything that is not a parameter set from a supported runtime, before those bytes reach a
|
|
536
|
+
* decoder — and, for a caller that holds two runtimes, the answer to which one to hand them to.
|
|
537
|
+
*
|
|
538
|
+
* Supported public API, deliberately: a caller refused a pre-fork block's parameters by an era-fixed
|
|
539
|
+
* read path has to decode them itself, and needs this to pick the runtime to decode them with.
|
|
540
|
+
*
|
|
541
|
+
* @param raw The serialized ledger parameters, as the network returned it.
|
|
542
|
+
* @returns The ledger era whose runtime wrote `raw`.
|
|
543
|
+
* @throws TagParseError when there is no well-formed `namespace:version:` tag prefix in the first
|
|
544
|
+
* 64 bytes, or when the tag is not one of the supported ledger-parameters version tags.
|
|
545
|
+
*/
|
|
546
|
+
declare const ledgerVersionOfLedgerParameters: (raw: Uint8Array) => LedgerEra;
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Checks a {@link MidnightConfig} before any work is done with it.
|
|
550
|
+
*
|
|
551
|
+
* @param config The config to check; `undefined` or `null` when a caller did not pass one.
|
|
552
|
+
* @param source Where the config was read from, named in the error.
|
|
553
|
+
* @throws ConfigurationError If `config` is missing.
|
|
554
|
+
* @throws InvalidArgumentError If `config.networkId` is not a non-empty string
|
|
555
|
+
* without surrounding whitespace, or if `config.ttlSeconds` is not a positive whole number, or is too large for the
|
|
556
|
+
* expiry to be a valid `Date`.
|
|
557
|
+
*/
|
|
558
|
+
declare function assertValidMidnightConfig(config: MidnightConfig | null | undefined, source?: string): asserts config is MidnightConfig;
|
|
559
|
+
/**
|
|
560
|
+
* The expiry for an intent built now: the current time plus `config.ttlSeconds`.
|
|
561
|
+
*
|
|
562
|
+
* @param config The config whose `ttlSeconds` is applied.
|
|
563
|
+
* @throws ConfigurationError, InvalidArgumentError As {@link assertValidMidnightConfig}.
|
|
564
|
+
*/
|
|
565
|
+
declare const intentTtl: (config: MidnightConfig) => Date;
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* Checks a provider set the dApp built and returns it unchanged, so a broken set fails at
|
|
569
|
+
* application start instead of at the first operation.
|
|
570
|
+
*
|
|
571
|
+
* @param providers The provider set to check.
|
|
572
|
+
* @returns The same `providers` object.
|
|
573
|
+
* @throws ConfigurationError If a required provider is missing, or as {@link assertValidMidnightConfig}.
|
|
574
|
+
* @throws InvalidArgumentError As {@link assertValidMidnightConfig}.
|
|
575
|
+
*/
|
|
576
|
+
declare const createMidnightProviders: <P extends MidnightProviders>(providers: P) => P;
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* The network id and endpoints of a Midnight network.
|
|
580
|
+
*
|
|
581
|
+
* Build your own object of this shape to point at a self-hosted node or indexer.
|
|
582
|
+
*/
|
|
583
|
+
interface MidnightNetwork {
|
|
584
|
+
readonly networkId: NetworkId;
|
|
585
|
+
readonly indexer: {
|
|
586
|
+
readonly queryURL: string;
|
|
587
|
+
readonly subscriptionURL: string;
|
|
588
|
+
};
|
|
589
|
+
readonly nodeURL: string;
|
|
590
|
+
readonly nodeWsURL: string;
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Public endpoints of the Midnight networks. Call the network to get its {@link MidnightNetwork}.
|
|
594
|
+
*
|
|
595
|
+
* `preview` is hosted by Midnight. `preprod` and `mainnet` are served by Blockfrost, so they take
|
|
596
|
+
* a Blockfrost project token for that network and put it on every URL as `?project_id=<token>`.
|
|
597
|
+
* The URLs then carry the token: remove it before you log them.
|
|
598
|
+
*
|
|
599
|
+
* These are defaults that can change between releases. To use other endpoints, pass your own
|
|
600
|
+
* {@link MidnightNetwork}. A browser dApp with a DApp Connector wallet takes its endpoints from the wallet
|
|
601
|
+
* with `dappConnectorNetwork` from `@midnightntwrk/midnight-js-dapp-connector-proof-provider`.
|
|
602
|
+
*
|
|
603
|
+
* @example
|
|
604
|
+
* ```typescript
|
|
605
|
+
* const preview = networks.preview();
|
|
606
|
+
* const mainnet = networks.mainnet(blockfrostMainnetProjectId);
|
|
607
|
+
* ```
|
|
608
|
+
*/
|
|
609
|
+
declare const networks: {
|
|
610
|
+
readonly preview: () => MidnightNetwork;
|
|
611
|
+
/**
|
|
612
|
+
* @throws InvalidArgumentError If `blockfrostProjectId` is empty or has whitespace around it.
|
|
613
|
+
*/
|
|
614
|
+
readonly preprod: (blockfrostProjectId: string) => MidnightNetwork;
|
|
615
|
+
/**
|
|
616
|
+
* @throws InvalidArgumentError If `blockfrostProjectId` is empty or has whitespace around it.
|
|
617
|
+
*/
|
|
618
|
+
readonly mainnet: (blockfrostProjectId: string) => MidnightNetwork;
|
|
619
|
+
};
|
|
620
|
+
|
|
621
|
+
declare const MIN_PASSWORD_LENGTH = 16;
|
|
622
|
+
declare const MIN_CHARACTER_CLASSES = 3;
|
|
623
|
+
declare const MAX_CONSECUTIVE_REPEATED = 3;
|
|
624
|
+
declare const MIN_SEQUENTIAL_LENGTH = 4;
|
|
625
|
+
/**
|
|
626
|
+
* Reason categories for password validation failures.
|
|
627
|
+
*/
|
|
628
|
+
type PasswordValidationFailure = 'missing' | 'too_short' | 'insufficient_classes' | 'repeated_characters' | 'sequential_pattern';
|
|
629
|
+
/**
|
|
630
|
+
* Thrown when a password does not satisfy the strength policy applied to
|
|
631
|
+
* private storage and export/import operations.
|
|
632
|
+
*/
|
|
633
|
+
declare class PasswordValidationError extends MidnightJsError {
|
|
634
|
+
readonly reason: PasswordValidationFailure;
|
|
635
|
+
readonly code: "MIDNIGHT_JS_U_PASSWORD_INVALID";
|
|
636
|
+
readonly category: _midnightntwrk_midnight_js_protocol_errors.MidnightJsErrorCategory;
|
|
637
|
+
constructor(message: string, reason: PasswordValidationFailure);
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* Shared password strength policy for private storage and export/import operations.
|
|
641
|
+
* Throws {@link PasswordValidationError} on the first violated rule.
|
|
642
|
+
*/
|
|
643
|
+
declare const validatePassword: (password: string) => void;
|
|
644
|
+
|
|
645
|
+
declare const MAX_SAFE_NAME_LENGTH = 255;
|
|
646
|
+
/**
|
|
647
|
+
* Asserts that `name` is safe to use as a single path segment or URL path
|
|
648
|
+
* component. Rejects traversal payloads (`.`, `..`, separators), URL-encoded
|
|
649
|
+
* characters, null bytes, whitespace, empty strings, and names longer than
|
|
650
|
+
* {@link MAX_SAFE_NAME_LENGTH}.
|
|
651
|
+
*
|
|
652
|
+
* @param name The value to validate.
|
|
653
|
+
* @param label Human-readable name of the parameter (for error messages).
|
|
654
|
+
* @throws InvalidArgumentError if `name` fails validation.
|
|
655
|
+
*/
|
|
656
|
+
declare function assertSafeName(name: string, label: string): void;
|
|
657
|
+
/**
|
|
658
|
+
* Asserts that `version` is a valid SemVer-style version string of the shape
|
|
659
|
+
* `MAJOR.MINOR.PATCH` with an optional pre-release suffix
|
|
660
|
+
* (`-[A-Za-z0-9._-]+`). Build metadata (`+...`) is intentionally not
|
|
661
|
+
* supported because compactc releases do not use it.
|
|
662
|
+
*
|
|
663
|
+
* @param version The version string to validate.
|
|
664
|
+
* @param label Human-readable name of the parameter (for error messages).
|
|
665
|
+
* @throws InvalidArgumentError if `version` is not SemVer-shaped.
|
|
666
|
+
*/
|
|
667
|
+
declare function assertSemVer(version: string, label: string): void;
|
|
668
|
+
/**
|
|
669
|
+
* Emits a `console.warn` when `url` uses an unencrypted scheme (`http:` or `ws:`)
|
|
670
|
+
* targeting a non-loopback host. No-op for encrypted schemes (`https:`, `wss:`),
|
|
671
|
+
* other schemes, and unparseable input.
|
|
672
|
+
*
|
|
673
|
+
* Intended to be called once at provider-factory construction time so
|
|
674
|
+
* misconfigured remote endpoints surface immediately rather than after sensitive
|
|
675
|
+
* payloads are transmitted in clear text. As a diagnostic helper it never throws —
|
|
676
|
+
* an unparseable URL will produce errors through other channels (the protocol
|
|
677
|
+
* checks at every call site already throw `InvalidProtocolSchemeError`), and
|
|
678
|
+
* crashing the factory from a warning helper would be worse than silence.
|
|
679
|
+
*
|
|
680
|
+
* @param url An absolute URL string to inspect (e.g. `https://indexer.example/graphql`).
|
|
681
|
+
* @param label Human-readable label used in the warning (e.g. "indexer query URL").
|
|
682
|
+
*/
|
|
683
|
+
declare function warnIfInsecureRemoteUrl(url: string, label: string): void;
|
|
684
|
+
|
|
685
|
+
declare class TagParseError extends MidnightJsError {
|
|
686
|
+
readonly code: "MIDNIGHT_JS_U_TAG_PARSE_FAILED";
|
|
687
|
+
readonly category: _midnightntwrk_midnight_js_protocol_errors.MidnightJsErrorCategory;
|
|
688
|
+
constructor(message: string, options?: {
|
|
689
|
+
cause: unknown;
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* Result of {@link parseSerializedTag}. `namespace` and `version` are the two
|
|
694
|
+
* segments of the `namespace:version:` prefix; `tag` is their `:`-joined
|
|
695
|
+
* form, kept for convenience where callers just want the whole prefix.
|
|
696
|
+
* `body` is an independent copy of the bytes following the prefix — it does
|
|
697
|
+
* not alias the input buffer.
|
|
698
|
+
*/
|
|
699
|
+
interface ParsedSerializedTag {
|
|
700
|
+
readonly namespace: string;
|
|
701
|
+
readonly version: string;
|
|
702
|
+
readonly tag: string;
|
|
703
|
+
readonly body: Uint8Array;
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Parses the `namespace:version:` prefix off the front of a serialized
|
|
707
|
+
* value's raw bytes.
|
|
708
|
+
*
|
|
709
|
+
* Only the first {@link MAX_TAG_PREFIX_BYTES} (64) bytes are ever scanned —
|
|
710
|
+
* this throws {@link TagParseError} without reading further into the buffer
|
|
711
|
+
* if no well-formed prefix is found there, so an attacker cannot force a
|
|
712
|
+
* full-buffer scan by omitting the tag. Both `namespace` and `version` must
|
|
713
|
+
* be non-empty and match `/^[a-z0-9_[\](),-]+$/i` — the character set the
|
|
714
|
+
* ledger runtimes actually emit, brackets and parentheses included. Anything
|
|
715
|
+
* else (whitespace, and control characters, which could otherwise be used to
|
|
716
|
+
* inject fake log lines) throws {@link TagParseError}. `body` is a `.slice()` copy, so it is
|
|
717
|
+
* isolated from the input buffer the caller passed in.
|
|
718
|
+
*/
|
|
719
|
+
declare const parseSerializedTag: (bytes: Uint8Array) => ParsedSerializedTag;
|
|
720
|
+
|
|
721
|
+
/**
|
|
722
|
+
* Determines whether `value` is a structurally valid signing key of the shape
|
|
723
|
+
* `{ tag: 'schnorr' | 'ecdsa', value: <hex> }`, where `value` is a 32-byte key
|
|
724
|
+
* written as exactly 64 lowercase-or-uppercase hex characters.
|
|
725
|
+
*
|
|
726
|
+
* Pure predicate (never throws) so callers can attach their own domain error.
|
|
727
|
+
*
|
|
728
|
+
* @param value The value to validate (typically a parsed import payload entry).
|
|
729
|
+
* @returns `true` if `value` matches the structured signing-key shape.
|
|
730
|
+
*/
|
|
731
|
+
declare const isValidSigningKey: (value: unknown) => value is SigningKey;
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Asserts that a string represents a hex-encoded contract address.
|
|
735
|
+
*
|
|
736
|
+
* @param contractAddress The source string.
|
|
737
|
+
*
|
|
738
|
+
* @throws `InvalidArgumentError`
|
|
739
|
+
* `contractAddress` is not a correctly formatted {@link ContractAddress}.
|
|
740
|
+
*
|
|
741
|
+
* @internal
|
|
742
|
+
*/
|
|
743
|
+
declare function assertIsContractAddress(contractAddress: string): asserts contractAddress is ContractAddress;
|
|
744
|
+
|
|
745
|
+
/** File name of the `compactc`-emitted contract description, beside the integrity manifest. */
|
|
746
|
+
declare const ZK_CONTRACT_INFO_FILE_NAME = "contract-info.json";
|
|
747
|
+
/**
|
|
748
|
+
* Thrown when a `compactc` `contract-info.json` cannot be read as one, or declares no runtime
|
|
749
|
+
* version.
|
|
750
|
+
*
|
|
751
|
+
* Distinct from {@link ZkArtifactIntegrityError}: nothing here is a failed integrity check. The
|
|
752
|
+
* file is the artifact set's own statement of which toolchain produced it, and this error says
|
|
753
|
+
* that statement is missing or unreadable.
|
|
754
|
+
*/
|
|
755
|
+
declare class ZkArtifactContractInfoError extends MidnightJsError {
|
|
756
|
+
readonly code: "MIDNIGHT_JS_U_ZK_ARTIFACT_CONTRACT_INFO_INVALID";
|
|
757
|
+
readonly category: _midnightntwrk_midnight_js_protocol_errors.MidnightJsErrorCategory;
|
|
758
|
+
constructor(message: string, options?: ErrorOptions);
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* Reads the `runtime-version` a `compactc` `contract-info.json` declares.
|
|
762
|
+
*
|
|
763
|
+
* Only the runtime version is returned. It names the `compact-runtime` the artifact set was
|
|
764
|
+
* compiled against, which is what places the artifact on the ledger-era timeline.
|
|
765
|
+
*
|
|
766
|
+
* FAIL-CLOSED: a missing, empty or non-string `runtime-version` throws rather than answering
|
|
767
|
+
* `undefined`.
|
|
768
|
+
*
|
|
769
|
+
* @param rawJson The file's bytes, decoded as UTF-8 text.
|
|
770
|
+
* @returns The declared runtime version, verbatim.
|
|
771
|
+
* @throws ZkArtifactContractInfoError if the text is not a JSON object, or declares no usable
|
|
772
|
+
* `runtime-version`.
|
|
773
|
+
* @see {@link ArtifactRuntimeVersion} for why only this member is read, and why absence is a
|
|
774
|
+
* refusal rather than a default.
|
|
775
|
+
*/
|
|
776
|
+
declare function parseZkArtifactRuntimeVersion(rawJson: string): string;
|
|
777
|
+
|
|
778
|
+
/** Directory (relative to a provider's base location) holding the manifest. */
|
|
779
|
+
declare const ZK_MANIFEST_DIR = "compiler";
|
|
780
|
+
/** File name of the `compactc`-emitted integrity manifest. */
|
|
781
|
+
declare const ZK_MANIFEST_FILE_NAME = "contract-manifest.json";
|
|
782
|
+
/**
|
|
783
|
+
* How a provider reacts to a manifest that does not cover an artifact. A digest mismatch always
|
|
784
|
+
* throws (except `off`).
|
|
785
|
+
*
|
|
786
|
+
* - `require`: both a wholly absent manifest and a manifest without an entry for the artifact throw.
|
|
787
|
+
* - `require-if-present`: a wholly absent manifest warns; a manifest that exists must cover the
|
|
788
|
+
* artifact, so a missing entry throws. `compactc` only began emitting the manifest in 0.33, so
|
|
789
|
+
* this is the mode for artifacts compiled by a toolchain that never produced one.
|
|
790
|
+
* - `warn`: both cases warn.
|
|
791
|
+
* - `off`: no verification at all.
|
|
792
|
+
*/
|
|
793
|
+
type ZkArtifactIntegrityMode = 'require' | 'require-if-present' | 'warn' | 'off';
|
|
794
|
+
/** Integrity options shared by both ZK config providers' constructor option bags. */
|
|
795
|
+
interface ZkConfigIntegrityOptions {
|
|
796
|
+
/**
|
|
797
|
+
* Default `'require'` (fail-closed). Trust boundary: without {@link expectedManifestHash} the
|
|
798
|
+
* manifest is loaded from the same base location as the artifacts, so every verifying mode detects
|
|
799
|
+
* corruption (partial deploy, truncation, a stale or wrong artifact set) but NOT an adversary who
|
|
800
|
+
* can rewrite both the artifacts and the co-located manifest. Set {@link expectedManifestHash} to
|
|
801
|
+
* defend against that coordinated substitution.
|
|
802
|
+
*/
|
|
803
|
+
readonly verify?: ZkArtifactIntegrityMode;
|
|
804
|
+
/**
|
|
805
|
+
* SHA-256 hex of the manifest file's bytes, pinned by the application at build time. This is the
|
|
806
|
+
* only mode that resists a coordinated swap of the artifacts and their co-located manifest: it
|
|
807
|
+
* anchors the whole chain to a hash the application controls rather than one fetched alongside the
|
|
808
|
+
* artifacts it certifies.
|
|
809
|
+
*/
|
|
810
|
+
readonly expectedManifestHash?: string;
|
|
811
|
+
/** Warning sink for `warn` mode. Default: `console.warn`. */
|
|
812
|
+
readonly onWarn?: (message: string) => void;
|
|
813
|
+
}
|
|
814
|
+
/** Thrown when a ZK artifact (or the manifest itself) fails integrity verification. */
|
|
815
|
+
declare class ZkArtifactIntegrityError extends MidnightJsError {
|
|
816
|
+
readonly code: "MIDNIGHT_JS_U_ZK_ARTIFACT_INTEGRITY_FAILED";
|
|
817
|
+
readonly category: _midnightntwrk_midnight_js_protocol_errors.MidnightJsErrorCategory;
|
|
818
|
+
constructor(message: string, options?: {
|
|
819
|
+
cause?: unknown;
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
/** A single file entry from the manifest. */
|
|
823
|
+
interface ZkArtifactManifestFile {
|
|
824
|
+
readonly size: number;
|
|
825
|
+
readonly hash: string;
|
|
826
|
+
}
|
|
827
|
+
/** The parsed manifest: metadata plus files flattened to `"<dir>/<fileName>"` keys. */
|
|
828
|
+
interface ZkArtifactManifest {
|
|
829
|
+
readonly version: string;
|
|
830
|
+
readonly compilerVersion?: string;
|
|
831
|
+
readonly languageVersion?: string;
|
|
832
|
+
readonly runtimeVersion?: string;
|
|
833
|
+
readonly files: ReadonlyMap<string, ZkArtifactManifestFile>;
|
|
834
|
+
}
|
|
835
|
+
/** Lowercase hex SHA-256 of the given bytes. */
|
|
836
|
+
declare const computeSha256Hex: (bytes: Uint8Array) => string;
|
|
837
|
+
/**
|
|
838
|
+
* Parses a `compactc` `contract-manifest.json`. Asserts `manifest-version === '1'`, flattens exactly
|
|
839
|
+
* one directory level into `"<dir>/<fileName>"` keys (nested sub-directories are ignored), validates
|
|
840
|
+
* each file entry, and throws {@link ZkArtifactIntegrityError} on any structural violation. A
|
|
841
|
+
* key repeated within one object also throws, so a manifest pinned by its hash cannot certify an
|
|
842
|
+
* entry other than the one a reader of its text sees.
|
|
843
|
+
*/
|
|
844
|
+
declare function parseZkArtifactManifest(rawJson: string): ZkArtifactManifest;
|
|
845
|
+
/** Verifies raw manifest bytes against a build-time pin. Throws on mismatch. */
|
|
846
|
+
declare function assertManifestHash(rawBytes: Uint8Array, expectedHash: string): void;
|
|
847
|
+
/**
|
|
848
|
+
* Verifies one artifact's bytes against the manifest entry for `relativePath`.
|
|
849
|
+
* - `off`: no-op.
|
|
850
|
+
* - no manifest at all: `require` throws, every other mode warns and returns.
|
|
851
|
+
* - manifest present but no entry for the artifact: `require` and `require-if-present` throw,
|
|
852
|
+
* `warn` warns and returns.
|
|
853
|
+
* - length or digest mismatch: always throws (except `off`). Length is checked first as a cheap
|
|
854
|
+
* pre-hash guard so a truncated artifact fails with a clear "expected N bytes" error.
|
|
855
|
+
*/
|
|
856
|
+
declare function verifyZkArtifactIntegrity(params: {
|
|
857
|
+
readonly manifest: ZkArtifactManifest | undefined;
|
|
858
|
+
readonly relativePath: string;
|
|
859
|
+
readonly bytes: Uint8Array;
|
|
860
|
+
readonly mode: ZkArtifactIntegrityMode;
|
|
861
|
+
readonly onWarn?: (message: string) => void;
|
|
862
|
+
}): void;
|
|
863
|
+
|
|
864
|
+
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 };
|
|
865
|
+
export type { CallSiteContext, Classification, ContractsErrorCode, DeserializationCallSite, DeserializationContext, Direction, ExtractedInfo, MidnightJsErrorCode, MidnightNetwork, ParsedHexString, ParsedSerializedTag, PasswordValidationFailure, PatternEntry, SourceLibrary, UtilsErrorCode, ZkArtifactIntegrityMode, ZkArtifactManifest, ZkArtifactManifestFile, ZkConfigIntegrityOptions };
|