@midnightntwrk/compact-js-command 0.0.0-stage → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +14 -0
  2. package/README.md +263 -2
  3. package/dist/dts/effect/CompiledContractReflection.d.ts +66 -0
  4. package/dist/dts/effect/CompiledContractReflection.d.ts.map +1 -0
  5. package/dist/dts/effect/ConfigCompilationError.d.ts +38 -0
  6. package/dist/dts/effect/ConfigCompilationError.d.ts.map +1 -0
  7. package/dist/dts/effect/ConfigCompiler.d.ts +63 -0
  8. package/dist/dts/effect/ConfigCompiler.d.ts.map +1 -0
  9. package/dist/dts/effect/ConfigError.d.ts +34 -0
  10. package/dist/dts/effect/ConfigError.d.ts.map +1 -0
  11. package/dist/dts/effect/index.d.ts +73 -0
  12. package/dist/dts/effect/index.d.ts.map +1 -0
  13. package/dist/dts/effect/internal/args.d.ts +7 -0
  14. package/dist/dts/effect/internal/args.d.ts.map +1 -0
  15. package/dist/dts/effect/internal/circuitCommand.d.ts +2 -0
  16. package/dist/dts/effect/internal/circuitCommand.d.ts.map +1 -0
  17. package/dist/dts/effect/internal/command.d.ts +98 -0
  18. package/dist/dts/effect/internal/command.d.ts.map +1 -0
  19. package/dist/dts/effect/internal/commandConfigProvider.d.ts +2 -0
  20. package/dist/dts/effect/internal/commandConfigProvider.d.ts.map +1 -0
  21. package/dist/dts/effect/internal/compiledContractReflection.d.ts +5 -0
  22. package/dist/dts/effect/internal/compiledContractReflection.d.ts.map +1 -0
  23. package/dist/dts/effect/internal/deployCommand.d.ts +2 -0
  24. package/dist/dts/effect/internal/deployCommand.d.ts.map +1 -0
  25. package/dist/dts/effect/internal/encodedZswapLocalStateSchema.d.ts +129 -0
  26. package/dist/dts/effect/internal/encodedZswapLocalStateSchema.d.ts.map +1 -0
  27. package/dist/dts/effect/internal/era/binding.d.ts +270 -0
  28. package/dist/dts/effect/internal/era/binding.d.ts.map +1 -0
  29. package/dist/dts/effect/internal/era/eras.d.ts +16 -0
  30. package/dist/dts/effect/internal/era/eras.d.ts.map +1 -0
  31. package/dist/dts/effect/internal/era/registry.d.ts +2 -0
  32. package/dist/dts/effect/internal/era/registry.d.ts.map +1 -0
  33. package/dist/dts/effect/internal/era/v8.d.ts +2 -0
  34. package/dist/dts/effect/internal/era/v8.d.ts.map +1 -0
  35. package/dist/dts/effect/internal/era/v9.d.ts +2 -0
  36. package/dist/dts/effect/internal/era/v9.d.ts.map +1 -0
  37. package/dist/dts/effect/internal/json.d.ts +2 -0
  38. package/dist/dts/effect/internal/json.d.ts.map +1 -0
  39. package/dist/dts/effect/internal/maintainCircuitCommand.d.ts +2 -0
  40. package/dist/dts/effect/internal/maintainCircuitCommand.d.ts.map +1 -0
  41. package/dist/dts/effect/internal/maintainCommand.d.ts +2 -0
  42. package/dist/dts/effect/internal/maintainCommand.d.ts.map +1 -0
  43. package/dist/dts/effect/internal/maintainContractCommand.d.ts +2 -0
  44. package/dist/dts/effect/internal/maintainContractCommand.d.ts.map +1 -0
  45. package/dist/dts/effect/internal/options.d.ts +7 -0
  46. package/dist/dts/effect/internal/options.d.ts.map +1 -0
  47. package/dist/dts/index.d.ts +2 -0
  48. package/dist/dts/index.d.ts.map +1 -0
  49. package/dist/esm/effect/CompiledContractReflection.js +33 -0
  50. package/dist/esm/effect/CompiledContractReflection.js.map +1 -0
  51. package/dist/esm/effect/ConfigCompilationError.js +40 -0
  52. package/dist/esm/effect/ConfigCompilationError.js.map +1 -0
  53. package/dist/esm/effect/ConfigCompiler.js +73 -0
  54. package/dist/esm/effect/ConfigCompiler.js.map +1 -0
  55. package/dist/esm/effect/ConfigError.js +40 -0
  56. package/dist/esm/effect/ConfigError.js.map +1 -0
  57. package/dist/esm/effect/index.js +53 -0
  58. package/dist/esm/effect/index.js.map +1 -0
  59. package/dist/esm/effect/internal/args.js +25 -0
  60. package/dist/esm/effect/internal/args.js.map +1 -0
  61. package/dist/esm/effect/internal/circuitCommand.js +282 -0
  62. package/dist/esm/effect/internal/circuitCommand.js.map +1 -0
  63. package/dist/esm/effect/internal/command.js +316 -0
  64. package/dist/esm/effect/internal/command.js.map +1 -0
  65. package/dist/esm/effect/internal/commandConfigProvider.js +19 -0
  66. package/dist/esm/effect/internal/commandConfigProvider.js.map +1 -0
  67. package/dist/esm/effect/internal/compiledContractReflection.js +296 -0
  68. package/dist/esm/effect/internal/compiledContractReflection.js.map +1 -0
  69. package/dist/esm/effect/internal/deployCommand.js +68 -0
  70. package/dist/esm/effect/internal/deployCommand.js.map +1 -0
  71. package/dist/esm/effect/internal/encodedZswapLocalStateSchema.js +51 -0
  72. package/dist/esm/effect/internal/encodedZswapLocalStateSchema.js.map +1 -0
  73. package/dist/esm/effect/internal/era/binding.js +16 -0
  74. package/dist/esm/effect/internal/era/binding.js.map +1 -0
  75. package/dist/esm/effect/internal/era/eras.js +50 -0
  76. package/dist/esm/effect/internal/era/eras.js.map +1 -0
  77. package/dist/esm/effect/internal/era/registry.js +46 -0
  78. package/dist/esm/effect/internal/era/registry.js.map +1 -0
  79. package/dist/esm/effect/internal/era/v8.js +75 -0
  80. package/dist/esm/effect/internal/era/v8.js.map +1 -0
  81. package/dist/esm/effect/internal/era/v9.js +61 -0
  82. package/dist/esm/effect/internal/era/v9.js.map +1 -0
  83. package/dist/esm/effect/internal/json.js +41 -0
  84. package/dist/esm/effect/internal/json.js.map +1 -0
  85. package/dist/esm/effect/internal/maintainCircuitCommand.js +62 -0
  86. package/dist/esm/effect/internal/maintainCircuitCommand.js.map +1 -0
  87. package/dist/esm/effect/internal/maintainCommand.js +35 -0
  88. package/dist/esm/effect/internal/maintainCommand.js.map +1 -0
  89. package/dist/esm/effect/internal/maintainContractCommand.js +64 -0
  90. package/dist/esm/effect/internal/maintainContractCommand.js.map +1 -0
  91. package/dist/esm/effect/internal/options.js +137 -0
  92. package/dist/esm/effect/internal/options.js.map +1 -0
  93. package/dist/esm/index.js +44 -0
  94. package/dist/esm/index.js.map +1 -0
  95. package/dist/esm/package.json +4 -0
  96. package/effect/CompiledContractReflection/package.json +5 -0
  97. package/effect/ConfigCompilationError/package.json +5 -0
  98. package/effect/ConfigCompiler/package.json +5 -0
  99. package/effect/ConfigError/package.json +5 -0
  100. package/effect/index/package.json +5 -0
  101. package/effect/package.json +5 -0
  102. package/package.json +96 -4
@@ -0,0 +1,316 @@
1
+ /*
2
+ * This file is part of midnight-sdk.
3
+ * Copyright (C) 2025 Midnight Foundation
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * You may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ * Unless required by applicable law or agreed to in writing, software
10
+ * distributed under the License is distributed on an "AS IS" BASIS,
11
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ * See the License for the specific language governing permissions and
13
+ * limitations under the License.
14
+ */
15
+ import { NodeContext } from '@effect/platform-node';
16
+ import * as Ansi from '@effect/printer-ansi/Ansi';
17
+ import * as Doc from '@effect/printer-ansi/AnsiDoc';
18
+ import * as Configuration from '@midnight-ntwrk/platform-js/effect/Configuration';
19
+ import { ContractExecutableRuntime } from '@midnightntwrk/compact-js/effect';
20
+ import { ZKFileConfiguration } from '@midnightntwrk/compact-js-node/effect';
21
+ import { ConfigError as EffectConfigError, Console, DateTime, Duration, Effect, Layer } from 'effect';
22
+ import * as CompiledContractReflection from '../CompiledContractReflection.js';
23
+ import * as ConfigCompilationError from '../ConfigCompilationError.js';
24
+ import * as ConfigCompiler from '../ConfigCompiler.js';
25
+ import * as ConfigError from '../ConfigError.js';
26
+ import * as CommandConfigProvider from './commandConfigProvider.js';
27
+ import * as InternalOptions from './options.js';
28
+ /** How far into the future a generated intent's TTL is set. */
29
+ const INTENT_TTL = Duration.minutes(10);
30
+ /**
31
+ * Applies a duration to the current date/time, returning a date/time that is in the future.
32
+ *
33
+ * @param duration A `Duration` describing how far into the future the returned date/time should be.
34
+ * @returns An `Effect` that yields a `Date` that will be in the future from `duration`.
35
+ */
36
+ const ttl = (duration) => DateTime.now.pipe(Effect.map((utcNow) => DateTime.toDate(DateTime.addDuration(utcNow, duration))));
37
+ /**
38
+ * Builds the shared intent operations for one era.
39
+ *
40
+ * @param ledger The era's `Ledger` facade — `@midnightntwrk/compact-js/v8/effect`'s or
41
+ * `/v9/effect`'s. The era arrives as an argument here exactly as it does in `compact-js`'s
42
+ * `internal/executable.ts`; nothing in this module names one.
43
+ *
44
+ * @internal
45
+ */
46
+ export const makeIntents = (ledger) => {
47
+ const tryLedger = ledger.tryConvert;
48
+ return {
49
+ tryLedger,
50
+ newIntent: () => ttl(INTENT_TTL).pipe(Effect.flatMap((date) => tryLedger('Failed to create intent', () => ledger.Intent.new(date)))),
51
+ serializeIntent: (intent) => tryLedger('Failed to serialize the intent', () => intent.serialize())
52
+ };
53
+ };
54
+ /**
55
+ * How many links of a cause chain are rendered before the walk gives up.
56
+ *
57
+ * @remarks
58
+ * A cap rather than a cycle guard alone: a chain can be unbounded without repeating an object
59
+ * (each link freshly wrapping the last), and a report long enough to scroll the real failure off
60
+ * the terminal is no more use than one that overflows the stack.
61
+ */
62
+ const MAX_CAUSE_DEPTH = 16;
63
+ /**
64
+ * Renders a link in a cause chain as text.
65
+ *
66
+ * @remarks
67
+ * `Doc.text` throws on a non-string, and a cause is not necessarily an `Error`:
68
+ * `ContractExecutable.circuit` maps a rejected witness with `Effect.tryPromise({ catch: identity })`,
69
+ * so a witness that does `throw 'insufficient balance'` puts a bare string in the chain. The
70
+ * reporter is what turns a failure into output, so a throw *here* is the silent exit it exists to
71
+ * prevent — it escapes {@link invocationHandler}'s `catchAll` as a defect.
72
+ *
73
+ * Hence the `try`: `String(x)` is not total. A null-prototype object — which is what a witness
74
+ * rejecting with `Object.create(null)` puts in the chain — throws
75
+ * `TypeError: Cannot convert object to primitive value`, as does any value whose `toString` throws.
76
+ * `JSON.stringify` is preferred over `String` for objects because `String({ code: 42 })` is
77
+ * `'[object Object]'`: a printed line with no diagnostic content, which reports the failure while
78
+ * losing the only part of it that identifies the fault.
79
+ */
80
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
81
+ const messageOf = (errOrCause) => {
82
+ if (typeof errOrCause?.message === 'string') {
83
+ return errOrCause.message;
84
+ }
85
+ try {
86
+ return errOrCause !== null && typeof errOrCause === 'object'
87
+ ? (JSON.stringify(errOrCause) ?? Object.prototype.toString.call(errOrCause))
88
+ : String(errOrCause);
89
+ }
90
+ catch {
91
+ // Unserializable (cyclic, a throwing getter, a bigint field) or unprintable. The tag is poor
92
+ // output, but it is output: the alternative is a defect in the one function that cannot fail.
93
+ return Object.prototype.toString.call(errOrCause);
94
+ }
95
+ };
96
+ /**
97
+ * The next link of a cause chain.
98
+ *
99
+ * @remarks
100
+ * compact-runtime's `ModuleResolutionError` keeps what a provider threw, or what loading a callee's
101
+ * module rejected with, on `failure.cause` rather than `cause`, therefore the walk reads it there
102
+ * too. It is recognised by the flag `ModuleResolutionError.is` reads, because the error may come
103
+ * from another copy of the runtime.
104
+ */
105
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
106
+ const causeOf = (err) => err?.cause || (err?.isModuleResolutionError === true ? err.failure?.cause : undefined);
107
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
108
+ const reportCausableError = (err) => Effect.gen(function* () {
109
+ const buildCauseDocs = () => {
110
+ const docs = [];
111
+ // A cause chain is user-supplied data, not a structure this package controls: wrapping an
112
+ // error in its own cause is an ordinary mistake, and the walk's only terminating condition is
113
+ // a falsy `.cause`. Unbounded, that recurses until the stack gives out — a defect inside the
114
+ // reporter, which is precisely the silent exit it exists to prevent.
115
+ const seen = new WeakSet();
116
+ const buildCauseDoc = (errOrDoc, depth) => {
117
+ if (Doc.isDoc(errOrDoc)) {
118
+ docs.push(errOrDoc);
119
+ return;
120
+ }
121
+ if (errOrDoc !== null && typeof errOrDoc === 'object') {
122
+ if (seen.has(errOrDoc)) {
123
+ docs.push(Doc.text('(cause chain is circular)'));
124
+ return;
125
+ }
126
+ seen.add(errOrDoc);
127
+ }
128
+ docs.push(Doc.text(messageOf(errOrDoc)));
129
+ const next = causeOf(errOrDoc);
130
+ if (next) {
131
+ if (depth >= MAX_CAUSE_DEPTH) {
132
+ docs.push(Doc.text(`(cause chain truncated at ${MAX_CAUSE_DEPTH} entries)`));
133
+ return;
134
+ }
135
+ buildCauseDoc(next, depth + 1);
136
+ }
137
+ };
138
+ if (err !== null && typeof err === 'object') {
139
+ seen.add(err);
140
+ }
141
+ buildCauseDoc(causeOf(err), 1);
142
+ return docs;
143
+ };
144
+ let errorDoc = Doc.text(messageOf(err));
145
+ if (causeOf(err)) {
146
+ errorDoc = errorDoc.pipe(Doc.catWithLineBreak(Doc.annotate(Doc.text('(cause)'), Ansi.italicized)), Doc.catWithLineBreak(Doc.hsep([
147
+ Doc.text('..'),
148
+ Doc.align(Doc.vsep(buildCauseDocs()))
149
+ ])));
150
+ }
151
+ yield* Console.log(Doc.render(errorDoc, { style: 'pretty' }));
152
+ if (!process.env['VITEST']) {
153
+ process.exit(1); // Terminate with non-zero exit code on any causable error (if not running inside a test).
154
+ }
155
+ });
156
+ /**
157
+ * Pretty prints a configuration error from {@link ConfigCompiler.ConfigCompiler | ConfigCompiler} implementations.
158
+ *
159
+ * @param err The {@link ConfigError.ConfigError | ConfigError} or
160
+ * {@link ConfigCompilationError.ConfigCompilationError | ConfigCompilationError} to report for.
161
+ * @returns An `Effect` that writes `err` to the console.
162
+ */
163
+ export const reportContractConfigError = (err) => Effect.gen(function* () {
164
+ if (err.cause && err.cause instanceof ConfigCompilationError.ConfigCompilationError) {
165
+ return yield* reportCausableError({
166
+ message: err.message,
167
+ cause: Doc.annotate(Doc.text(err.cause.message), Ansi.italicized).pipe(Doc.catWithLineBreak(Doc.hsep([
168
+ Doc.text('..'),
169
+ Doc.align(Doc.vsep(err.cause.diagnostics.map((d) => Doc.text(d.messageText))))
170
+ ])))
171
+ });
172
+ }
173
+ yield* reportCausableError(err);
174
+ });
175
+ const ConfigErrorType = {
176
+ MissingData: 1,
177
+ InvalidData: 2,
178
+ UnsupportedData: 4
179
+ };
180
+ const reduceConfigError = (err) => EffectConfigError.reduceWithContext(err, undefined, {
181
+ andCase: (_, left, right) => [left[0] | right[0], [...left[1], ...right[1]]],
182
+ orCase: (_, left, right) => left || right,
183
+ missingDataCase: (_, path) => [ConfigErrorType.MissingData, [`Missing data at path '${path.join(',')}'`]],
184
+ invalidDataCase: (_, path) => [ConfigErrorType.InvalidData, [`Invalid data at path '${path.join(',')}'`]],
185
+ sourceUnavailableCase: (_, path, message, cause) => [ConfigErrorType.MissingData, [`The underlying source for data at path '${path.join(',')}' could not be found`, message, cause.toString()]],
186
+ unsupportedCase: (_, path) => [ConfigErrorType.UnsupportedData, [`Unsupported data at path '${path.join(',')}'`]],
187
+ });
188
+ /**
189
+ * Pretty prints a configuration or contract execution error.
190
+ *
191
+ * @param err The {@link ContractExecutable.ContractExecutionError | ContractExecutionError} or `ConfigError` to
192
+ * report for.
193
+ * @returns An `Effect` that writes `err` to the console.
194
+ */
195
+ export const reportContractExecutionError = (err) => Effect.gen(function* () {
196
+ if (EffectConfigError.isConfigError(err)) {
197
+ const [errorType, messages] = reduceConfigError(err);
198
+ yield* reportCausableError({
199
+ message: 'Invalid, missing, or unsupported configuration',
200
+ cause: Doc.vsep(messages.map(Doc.text))
201
+ });
202
+ if (errorType & ConfigErrorType.InvalidData || errorType & ConfigErrorType.MissingData) {
203
+ yield* Console.log();
204
+ yield* Console.log(Doc.render(Doc.vsep([
205
+ Doc.text('The reported error indicates that configuration may be missing, or is invalid.'),
206
+ Doc.text('Check the values provided in the \'config\' property of the specified \'contract.config.ts\' file,'),
207
+ Doc.text('or the supplied environment variables, or the values supplied as options on the command line.')
208
+ ]), { style: 'compact' }));
209
+ }
210
+ if (errorType & ConfigErrorType.UnsupportedData) {
211
+ yield* Console.log();
212
+ yield* Console.log(Doc.render(Doc.vsep([
213
+ Doc.text('The reported error indicates that unsupported or incompatible configuration values was detected.'),
214
+ Doc.text('Check the values (along with their formats and lengths), provided in the \'config\' property of'),
215
+ Doc.text('the specified \'contract.config.ts\' file, or the supplied environment variables, or the values'),
216
+ Doc.text('supplied as options on the command line.')
217
+ ]), { style: 'compact' }));
218
+ }
219
+ return;
220
+ }
221
+ yield* reportCausableError(err);
222
+ });
223
+ /**
224
+ * Reports a defect — a failure the command did not model — rather than letting it exit silently.
225
+ *
226
+ * @remarks
227
+ * The backstop for the whole CLI. `Effect.catchAll` covers the *failure* channel only, so a throw
228
+ * evaluated in an `Effect.gen` body passes every recovery this module installs and reaches
229
+ * `NodeRuntime.runMain({ disableErrorReporting: true })` in `src/index.ts`, which exits non-zero
230
+ * printing nothing. That is the worst outcome the CLI can produce: the user has no message, no exit
231
+ * context, and nothing to report.
232
+ *
233
+ * Individual defect sources are worth fixing at the source — and are, as they are found — but this
234
+ * exists so that the *next* one is a legible bug report instead of a silent exit. The wording
235
+ * separates "your input was wrong" from "this is our bug", because a defect is always the latter.
236
+ *
237
+ * @internal
238
+ */
239
+ export const reportUnhandledDefect = (defect) => reportCausableError({
240
+ message: 'Internal error: the command failed in a way it does not handle. Please report this.',
241
+ cause: defect
242
+ });
243
+ /** @internal */
244
+ export const GlobalOptions = {
245
+ config: InternalOptions.config,
246
+ coinPublicKey: InternalOptions.coinPublicKey,
247
+ ledgerEra: InternalOptions.ledgerEra
248
+ };
249
+ /**
250
+ * Creates a default layer that provides services for executing Compact contracts via a command line.
251
+ *
252
+ * @param configProvider
253
+ * @param zkBaseFolderPath A base path to a folder containing the ZK assets for the contract that will be in
254
+ * scope during invocation
255
+ *
256
+ * @category layers
257
+ */
258
+ export const layer = (configProvider, zkBaseFolderPath) => Layer.mergeAll(ZKFileConfiguration.layer(zkBaseFolderPath), Configuration.layer).pipe(Layer.provideMerge(NodeContext.layer), Layer.provide(Layer.setConfigProvider(configProvider)));
259
+ /**
260
+ * Fails when the era `--ledger-era` selected and the era the configuration's executable was built
261
+ * for are not the same.
262
+ *
263
+ * @remarks
264
+ * There are two era choices in play and the CLI only makes one of them. `--ledger-era` picks the
265
+ * era of the intents, state files and conversions the command produces; the *executable's* era was
266
+ * fixed by the import at the top of `contract.config.ts` (`/v8/effect` or `/v9/effect`). Left
267
+ * unreconciled, a disagreement surfaces several conversions later as a WASM rejection — `expected
268
+ * instance of ContractState` — whose message names neither era and points at neither decision.
269
+ *
270
+ * An executable from a compact-js older than `ContractExecutable.era` reports `undefined`; that is
271
+ * treated as "unknown", not as a mismatch, so a configuration that worked before this check existed
272
+ * still works. Such a mismatch still fails, just at the boundary and with the older message.
273
+ */
274
+ const checkEra = (configFilePath, selected, executable) => executable.era === undefined || executable.era.ledger === selected
275
+ ? Effect.void
276
+ : ConfigError.make(`The contract configuration '${configFilePath}' builds its executable against ledger era ` +
277
+ `${executable.era.ledger}, but --ledger-era selected ${selected}. Import ` +
278
+ `'@midnightntwrk/compact-js/v${selected}/effect' in the configuration, or run with ` +
279
+ `--ledger-era ${executable.era.ledger}.`);
280
+ /**
281
+ * Creates an appropriate runtime for a command handler, having first resolved the era the
282
+ * invocation selected.
283
+ *
284
+ * @remarks
285
+ * The parameter is a *selector* rather than a handler because the handler is era-specific: each
286
+ * command module is a factory applied once per era (`internal/era/v8.ts`, `internal/era/v9.ts`),
287
+ * and this is where `--ledger-era` stops being a validated-then-discarded option and becomes the
288
+ * choice of which of those applications runs.
289
+ *
290
+ * It takes the era as a *number* and resolves nothing itself, so this module does not import the
291
+ * era registry. That keeps the graph acyclic — the registry imports the command modules, which
292
+ * import this one — and leaves `effect/index.ts`, which is downstream of all of them, as the single
293
+ * place where a command is tied to the handler it wants.
294
+ *
295
+ * @param handlerForEra Picks this command's handler for the selected ledger era, e.g.
296
+ * `(era) => EraRegistry.forLedgerEra(era).circuit`.
297
+ * @returns An `Effect` that adapts the selected handler by compiling the configured configuration
298
+ * file, reconciling its era against the selected one, and invoking the handler within an
299
+ * appropriate `ContractExecutableRuntime`.
300
+ */
301
+ export const invocationHandler = (handlerForEra) => (inputs) => Effect.gen(function* () {
302
+ // Option parsing has already rejected any era this build has no command set for, so the
303
+ // selector below cannot fail to resolve one.
304
+ const handler = handlerForEra(inputs.ledgerEra);
305
+ const configCompiler = yield* ConfigCompiler.ConfigCompiler;
306
+ const moduleSpec = yield* configCompiler.compile(inputs.config);
307
+ const { moduleImportDirectoryPath, module: { default: contractModule } } = moduleSpec;
308
+ yield* checkEra(inputs.config, inputs.ledgerEra, contractModule.contractExecutable);
309
+ const contractRuntime = ContractExecutableRuntime.make(layer(CommandConfigProvider.make(contractModule.config ?? {}, InternalOptions.asConfigProvider(inputs)), moduleImportDirectoryPath));
310
+ yield* handler(inputs, moduleSpec).pipe(Effect.provide(CompiledContractReflection.layer(moduleImportDirectoryPath).pipe(Layer.provideMerge(NodeContext.layer))), contractRuntime.runFork, Effect.catchAll(reportContractExecutionError));
311
+ }).pipe(Effect.catchAll(reportContractConfigError),
312
+ // Outermost, so it covers the handler, the config compilation and the era reconciliation
313
+ // alike. `catchAll` above it sees failures only; without this, a defect from any of them is
314
+ // an exit code and an empty terminal.
315
+ Effect.catchAllDefect(reportUnhandledDefect));
316
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command.js","sourceRoot":"","sources":["../../../../src/effect/internal/command.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAKH,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,KAAK,IAAI,MAAM,2BAA2B,CAAC;AAClD,OAAO,KAAK,GAAG,MAAM,8BAA8B,CAAC;AACpD,OAAO,KAAK,aAAa,MAAM,kDAAkD,CAAC;AAClF,OAAO,EAA2B,yBAAyB,EAAmD,MAAM,kCAAkC,CAAC;AACvJ,OAAO,EAAE,mBAAmB,EAAE,MAAM,uCAAuC,CAAC;AAC5E,OAAO,EAAE,WAAW,IAAI,iBAAiB,EAAuB,O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,cAAc,CAAC,kBAAkB,CAAC,CAAC;IAEpF,MAAM,eAAe,GAAG,yBAAyB,CAAC,IAAI,CACpD,KAAK,CACH,qBAAqB,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM,IAAI,EAAE,EAAE,eAAe,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC,EACjG,yBAAyB,CAC1B,CACF,CAAC;IAEF,KAAK,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,IAAI,CACrC,MAAM,CAAC,OAAO,CAAC,0BAA0B,CAAC,KAAK,CAAC,yBAAyB,CAAC,CAAC,IAAI,CAC7E,KAAK,CAAC,YAAY,CAAC,WAAW,CAAC,KAAK,CAAC,CACtC,CAAC,EACF,eAAe,CAAC,OAAO,EACvB,MAAM,CAAC,QAAQ,CAAC,4BAA4B,CAAC,CAC9C,CAAC;AACJ,CAAC,CAAC,CAAC,IAAI,CACL,MAAM,CAAC,QAAQ,CAAC,yBAAyB,CAAC;AAC1C,yFAAyF;AACzF,4FAA4F;AAC5F,sCAAsC;AACtC,MAAM,CAAC,cAAc,CAAC,qBAAqB,CAAC,CAC7C,CAAC"}
@@ -0,0 +1,19 @@
1
+ /*
2
+ * This file is part of midnight-sdk.
3
+ * Copyright (C) 2025 Midnight Foundation
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * You may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ * Unless required by applicable law or agreed to in writing, software
10
+ * distributed under the License is distributed on an "AS IS" BASIS,
11
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ * See the License for the specific language governing permissions and
13
+ * limitations under the License.
14
+ */
15
+ import * as Configuration from '@midnight-ntwrk/platform-js/effect/Configuration';
16
+ import { ConfigProvider } from 'effect';
17
+ /** @internal */
18
+ export const make = (jsonConfig, cliConfigProvider) => cliConfigProvider.pipe(ConfigProvider.orElse(() => Configuration.configProvider(jsonConfig)));
19
+ //# sourceMappingURL=commandConfigProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commandConfigProvider.js","sourceRoot":"","sources":["../../../../src/effect/internal/commandConfigProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,aAAa,MAAM,kDAAkD,CAAC;AAClF,OAAO,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAExC,gBAAgB;AAChB,MAAM,CAAC,MAAM,IAAI,GAEb,CAAC,UAAU,EAAE,iBAAiB,EAAE,EAAE,CAAC,iBAAiB,CAAC,IAAI,CACvD,cAAc,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC,CACtE,CAAC"}
@@ -0,0 +1,296 @@
1
+ /*
2
+ * This file is part of midnight-sdk.
3
+ * Copyright (C) 2025 Midnight Foundation
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * You may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ * Unless required by applicable law or agreed to in writing, software
10
+ * distributed under the License is distributed on an "AS IS" BASIS,
11
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ * See the License for the specific language governing permissions and
13
+ * limitations under the License.
14
+ */
15
+ import { FileSystem, Path } from '@effect/platform';
16
+ import * as Hex from '@midnight-ntwrk/platform-js/effect/Hex';
17
+ import { CompiledContract, ContractRuntimeError } from '@midnightntwrk/compact-js/effect';
18
+ import { Effect, Either, identity, Layer } from 'effect';
19
+ import pkg from 'json5';
20
+ import TS from 'typescript';
21
+ const { parse, stringify } = pkg;
22
+ import { MidnightBech32m, UnshieldedAddress } from '@midnightntwrk/wallet-sdk-address-format';
23
+ import * as CompiledContractReflection from "../CompiledContractReflection.js";
24
+ const CONTRACT_FOLDER = 'contract';
25
+ const CONTRACT_DECLARATION_FILE = 'index.d.ts';
26
+ const TRUE_OR_FALSE_REGEXP = /^(true|false)$/;
27
+ // Ceiling on consecutive alias and type-parameter resolutions. Those steps consume no input, so a
28
+ // cyclic alias (`type A = A`) would otherwise recurse until the stack overflows. Branches that do
29
+ // consume input reset the count, leaving deeply nested values bounded by the input itself.
30
+ const MAX_RESOLUTION_DEPTH = 64;
31
+ class BasicHost {
32
+ files;
33
+ #files;
34
+ constructor(files) {
35
+ this.files = files;
36
+ this.#files = { ...files };
37
+ }
38
+ getCurrentDirectory() {
39
+ return '';
40
+ }
41
+ getDefaultLibFileName(_) {
42
+ return 'lib';
43
+ }
44
+ getCompilationSettings() {
45
+ return TS.getDefaultCompilerOptions();
46
+ }
47
+ getScriptVersion(fileName) {
48
+ return String(this.files[fileName].version);
49
+ }
50
+ getScriptSnapshot(fileName) {
51
+ return this.files[fileName]?.file;
52
+ }
53
+ getScriptFileNames() {
54
+ return Object.keys(this.#files);
55
+ }
56
+ fileExists(path) {
57
+ return !!this.files[path];
58
+ }
59
+ readFile(path) {
60
+ const file = this.files[path].file;
61
+ return file?.getText(0, file?.getLength());
62
+ }
63
+ }
64
+ const parseBech32mToHex = (input) => Either.try({
65
+ try: () => {
66
+ const parsedBech32 = MidnightBech32m.parse(input);
67
+ return UnshieldedAddress.codec.decode(parsedBech32.network, parsedBech32).hexString;
68
+ },
69
+ catch: (error) => error instanceof Error ? error : new Error(String(error))
70
+ });
71
+ const typeNodeName = (type) => {
72
+ if (type.kind === TS.SyntaxKind.NumberKeyword)
73
+ return 'number';
74
+ if (type.kind === TS.SyntaxKind.BigIntKeyword)
75
+ return 'bigint';
76
+ if (type.kind === TS.SyntaxKind.StringKeyword)
77
+ return 'string';
78
+ if (type.kind === TS.SyntaxKind.BooleanKeyword)
79
+ return 'boolean';
80
+ if (type.kind === TS.SyntaxKind.ArrayType) {
81
+ return `${typeNodeName(type.elementType)}[]`;
82
+ }
83
+ if (type.kind === TS.SyntaxKind.TupleType) {
84
+ return `[${type.elements.map((_) => typeNodeName(_)).join(', ')}]`;
85
+ }
86
+ if (type.kind === TS.SyntaxKind.TypeLiteral) {
87
+ const typeLiteral = type;
88
+ return `{ ${typeLiteral.members.map((_) => `${_.name.escapedText.toString()}: ${typeNodeName(_.type)}`).join(', ')} }`;
89
+ }
90
+ if (TS.isTypeReferenceNode(type) && TS.isIdentifier(type.typeName)) {
91
+ const name = type.typeName.escapedText.toString();
92
+ const typeArgs = type.typeArguments?.map(typeNodeName) ?? [];
93
+ return typeArgs.length ? `${name}<${typeArgs.join(', ')}>` : name;
94
+ }
95
+ return '<unknown>';
96
+ };
97
+ // A source file's top-level type aliases by name, generic ones (`Maybe<T>`) included, so
98
+ // `transformParams` can resolve a named reference. Cached, since every reference looks one up.
99
+ const typeAliasCache = new WeakMap();
100
+ const getTypeAliases = (sourceFile) => {
101
+ const cached = typeAliasCache.get(sourceFile);
102
+ if (cached)
103
+ return cached;
104
+ const aliases = new Map();
105
+ for (const statement of sourceFile.statements) {
106
+ if (TS.isTypeAliasDeclaration(statement)) {
107
+ aliases.set(statement.name.escapedText.toString(), statement);
108
+ }
109
+ }
110
+ typeAliasCache.set(sourceFile, aliases);
111
+ return aliases;
112
+ };
113
+ const transformParams = // eslint-disable-line @typescript-eslint/no-explicit-any
114
+ (args, types, quotedStrings = false, bindings = new Map(), depth = 0) => {
115
+ // Recurse, rethrowing the typed error as an exception so it is caught by the enclosing
116
+ // `Either.try`. Used by the branches that decode a compound type element by element.
117
+ const transformOrThrow = (elemArgs, elemTypes, elemQuoted, elemBindings, elemDepth = 0) => {
118
+ if (elemDepth >= MAX_RESOLUTION_DEPTH) {
119
+ throw new SyntaxError(`Exceeded the maximum type alias resolution depth of ${MAX_RESOLUTION_DEPTH}; the declaration may contain a cyclic type alias`);
120
+ }
121
+ return Either.getOrThrowWith(transformParams(elemArgs, elemTypes, elemQuoted, elemBindings, elemDepth), identity);
122
+ };
123
+ if (args.length !== types.length) {
124
+ return Either.left(ContractRuntimeError.make(`Invalid number of arguments. Expected ${types.length} arguments, but got ${args.length}`));
125
+ }
126
+ const transformedArgs = []; // eslint-disable-line @typescript-eslint/no-explicit-any
127
+ for (let idx = 0; idx < types.length; idx++) {
128
+ const type = types[idx];
129
+ const transformedArg = Either.try({
130
+ try: () => {
131
+ if (type.kind === TS.SyntaxKind.NumberKeyword) {
132
+ const num = Number(args[idx]);
133
+ if (!Number.isFinite(num) || args[idx].trim() === '') {
134
+ throw new SyntaxError(`Cannot convert ${args[idx]} to a Number`);
135
+ }
136
+ return num;
137
+ }
138
+ if (type.kind === TS.SyntaxKind.BigIntKeyword) {
139
+ const input = quotedStrings ? parse(args[idx]) : args[idx];
140
+ if (typeof input === 'string') {
141
+ if (input.trim() === '') {
142
+ throw new SyntaxError(`Cannot convert ${args[idx]} to a BigInt`);
143
+ }
144
+ return BigInt(input);
145
+ }
146
+ if (typeof input === 'number') {
147
+ if (!Number.isInteger(input)) {
148
+ throw new SyntaxError(`Cannot convert ${args[idx]} to a BigInt`);
149
+ }
150
+ if (!Number.isSafeInteger(input)) {
151
+ throw new SyntaxError('Unsafe JSON number; pass bigint values as quoted decimal strings');
152
+ }
153
+ return BigInt(input);
154
+ }
155
+ throw new SyntaxError(`Cannot convert ${args[idx]} to a BigInt`);
156
+ }
157
+ if (type.kind === TS.SyntaxKind.StringKeyword) {
158
+ return quotedStrings ? args[idx].replaceAll('\'', '') : args[idx];
159
+ }
160
+ if (type.kind === TS.SyntaxKind.BooleanKeyword) {
161
+ if (!TRUE_OR_FALSE_REGEXP.test(args[idx]))
162
+ throw new SyntaxError(`Cannot convert ${args[idx]} to a Boolean`);
163
+ return args[idx] === 'true';
164
+ }
165
+ if (type.kind === TS.SyntaxKind.ArrayType) {
166
+ const arrayElems = parse(args[idx]);
167
+ if (!Array.isArray(arrayElems)) {
168
+ throw new SyntaxError(`Cannot convert ${args[idx]} to an array`);
169
+ }
170
+ return transformOrThrow(arrayElems.map((arrayElem) => stringify(arrayElem)), Array(arrayElems.length).fill(type.elementType), true, bindings);
171
+ }
172
+ if (type.kind === TS.SyntaxKind.TupleType) {
173
+ const tupleElems = parse(args[idx]);
174
+ if (!Array.isArray(tupleElems)) {
175
+ throw new SyntaxError(`Cannot convert ${args[idx]} to an array`);
176
+ }
177
+ return transformOrThrow(tupleElems.map((tupleElem) => stringify(tupleElem)), type.elements.map((elemType) => elemType), true, bindings);
178
+ }
179
+ if (type.kind === TS.SyntaxKind.TypeLiteral) {
180
+ const typeLiteral = type;
181
+ const srcObj = parse(args[idx]);
182
+ if (typeof srcObj !== 'object') {
183
+ throw new SyntaxError(`Cannot convert ${args[idx]} to an object literal`);
184
+ }
185
+ for (const member of typeLiteral.members) {
186
+ const propKey = member.name.escapedText.toString();
187
+ const propType = member.type;
188
+ const memberValue = transformOrThrow([stringify(srcObj[propKey])], [propType], true, bindings);
189
+ srcObj[propKey] = memberValue[0];
190
+ }
191
+ return srcObj;
192
+ }
193
+ if (type.kind === TS.SyntaxKind.TypeReference) {
194
+ const typeRef = type;
195
+ const typeName = typeRef.typeName;
196
+ if (TS.isIdentifier(typeName)) {
197
+ const name = typeName.escapedText.toString();
198
+ if (name === 'Uint8Array') {
199
+ const cleanInput = quotedStrings ? args[idx].replaceAll('\'', '') : args[idx];
200
+ const bech32Result = parseBech32mToHex(cleanInput);
201
+ const hexString = Either.match(bech32Result, {
202
+ onLeft: () => cleanInput,
203
+ onRight: (hex) => hex
204
+ });
205
+ return Either.match(Hex.parseHex(hexString), {
206
+ onRight: (parsedHex) => Buffer.from(parsedHex.byteChars, 'hex'),
207
+ onLeft: (parseErr) => {
208
+ throw new SyntaxError(`Cannot convert ${args[idx]} to a Uint8Array: ${parseErr.message}`);
209
+ }
210
+ });
211
+ }
212
+ // A reference to a generic type parameter (e.g. `T` in a `Maybe<T>` body): resolve the
213
+ // bound argument node in the environment it was captured in, then recurse.
214
+ const bound = bindings.get(name);
215
+ if (bound) {
216
+ return transformOrThrow([args[idx]], [bound.node], quotedStrings, bound.env, depth + 1)[0];
217
+ }
218
+ // Resolve a named alias and recurse, reusing the branches that already decode its body
219
+ // (e.g. `TypeLiteral` for a struct). For a generic alias (`Maybe<bigint>`) each type
220
+ // parameter binds to its type argument together with the current environment, so a
221
+ // parameter used as another generic's argument still resolves against the outer scope.
222
+ const aliasDecl = getTypeAliases(type.getSourceFile()).get(name);
223
+ if (aliasDecl) {
224
+ const typeParams = aliasDecl.typeParameters ?? [];
225
+ const typeArgs = typeRef.typeArguments ?? [];
226
+ // Parameters with a default may be omitted, as in TypeScript. Defaults are a
227
+ // suffix of the parameter list, so an omitted argument is always a defaulted one.
228
+ const requiredCount = typeParams.filter((typeParam) => !typeParam.default).length;
229
+ if (typeArgs.length < requiredCount || typeArgs.length > typeParams.length) {
230
+ const expected = requiredCount === typeParams.length
231
+ ? `${typeParams.length}`
232
+ : `${requiredCount} to ${typeParams.length}`;
233
+ throw new SyntaxError(`Cannot resolve ${typeNodeName(type)}: expected ${expected} type argument(s), but got ${typeArgs.length}`);
234
+ }
235
+ // A default is written in the alias's own scope, so it resolves against the
236
+ // bindings being built here; an explicit argument resolves in the caller's scope.
237
+ const aliasBindings = new Map();
238
+ typeParams.forEach((typeParam, typeParamIdx) => {
239
+ const typeArg = typeArgs[typeParamIdx];
240
+ aliasBindings.set(typeParam.name.escapedText.toString(), typeArg ? { node: typeArg, env: bindings } : { node: typeParam.default, env: aliasBindings });
241
+ });
242
+ return transformOrThrow([args[idx]], [aliasDecl.type], quotedStrings, aliasBindings, depth + 1)[0];
243
+ }
244
+ }
245
+ }
246
+ // Unsupported type: fail legibly instead of silently returning `undefined`.
247
+ throw new SyntaxError(`Cannot convert ${args[idx]}: unsupported argument type ${typeNodeName(type)}`);
248
+ },
249
+ catch: (err) => ContractRuntimeError.make(`Failed to parse argument with index ${idx}`, ContractRuntimeError.make(`Failed to parse string '${args[idx]}' as type of ${typeNodeName(type)}`, err))
250
+ });
251
+ if (Either.isLeft(transformedArg))
252
+ return transformedArg;
253
+ transformedArgs.push(transformedArg.right);
254
+ }
255
+ return Either.right(transformedArgs);
256
+ };
257
+ const makeArgumentParser = (path, fs, baseAssetFolderPath) => (compiledContract) => Effect.gen(function* () {
258
+ const assetsPath = CompiledContract.getCompiledAssetsPath(compiledContract);
259
+ const tsDeclFilePath = path.join(path.resolve(baseAssetFolderPath, assetsPath), CONTRACT_FOLDER, CONTRACT_DECLARATION_FILE);
260
+ const tsHost = new BasicHost({
261
+ [tsDeclFilePath]: {
262
+ file: TS.ScriptSnapshot.fromString(yield* fs.readFileString(tsDeclFilePath)),
263
+ version: 1
264
+ }
265
+ });
266
+ const tsLangService = TS.createLanguageService(tsHost, TS.createDocumentRegistry());
267
+ const sourceFile = tsLangService.getProgram().getSourceFile(tsDeclFilePath);
268
+ const impureCircuitsTypeNode = sourceFile?.statements.find((_) => TS.isTypeAliasDeclaration(_)
269
+ && _.name.escapedText === 'ImpureCircuits'
270
+ && _.type.kind === TS.SyntaxKind.TypeLiteral);
271
+ const circuitMethodSignatureNodes = impureCircuitsTypeNode.type.members;
272
+ const contractClassNode = sourceFile?.statements.find((_) => TS.isClassDeclaration(_) && _.name.escapedText === 'Contract');
273
+ const initialStateMethodSignatureNode = contractClassNode.members.find((_) => TS.isMethodDeclaration(_)
274
+ && _.name.escapedText === 'initialState');
275
+ return {
276
+ parseInitializationArgs: (args) => transformParams(args, initialStateMethodSignatureNode.parameters.slice(1).map((_) => _.type)),
277
+ // Generic in `K` to match `ArgumentParser.parseCircuitArgs`, whose return type is
278
+ // `CircuitParameters<C, K>`. A non-generic implementation cannot satisfy it — the
279
+ // assertion would have to widen `K` back to the whole circuit-id union.
280
+ parseCircuitArgs: (circuitId, args) => {
281
+ const circuitNode = circuitMethodSignatureNodes.find((_) => _.name.escapedText === circuitId);
282
+ if (!circuitNode) {
283
+ return Either.left(ContractRuntimeError.make(`Circuit '${circuitId}' not found on the Compact generated TypeScript declaration.`));
284
+ }
285
+ return transformParams(args, circuitNode.parameters.slice(1).map((_) => _.type));
286
+ }
287
+ };
288
+ });
289
+ export const layer = (baseAssetFolderPath = '.') => Layer.effect(CompiledContractReflection.CompiledContractReflection, Effect.gen(function* () {
290
+ const path = yield* Path.Path;
291
+ const fs = yield* FileSystem.FileSystem;
292
+ return CompiledContractReflection.CompiledContractReflection.of({
293
+ createArgumentParser: makeArgumentParser(path, fs, baseAssetFolderPath)
294
+ });
295
+ }));
296
+ //# sourceMappingURL=compiledContractReflection.js.map