@lionden/leo-compiler 0.1.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 (67) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +23 -0
  3. package/dist/abi-hash.d.ts +15 -0
  4. package/dist/abi-hash.d.ts.map +1 -0
  5. package/dist/abi-hash.js +75 -0
  6. package/dist/abi-hash.js.map +1 -0
  7. package/dist/abi-parser.d.ts +38 -0
  8. package/dist/abi-parser.d.ts.map +1 -0
  9. package/dist/abi-parser.js +513 -0
  10. package/dist/abi-parser.js.map +1 -0
  11. package/dist/abi-types.d.ts +111 -0
  12. package/dist/abi-types.d.ts.map +1 -0
  13. package/dist/abi-types.js +5 -0
  14. package/dist/abi-types.js.map +1 -0
  15. package/dist/cache.d.ts +27 -0
  16. package/dist/cache.d.ts.map +1 -0
  17. package/dist/cache.js +74 -0
  18. package/dist/cache.js.map +1 -0
  19. package/dist/codegen/codegen-error.d.ts +10 -0
  20. package/dist/codegen/codegen-error.d.ts.map +1 -0
  21. package/dist/codegen/codegen-error.js +14 -0
  22. package/dist/codegen/codegen-error.js.map +1 -0
  23. package/dist/codegen/contract-wrapper.d.ts +6 -0
  24. package/dist/codegen/contract-wrapper.d.ts.map +1 -0
  25. package/dist/codegen/contract-wrapper.js +2482 -0
  26. package/dist/codegen/contract-wrapper.js.map +1 -0
  27. package/dist/codegen/type-mapper.d.ts +46 -0
  28. package/dist/codegen/type-mapper.d.ts.map +1 -0
  29. package/dist/codegen/type-mapper.js +132 -0
  30. package/dist/codegen/type-mapper.js.map +1 -0
  31. package/dist/codegen/typescript-generator.d.ts +65 -0
  32. package/dist/codegen/typescript-generator.d.ts.map +1 -0
  33. package/dist/codegen/typescript-generator.js +2076 -0
  34. package/dist/codegen/typescript-generator.js.map +1 -0
  35. package/dist/compiler.d.ts +43 -0
  36. package/dist/compiler.d.ts.map +1 -0
  37. package/dist/compiler.js +532 -0
  38. package/dist/compiler.js.map +1 -0
  39. package/dist/dependency-resolver.d.ts +33 -0
  40. package/dist/dependency-resolver.d.ts.map +1 -0
  41. package/dist/dependency-resolver.js +142 -0
  42. package/dist/dependency-resolver.js.map +1 -0
  43. package/dist/import-parser.d.ts +17 -0
  44. package/dist/import-parser.d.ts.map +1 -0
  45. package/dist/import-parser.js +46 -0
  46. package/dist/import-parser.js.map +1 -0
  47. package/dist/index.d.ts +15 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +22 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/package-materializer.d.ts +29 -0
  52. package/dist/package-materializer.d.ts.map +1 -0
  53. package/dist/package-materializer.js +160 -0
  54. package/dist/package-materializer.js.map +1 -0
  55. package/dist/source-discovery.d.ts +24 -0
  56. package/dist/source-discovery.d.ts.map +1 -0
  57. package/dist/source-discovery.js +131 -0
  58. package/dist/source-discovery.js.map +1 -0
  59. package/dist/source-scrubber.d.ts +22 -0
  60. package/dist/source-scrubber.d.ts.map +1 -0
  61. package/dist/source-scrubber.js +71 -0
  62. package/dist/source-scrubber.js.map +1 -0
  63. package/dist/types.d.ts +72 -0
  64. package/dist/types.d.ts.map +1 -0
  65. package/dist/types.js +8 -0
  66. package/dist/types.js.map +1 -0
  67. package/package.json +34 -0
@@ -0,0 +1,2482 @@
1
+ /**
2
+ * Base contract wrapper class template.
3
+ * Generated wrappers extend this class.
4
+ */
5
+ export const CONTRACT_WRAPPER_TEMPLATE = String.raw `
6
+ import { normalizeProgramId } from "@lionden/config";
7
+ import type { LionDenRuntimeEnvironment, LogStyleRole } from "@lionden/core";
8
+ import { logDivider, logMetadata, pluralize, shouldRenderDivider, styleLogRole } from "@lionden/core";
9
+ import {
10
+ decryptRecordCiphertext,
11
+ decryptValueCiphertext,
12
+ deriveViewKey,
13
+ programAddressFromProgramId,
14
+ LocalVmExecutionError,
15
+ NetworkRecordDecryptionError,
16
+ NetworkValueDecryptionError,
17
+ } from "@lionden/network";
18
+
19
+ export type ExecutionMode = "local" | "onchain";
20
+
21
+ const LEO_BRAND: unique symbol = Symbol("LIONDEN_LEO_BRAND");
22
+
23
+ // Brands are compile-time guidance only; runtime values are the underlying Leo strings.
24
+ type LeoBrand<Name extends string> = string & { readonly [LEO_BRAND]: Name };
25
+
26
+ export type LeoAddress = LeoBrand<"Address">;
27
+ export type LeoField = LeoBrand<"Field">;
28
+ export type LeoGroup = LeoBrand<"Group">;
29
+ export type LeoScalar = LeoBrand<"Scalar">;
30
+ export type LeoIdentifier = LeoBrand<"Identifier">;
31
+ export type LeoDynamicRecord = LeoBrand<"DynamicRecord">;
32
+ export type LeoPlaintext = LeoBrand<"Plaintext">;
33
+
34
+ export type AddressInput = LeoAddress | { readonly address: string };
35
+ // field/scalar/group inputs accept the branded value or a bare non-negative
36
+ // integer (bigint | number), auto-suffixed during serialization. Branded values
37
+ // remain cross-type checked; bare numerics are interchangeable across these
38
+ // three slots (consistent with how integer inputs already work).
39
+ export type FieldInput = LeoField | bigint | number;
40
+ export type GroupInput = LeoGroup | bigint | number;
41
+ export type ScalarInput = LeoScalar | bigint | number;
42
+ export type IdentifierInput = LeoIdentifier;
43
+ export type DynamicRecordInput = LeoDynamicRecord;
44
+ export type PlaintextInput = LeoPlaintext;
45
+
46
+ // Widen a branded output type to its input counterpart, recursively. Used by
47
+ // generated cross-program (external) struct/record input aliases; local
48
+ // struct/record input shapes are emitted as explicit interfaces. Branded scalar
49
+ // strings map to their *Input alias (so bare bigint/number is accepted); arrays
50
+ // and nested structs/records widen element-wise; everything else is unchanged.
51
+ // Arm order matters: branded strings and primitives resolve before the generic
52
+ // object arm (arrays are objects too, so the array arm precedes it).
53
+ export type WidenInput<T> =
54
+ T extends LeoField ? FieldInput :
55
+ T extends LeoGroup ? GroupInput :
56
+ T extends LeoScalar ? ScalarInput :
57
+ T extends LeoAddress ? AddressInput :
58
+ T extends LeoIdentifier ? IdentifierInput :
59
+ T extends bigint | number | boolean ? T :
60
+ T extends readonly (infer E)[] ? ReadonlyArray<WidenInput<E>> :
61
+ T extends object ? { readonly [K in keyof T]: WidenInput<T[K]> } :
62
+ T;
63
+
64
+ export interface SignerInput {
65
+ readonly privateKey: string;
66
+ readonly address: string;
67
+ }
68
+
69
+ export interface TransitionInputContext {
70
+ readonly programId?: string;
71
+ readonly transition?: string;
72
+ readonly input?: string;
73
+ readonly path?: string;
74
+ }
75
+
76
+ export interface BaseCallOptions {
77
+ fee?: number;
78
+ privateFee?: boolean;
79
+ /**
80
+ * Generate real proofs during on-chain execution.
81
+ * When false (default), devnode connections use the fast-path builder
82
+ * which skips proof generation. When true, real proofs are generated
83
+ * (significantly slower). Has no effect in "local" mode or on
84
+ * non-devnode connections.
85
+ */
86
+ prove?: boolean;
87
+ /** Override the signer for this call. */
88
+ signer?: SignerInput;
89
+ /**
90
+ * Additional programs to load into the VM at execute time. Each entry
91
+ * is a Leo program id (bare or \`.aleo\`) or a path to a local \`.aleo\`
92
+ * file (relative paths anchor to project root). Merged with any
93
+ * instance-level imports (set via \`createX({ imports })\`) and the
94
+ * config-level \`execution.imports[programId]\`. Required for
95
+ * dynamic-dispatch targets that cannot be inferred from static
96
+ * \`import\` statements.
97
+ */
98
+ imports?: readonly string[];
99
+ }
100
+
101
+ /**
102
+ * Options accepted by every generated contract factory (\`createX({...})\`)
103
+ * and the underlying \`BaseContract\` constructor. Currently exposes a list
104
+ * of runtime imports that the wrapper carries on every call — useful for
105
+ * dispatch hubs that need the same set of dynamic targets on each call.
106
+ */
107
+ export interface BaseContractOptions {
108
+ /**
109
+ * Effective runtime/on-chain program id for this wrapper instance. Defaults
110
+ * to the generated source program id.
111
+ */
112
+ readonly programId?: string;
113
+ /**
114
+ * Runtime imports declared at instance creation time. Same accepted
115
+ * shapes as \`BaseCallOptions.imports\`: bare names, \`.aleo\` ids, or
116
+ * paths. Merged additively with per-call \`options.imports\` in
117
+ * \`executeRaw\`.
118
+ */
119
+ readonly imports?: readonly string[];
120
+ }
121
+
122
+ const LOG_ARG_MAX_LENGTH = 120;
123
+
124
+ type TransitionLogRole = Extract<LogStyleRole, "action" | "success" | "warning">;
125
+
126
+ export interface LocalExecutionOptions extends Omit<BaseCallOptions, "privateFee"> {}
127
+
128
+ export interface OnChainExecutionOptions extends BaseCallOptions {
129
+ /** Confirmation timeout used by settled/accepted/rejected helpers. */
130
+ confirmTimeout?: number;
131
+ }
132
+
133
+ export interface TransitionExecutionResult {
134
+ /** Raw outputs from the transition as Leo-encoded strings. */
135
+ readonly outputs: string[];
136
+ /** Transaction ID. Only set for on-chain execution. */
137
+ readonly txId?: string;
138
+ }
139
+
140
+ export interface SubmittedTransition {
141
+ readonly txId: string;
142
+ }
143
+
144
+ export interface IdOnlyRawOutput {
145
+ readonly kind: "idOnly";
146
+ readonly type: string;
147
+ readonly id: string;
148
+ }
149
+
150
+ export type RawTransitionOutput = string | IdOnlyRawOutput;
151
+
152
+ /**
153
+ * Per-transition record in a confirmed transaction's callgraph. Mirrors the
154
+ * network-layer ConfirmedTransitionRecord with the same field shape — kept in
155
+ * sync with packages/network/src/types.ts:39-62. The template stays self-
156
+ * contained (no @lionden/network type imports), so this is a parallel
157
+ * declaration that the codegen pipeline asserts is structurally compatible.
158
+ */
159
+ export interface ConfirmedTransitionRecord {
160
+ readonly programId: string;
161
+ readonly transitionName: string;
162
+ readonly rawOutputs: readonly RawTransitionOutput[];
163
+ readonly transitionPublicKey: string;
164
+ }
165
+
166
+ /**
167
+ * Settled transition with status pinned to "accepted" but without typed
168
+ * outputs. Used by \`expectAccepted\` and as the structural base for
169
+ * AcceptedTransition<TOutputs>.
170
+ *
171
+ * \`rawOutputs\` are the outputs of the SPECIFIC transition the caller
172
+ * invoked, filtered from the confirmed transaction's transitions[] by
173
+ * transition identity. Record outputs are ciphertexts (\`record1...\`) — pass
174
+ * them to the per-record \`decryptXxx(ciphertext, key)\` helpers to recover
175
+ * typed records. Private plaintext outputs are value ciphertexts
176
+ * (\`ciphertext1...\`) — pass them to \`EncryptedValue<T>.decrypt(key)\`.
177
+ *
178
+ * Indexed by the ORIGINAL ABI output position, including Future entries.
179
+ * The typed \`outputs\` projection on AcceptedTransition<T> drops Futures
180
+ * from its result shape but still indexes back into the original ABI
181
+ * position.
182
+ *
183
+ * Exactly one matching transition is required (0 or >1 throws
184
+ * TransactionShapeError).
185
+ */
186
+ export interface AcceptedTransitionBase extends SubmittedTransition {
187
+ readonly blockHeight: number;
188
+ readonly status: "accepted";
189
+ readonly rawOutputs: readonly RawTransitionOutput[];
190
+ /**
191
+ * Transition public key (\`tpk\`) from the on-chain confirmed transition.
192
+ * Required input to value-ciphertext decryption (\`EncryptedValue<T>.decrypt\`).
193
+ */
194
+ readonly transitionPublicKey: string;
195
+ /**
196
+ * Full callgraph snapshot of the confirmed transaction. Each entry is one
197
+ * transition in the call chain, in execution order, including callee
198
+ * transitions from cross-program dispatch.
199
+ *
200
+ * Used by \`IdOnlyExternalRecordHandle.match(matcher).decrypt(...)\` to
201
+ * select the callee transition that actually emitted the record
202
+ * ciphertext. Also useful for raw inspection — e.g. correlating
203
+ * dispatched-call commitments back to their producing transitions.
204
+ */
205
+ readonly transitions: readonly ConfirmedTransitionRecord[];
206
+ }
207
+
208
+ /**
209
+ * Accepted on-chain settlement carrying typed outputs in shape TOutputs.
210
+ *
211
+ * \`outputs\` carries only client-decodable transition outputs. Future-typed
212
+ * outputs appear in \`rawOutputs\` at their original ABI index but are not
213
+ * represented in the typed projection (no client-side decoding exists).
214
+ * Record outputs become EncryptedRecord<RecordName> handles; private
215
+ * plaintext outputs become EncryptedValue<T> handles; public plaintext
216
+ * outputs are decoded eagerly.
217
+ */
218
+ export interface AcceptedTransition<TOutputs> extends AcceptedTransitionBase {
219
+ readonly outputs: TOutputs;
220
+ }
221
+
222
+ /**
223
+ * Rejected on-chain settlement. No \`outputs\` field: Aleo converts rejected
224
+ * executes to fee-only on inclusion, so there's no typed-output projection
225
+ * meaningful for a rejection. Inspect \`rawOutputs\` if a matching transition
226
+ * happens to be present. No \`transitionPublicKey\` either — rejected execs
227
+ * usually carry no matching transition, so tpk is not meaningful.
228
+ */
229
+ export interface RejectedTransition extends SubmittedTransition {
230
+ readonly blockHeight: number;
231
+ readonly status: "rejected";
232
+ readonly rawOutputs: readonly RawTransitionOutput[];
233
+ }
234
+
235
+ /**
236
+ * Discriminated union over settled transitions. Narrow on \`status === "accepted"\`
237
+ * to reach \`transitionPublicKey\` and the rest of the AcceptedTransitionBase
238
+ * fields; both arms share \`{ txId, blockHeight, status, rawOutputs }\`.
239
+ */
240
+ export type SettledTransition = AcceptedTransitionBase | RejectedTransition;
241
+
242
+ /**
243
+ * Typed handle for an on-chain record output. Wraps the ciphertext so the
244
+ * caller can defer decryption to whichever account holds the view key.
245
+ *
246
+ * Carries \`program\` and \`recordName\` so \`.match(matcher)\` can verify the
247
+ * matcher's identity against the ciphertext's actual type at decrypt time —
248
+ * this blocks accidentally deserializing a GoldToken ciphertext as a
249
+ * SilverToken record.
250
+ */
251
+ export interface EncryptedRecord<T> {
252
+ readonly program: string;
253
+ readonly recordName: string;
254
+ readonly ciphertext: string;
255
+ decrypt(key: DecryptionKey): Promise<T>;
256
+ /**
257
+ * Capture the matcher and defer all validation + decryption to
258
+ * \`CapturedRecord.decrypt(key)\`. The matcher's \`source\` is ignored on this
259
+ * arm (the ciphertext lives on the handle itself); the matcher's
260
+ * \`program\` / \`recordName\` MUST equal this handle's fields or
261
+ * \`CapturedRecord.decrypt\` async-throws \`TransactionShapeError\`.
262
+ */
263
+ match<TOut = T>(
264
+ matcher: RecordOutputMatcher<TOut, "unbound"> | RecordOutputMatcher<TOut, "bound">,
265
+ ): CapturedRecord<TOut>;
266
+ }
267
+
268
+ /**
269
+ * Fields shared by both id-only record handle variants. The chain exposes
270
+ * \`record_dynamic\` and \`external_record\` outputs without a ciphertext on
271
+ * the surfacing transition; this base captures the inspection-only fields.
272
+ *
273
+ * \`id\` is an IDENTIFIER, not a dereferenceable pointer — in nested call
274
+ * graphs the same id can appear in multiple places and the typechain does
275
+ * NOT auto-resolve it.
276
+ *
277
+ * \`transitions\` is the full callgraph snapshot from the confirmed
278
+ * transaction. Used by \`.match(matcher.from(...)|matcher.at(...))\` to select
279
+ * the source transition that holds the ciphertext.
280
+ */
281
+ export interface IdOnlyRecordHandleBase {
282
+ readonly id: string;
283
+ readonly transitions: readonly ConfirmedTransitionRecord[];
284
+ }
285
+
286
+ /**
287
+ * Output-side matcher: identity (program + recordName + deserializer) plus
288
+ * a phantom "bound" / "unbound" flag tracking whether a transition source
289
+ * has been chosen via \`.from(...)\` or \`.at(...)\`. Id-only arms only accept
290
+ * \`"bound"\` matchers — passing an unbound matcher is a compile error, not
291
+ * a runtime throw.
292
+ *
293
+ * Construct via the typed helper's \`output\` field (e.g. \`asGoldToken.output\`)
294
+ * or via the public \`createRecordOutputMatcher\` factory for unresolved
295
+ * external records (where no ABI-backed helper is generated).
296
+ */
297
+ export interface RecordOutputMatcher<T, S extends "unbound" | "bound" = "unbound"> {
298
+ readonly program: string;
299
+ readonly recordName: string;
300
+ readonly deserialize: (plaintext: string) => T;
301
+ readonly source: S extends "bound" ? IdOnlyRecordSource : undefined;
302
+ /**
303
+ * Name-based source binding. The matcher's \`program\` is inherited as the
304
+ * source \`programId\`, so the caller cannot accidentally point at a
305
+ * different program. \`opts.match\` disambiguates when more than one
306
+ * matching transition exists (0-based, within matches).
307
+ */
308
+ from(
309
+ transitionName: string,
310
+ outputIndex: number,
311
+ opts?: { readonly match?: number },
312
+ ): RecordOutputMatcher<T, "bound">;
313
+ /**
314
+ * Positional source binding. Indexes directly into the callgraph's
315
+ * \`transitions[transitionIndex].rawOutputs[outputIndex]\`. Use this when
316
+ * a name-based binding is too coarse — e.g. multiple matches at the same
317
+ * \`(program, transitionName)\` that \`.from(..., { match: n })\` could
318
+ * handle but you'd rather index directly — or when authoring an
319
+ * intentional cross-program mismatch test. Successful decryption still
320
+ * requires \`selected.transition.programId === matcher.program\`;
321
+ * any mismatch surfaces as \`program-mismatch\` from \`.decrypt(key)\`.
322
+ */
323
+ at(transitionIndex: number, outputIndex: number): RecordOutputMatcher<T, "bound">;
324
+ }
325
+
326
+ export type DynamicRecordHelper<TIn, TOut> = ((value: TIn) => LeoDynamicRecord) & {
327
+ readonly output: RecordOutputMatcher<TOut, "unbound">;
328
+ forProgram(programId: string): DynamicRecordHelper<TIn, TOut>;
329
+ };
330
+
331
+ /**
332
+ * Result of \`.match(matcher)\`. All validation, source resolution, and
333
+ * decryption is deferred to \`.decrypt(key)\`. Calling \`.match\` itself is a
334
+ * pure builder and never throws.
335
+ */
336
+ export interface CapturedRecord<T> {
337
+ decrypt(key: DecryptionKey): Promise<T>;
338
+ }
339
+
340
+ /**
341
+ * Handle for a \`dyn record\` output. The chain never exposes a ciphertext
342
+ * for the dynamic-record id itself — not on the producing transition, not
343
+ * on the caller. \`.match(matcher.from(...)|.at(...)).decrypt(key)\` therefore
344
+ * does NOT dereference the \`record_dynamic\` id; it selects an explicit
345
+ * sibling concrete output in the same callgraph (typically the materialized
346
+ * static record that a V15-compliant callee emitted alongside the dynamic
347
+ * handle, per snarkVM's V15 record-existence rule) and decrypts that
348
+ * ciphertext via the matcher's deserializer. See \`docs/network.md\` §
349
+ * Id-only record outputs for the recovery flow.
350
+ */
351
+ export interface IdOnlyDynamicRecordHandle extends IdOnlyRecordHandleBase {
352
+ readonly kind: "idOnlyDynamicRecord";
353
+ readonly type: "record_dynamic";
354
+ match<TOut>(matcher: RecordOutputMatcher<TOut, "bound">): CapturedRecord<TOut>;
355
+ }
356
+
357
+ /**
358
+ * Selector for picking the source transition + output that holds the
359
+ * ciphertext referenced by an id-only record handle. Produced by
360
+ * \`RecordOutputMatcher.from(...)\` (named form) or \`.at(...)\` (positional
361
+ * form); user code does not construct these directly.
362
+ *
363
+ * Two forms:
364
+ * - Positional: \`{ transitionIndex, outputIndex }\` — direct index into
365
+ * \`transitions[i].rawOutputs[j]\`.
366
+ * - Named: \`{ programId, transitionName, outputIndex, transitionMatchIndex? }\`
367
+ * — match by program+transition name. \`transitionMatchIndex\` is required
368
+ * when more than one transition matches (otherwise \`transition-not-unique\`
369
+ * is thrown).
370
+ */
371
+ export type IdOnlyRecordSource =
372
+ | {
373
+ readonly transitionIndex: number;
374
+ readonly outputIndex: number;
375
+ }
376
+ | {
377
+ readonly programId: string;
378
+ readonly transitionName: string;
379
+ readonly outputIndex: number;
380
+ readonly transitionMatchIndex?: number;
381
+ };
382
+
383
+ /**
384
+ * Handle for an external \`Record\` output where the ciphertext lives on the
385
+ * callee transition (the imported program's transition that actually emitted
386
+ * the record). \`.match(matcher.from(...)|.at(...)).decrypt(key)\` selects the
387
+ * callee transition+output and deserializes via the matcher.
388
+ *
389
+ * The \`T\` type parameter is the resolved external record type when the
390
+ * imported program's ABI is available at codegen time, or
391
+ * \`LeoDynamicRecord\` as fallback (caller constructs their own matcher via
392
+ * \`createRecordOutputMatcher\`).
393
+ */
394
+ export interface IdOnlyExternalRecordHandle<T> extends IdOnlyRecordHandleBase {
395
+ readonly kind: "idOnlyExternalRecord";
396
+ readonly type: "external_record";
397
+ match<TOut = T>(matcher: RecordOutputMatcher<TOut, "bound">): CapturedRecord<TOut>;
398
+ }
399
+
400
+ /**
401
+ * Construct a \`RecordOutputMatcher\` for a record shape. Codegen calls this
402
+ * for every typed helper (\`asGoldToken.output\`, \`GoldToken_Token.output\`,
403
+ * etc.); user code calls it directly when working with an unresolved
404
+ * external-record output — i.e. an \`IdOnlyExternalRecordHandle<LeoDynamicRecord>\`
405
+ * whose record type has no ABI-backed typed helper.
406
+ *
407
+ * Returns an "unbound" matcher; chain \`.from(transition, index)\` or
408
+ * \`.at(transitionIndex, outputIndex)\` before passing to an id-only handle's
409
+ * \`.match\`. The encrypted-record arm accepts unbound or bound matchers.
410
+ */
411
+ export function createRecordOutputMatcher<T>(base: {
412
+ readonly program: string;
413
+ readonly recordName: string;
414
+ readonly deserialize: (plaintext: string) => T;
415
+ }): RecordOutputMatcher<T, "unbound"> {
416
+ return buildRecordOutputMatcher(base, undefined) as RecordOutputMatcher<T, "unbound">;
417
+ }
418
+
419
+ export function bindDynamicRecordHelperProgram<TIn, TOut>(
420
+ fn: (value: TIn) => LeoDynamicRecord,
421
+ matcher: RecordOutputMatcher<TOut, "unbound">,
422
+ programId: string,
423
+ ): DynamicRecordHelper<TIn, TOut> {
424
+ const output = BaseContract.bindRecordOutputMatcherProgram(matcher, programId);
425
+ const helper = Object.assign(((value: TIn) => fn(value)), {
426
+ output,
427
+ forProgram(nextProgramId: string): DynamicRecordHelper<TIn, TOut> {
428
+ return bindDynamicRecordHelperProgram(fn, helper.output, nextProgramId);
429
+ },
430
+ });
431
+ return helper;
432
+ }
433
+
434
+ function buildRecordOutputMatcher<T>(
435
+ base: {
436
+ readonly program: string;
437
+ readonly recordName: string;
438
+ readonly deserialize: (plaintext: string) => T;
439
+ },
440
+ source: IdOnlyRecordSource | undefined,
441
+ ): RecordOutputMatcher<T, "unbound"> | RecordOutputMatcher<T, "bound"> {
442
+ const matcher = {
443
+ program: base.program,
444
+ recordName: base.recordName,
445
+ deserialize: base.deserialize,
446
+ source: source as IdOnlyRecordSource,
447
+ from(
448
+ transitionName: string,
449
+ outputIndex: number,
450
+ opts?: { readonly match?: number },
451
+ ): RecordOutputMatcher<T, "bound"> {
452
+ return buildRecordOutputMatcher(base, {
453
+ programId: base.program,
454
+ transitionName,
455
+ outputIndex,
456
+ transitionMatchIndex: opts?.match,
457
+ }) as RecordOutputMatcher<T, "bound">;
458
+ },
459
+ at(transitionIndex: number, outputIndex: number): RecordOutputMatcher<T, "bound"> {
460
+ return buildRecordOutputMatcher(base, { transitionIndex, outputIndex }) as RecordOutputMatcher<T, "bound">;
461
+ },
462
+ };
463
+ return matcher as RecordOutputMatcher<T, "unbound"> | RecordOutputMatcher<T, "bound">;
464
+ }
465
+
466
+ function rebindMatcherSource(
467
+ source: IdOnlyRecordSource | undefined,
468
+ fromProgramId: string,
469
+ toProgramId: string,
470
+ ): IdOnlyRecordSource | undefined {
471
+ if (source === undefined || !("programId" in source) || source.programId !== fromProgramId) {
472
+ return source;
473
+ }
474
+ return { ...source, programId: toProgramId };
475
+ }
476
+
477
+ /**
478
+ * Typed handle for an on-chain private plaintext output (Aleo value
479
+ * ciphertext, \`ciphertext1...\`). Wraps the ciphertext so the caller can
480
+ * defer decryption to whichever account holds the view key.
481
+ */
482
+ export interface EncryptedValue<T> {
483
+ readonly ciphertext: string;
484
+ decrypt(key: DecryptionKey): Promise<T>;
485
+ }
486
+
487
+ /**
488
+ * Accepts a raw key string (auto-detected by \`APrivateKey1...\` /
489
+ * \`AViewKey1...\` prefix), an object with \`viewKey\`, or an object with
490
+ * \`privateKey\` (lionden \`SignerInput\` and similar structures match the
491
+ * \`privateKey\` arm). Unrecognized strings throw \`RecordDecryptionKeyError\`
492
+ * rather than guessing.
493
+ *
494
+ * Same shape applies to both record and value decryption — the
495
+ * \`RecordDecryptionKey\` name is retained for backwards compatibility;
496
+ * new code may use the neutral alias \`DecryptionKey\`.
497
+ */
498
+ export type RecordDecryptionKey =
499
+ | string
500
+ | { readonly viewKey: string }
501
+ | { readonly privateKey: string };
502
+
503
+ /** Neutral alias — same shape as RecordDecryptionKey. */
504
+ export type DecryptionKey = RecordDecryptionKey;
505
+
506
+ // Primitive types lionden has serializers/parsers for. "signature" is
507
+ // intentionally excluded — no serializeSignature exists yet.
508
+ export type LeoPrimitiveType =
509
+ | "address" | "boolean" | "field" | "group" | "scalar"
510
+ | "u8" | "u16" | "u32" | "u64" | "u128"
511
+ | "i8" | "i16" | "i32" | "i64" | "i128";
512
+
513
+ export type LeoVisibility = "public" | "private";
514
+
515
+ export type LeoFieldSchemaEntry = __LEO_FIELD_SCHEMA_ENTRY__;
516
+
517
+ export type DynamicRecordSchema<T> = {
518
+ readonly [K in keyof T]: LeoFieldSchemaEntry;
519
+ };
520
+
521
+ export type IdOnlyRecordResolutionReason =
522
+ | "transition-not-found"
523
+ | "transition-not-unique"
524
+ | "transition-index-out-of-range"
525
+ | "transition-match-index-out-of-range"
526
+ | "program-mismatch"
527
+ | "not-a-ciphertext";
528
+
529
+ export type TypechainErrorKind =
530
+ | "TransitionInputError"
531
+ | "LocalTransitionError"
532
+ | "UnexpectedLocalSuccessError"
533
+ | "TransitionSubmissionError"
534
+ | "TransactionConfirmationTimeoutError"
535
+ | "OnChainRejectedError"
536
+ | "UnexpectedTransactionStatusError"
537
+ | "TransactionShapeError"
538
+ | "RecordDecryptionKeyError"
539
+ | "LocalRecordDecryptionError"
540
+ | "LocalValueDecryptionError"
541
+ | "IdOnlyRecordResolutionError"
542
+ | "MappingKeyNotFoundError"
543
+ | "StorageValueNotFoundError";
544
+
545
+ export type TypechainErrorPhase =
546
+ | "input"
547
+ | "local"
548
+ | "submit"
549
+ | "confirm"
550
+ | "settled"
551
+ | "shape"
552
+ | "mapping"
553
+ | "storage";
554
+
555
+ export interface TypechainErrorContext {
556
+ readonly phase: TypechainErrorPhase;
557
+ readonly programId?: string;
558
+ readonly transition?: string;
559
+ readonly input?: string;
560
+ readonly outputIndex?: number;
561
+ readonly mapping?: string;
562
+ readonly storage?: string;
563
+ readonly key?: string;
564
+ readonly cause?: unknown;
565
+ }
566
+
567
+ export class LionDenTypechainError extends Error {
568
+ readonly kind: TypechainErrorKind;
569
+ readonly phase: TypechainErrorPhase;
570
+ readonly programId?: string;
571
+ readonly transition?: string;
572
+ readonly input?: string;
573
+ readonly outputIndex?: number;
574
+ readonly mapping?: string;
575
+ readonly storage?: string;
576
+ readonly key?: string;
577
+
578
+ constructor(kind: TypechainErrorKind, message: string, context: TypechainErrorContext) {
579
+ super(message, context.cause === undefined ? undefined : { cause: context.cause });
580
+ this.name = kind;
581
+ this.kind = kind;
582
+ this.phase = context.phase;
583
+ this.programId = context.programId;
584
+ this.transition = context.transition;
585
+ this.input = context.input;
586
+ this.outputIndex = context.outputIndex;
587
+ this.mapping = context.mapping;
588
+ this.storage = context.storage;
589
+ this.key = context.key;
590
+ }
591
+ }
592
+
593
+ export class TransitionInputError extends LionDenTypechainError {
594
+ constructor(message: string, context: Omit<TypechainErrorContext, "phase"> = {}) {
595
+ super("TransitionInputError", message, { ...context, phase: "input" });
596
+ }
597
+ }
598
+
599
+ export class LocalTransitionError extends LionDenTypechainError {
600
+ constructor(message: string, context: Omit<TypechainErrorContext, "phase"> = {}) {
601
+ super("LocalTransitionError", message, { ...context, phase: "local" });
602
+ }
603
+ }
604
+
605
+ export class UnexpectedLocalSuccessError extends LionDenTypechainError {
606
+ constructor(message: string, context: Omit<TypechainErrorContext, "phase"> = {}) {
607
+ super("UnexpectedLocalSuccessError", message, { ...context, phase: "local" });
608
+ }
609
+ }
610
+
611
+ export class TransitionSubmissionError extends LionDenTypechainError {
612
+ constructor(message: string, context: Omit<TypechainErrorContext, "phase"> = {}) {
613
+ super("TransitionSubmissionError", message, { ...context, phase: "submit" });
614
+ }
615
+ }
616
+
617
+ export class TransactionConfirmationTimeoutError extends LionDenTypechainError {
618
+ constructor(message: string, context: Omit<TypechainErrorContext, "phase"> = {}) {
619
+ super("TransactionConfirmationTimeoutError", message, { ...context, phase: "confirm" });
620
+ }
621
+ }
622
+
623
+ export class OnChainRejectedError extends LionDenTypechainError {
624
+ constructor(message: string, context: Omit<TypechainErrorContext, "phase"> = {}) {
625
+ super("OnChainRejectedError", message, { ...context, phase: "settled" });
626
+ }
627
+ }
628
+
629
+ export class UnexpectedTransactionStatusError extends LionDenTypechainError {
630
+ constructor(message: string, context: Omit<TypechainErrorContext, "phase"> = {}) {
631
+ super("UnexpectedTransactionStatusError", message, { ...context, phase: "settled" });
632
+ }
633
+ }
634
+
635
+ export class TransactionShapeError extends LionDenTypechainError {
636
+ constructor(message: string, context: Omit<TypechainErrorContext, "phase"> = {}) {
637
+ super("TransactionShapeError", message, { ...context, phase: "shape" });
638
+ }
639
+ }
640
+
641
+ export class MappingKeyNotFoundError extends LionDenTypechainError {
642
+ constructor(message: string, context: Omit<TypechainErrorContext, "phase"> = {}) {
643
+ super("MappingKeyNotFoundError", message, { ...context, phase: "mapping" });
644
+ }
645
+ }
646
+
647
+ export class StorageValueNotFoundError extends LionDenTypechainError {
648
+ constructor(message: string, context: Omit<TypechainErrorContext, "phase"> = {}) {
649
+ super("StorageValueNotFoundError", message, { ...context, phase: "storage" });
650
+ }
651
+ }
652
+
653
+ export class RecordDecryptionKeyError extends LionDenTypechainError {
654
+ constructor(message: string, context: Omit<TypechainErrorContext, "phase"> = {}) {
655
+ super("RecordDecryptionKeyError", message, { ...context, phase: "input" });
656
+ }
657
+ }
658
+
659
+ export class LocalRecordDecryptionError extends LionDenTypechainError {
660
+ constructor(message: string, context: Omit<TypechainErrorContext, "phase"> = {}) {
661
+ super("LocalRecordDecryptionError", message, { ...context, phase: "local" });
662
+ }
663
+ }
664
+
665
+ export class LocalValueDecryptionError extends LionDenTypechainError {
666
+ constructor(message: string, context: Omit<TypechainErrorContext, "phase"> = {}) {
667
+ super("LocalValueDecryptionError", message, { ...context, phase: "local" });
668
+ }
669
+ }
670
+
671
+ /**
672
+ * Thrown by an id-only handle's \`.match(matcher).decrypt(key)\` when the
673
+ * matcher's source fails to resolve to a decryptable ciphertext. The
674
+ * \`reason\` field discriminates each failure mode so callers can narrow at
675
+ * the call site without parsing the message.
676
+ *
677
+ * - \`transition-not-found\`: \`.from(name, idx)\` — no matching (program, transitionName).
678
+ * - \`transition-not-unique\`: \`.from(name, idx)\` with no \`{ match: n }\` but >1 match.
679
+ * - \`transition-index-out-of-range\`: \`.at(transitionIndex, idx)\` — index outside \`transitions\`.
680
+ * - \`transition-match-index-out-of-range\`: \`.from(..., { match })\` — \`match\` outside the match set.
681
+ * - \`program-mismatch\`: selected transition's \`programId\` ≠ \`matcher.program\`.
682
+ * - \`not-a-ciphertext\`: selected output slot exists but is not a record ciphertext string.
683
+ */
684
+ export class IdOnlyRecordResolutionError extends LionDenTypechainError {
685
+ readonly reason: IdOnlyRecordResolutionReason;
686
+ readonly expectedProgram?: string;
687
+ readonly actualProgram?: string;
688
+
689
+ constructor(
690
+ reason: IdOnlyRecordResolutionReason,
691
+ message: string,
692
+ context: Omit<TypechainErrorContext, "phase"> & {
693
+ readonly expectedProgram?: string;
694
+ readonly actualProgram?: string;
695
+ } = {},
696
+ ) {
697
+ super("IdOnlyRecordResolutionError", message, { ...context, phase: "shape" });
698
+ this.reason = reason;
699
+ this.expectedProgram = context.expectedProgram;
700
+ this.actualProgram = context.actualProgram;
701
+ }
702
+ }
703
+
704
+ /**
705
+ * Symbol-keyed cache for the original record literal a deserializer parsed.
706
+ * Generated record serializers use this to round-trip records losslessly.
707
+ */
708
+ export const RECORD_RAW: unique symbol = Symbol("LIONDEN_RECORD_RAW");
709
+
710
+ function stripVisibility(value: string): string {
711
+ return value.trim().replace(/\.(?:public|private)$/i, "");
712
+ }
713
+
714
+ function describeInput(context?: TransitionInputContext): string {
715
+ const location = context?.programId && context.transition
716
+ ? context.programId + "/" + context.transition
717
+ : context?.programId ?? "transition";
718
+ if (context?.input && context.path) {
719
+ return location + " input " + JSON.stringify(context.input) + "." + context.path;
720
+ }
721
+ if (context?.input) {
722
+ return location + " input " + JSON.stringify(context.input);
723
+ }
724
+ if (context?.path) {
725
+ return location + " input ." + context.path;
726
+ }
727
+ return location + " input";
728
+ }
729
+
730
+ function childPath(parent: string | undefined, segment: string): string {
731
+ return parent ? parent + "." + segment : segment;
732
+ }
733
+
734
+ function summarizeLogArg(value: string): string {
735
+ const singleLine = value.replace(/\s+/g, " ").trim();
736
+ if (singleLine.length <= LOG_ARG_MAX_LENGTH) return singleLine;
737
+ return singleLine.slice(0, LOG_ARG_MAX_LENGTH - 3) + "...";
738
+ }
739
+
740
+ function formatLogArgs(args: readonly string[]): string {
741
+ try {
742
+ return args.map((arg) => summarizeLogArg(arg)).join(", ");
743
+ } catch {
744
+ return "...args";
745
+ }
746
+ }
747
+
748
+ function transitionLogKindRole(kind: string): TransitionLogRole {
749
+ if (kind === "Executed" || kind === "Accepted") return "success";
750
+ if (kind === "Submitted") return "action";
751
+ if (kind === "Rejected") return "warning";
752
+ if (kind === "Observed expected local failure for") return "warning";
753
+ return "action";
754
+ }
755
+
756
+ function createInputError(
757
+ expected: string,
758
+ received: unknown,
759
+ context?: TransitionInputContext,
760
+ hint?: string,
761
+ ): TransitionInputError {
762
+ const rendered = typeof received === "string"
763
+ ? "string " + JSON.stringify(received)
764
+ : received === null
765
+ ? "null"
766
+ : Array.isArray(received)
767
+ ? "array"
768
+ : typeof received;
769
+ const suffix = hint ? " " + hint : "";
770
+ return new TransitionInputError(
771
+ describeInput(context) + " expected " + expected + ". Received " + rendered + "." + suffix,
772
+ {
773
+ programId: context?.programId,
774
+ transition: context?.transition,
775
+ input: context?.input,
776
+ },
777
+ );
778
+ }
779
+
780
+ function expectString(value: unknown, expected: string, context?: TransitionInputContext, hint?: string): string {
781
+ if (typeof value !== "string") {
782
+ throw createInputError(expected, value, context, hint);
783
+ }
784
+ return value.trim();
785
+ }
786
+
787
+ function brand<Name extends string>(value: string): LeoBrand<Name> {
788
+ return value as LeoBrand<Name>;
789
+ }
790
+
791
+ export const Leo = {
792
+ address(value: string | { readonly address: string }): LeoAddress {
793
+ return brand<"Address">(BaseContract.serializeAddress(value, undefined));
794
+ },
795
+
796
+ field(value: bigint | number | string): LeoField {
797
+ return brand<"Field">(BaseContract.serializeField(value, undefined));
798
+ },
799
+
800
+ group(value: bigint | number | string): LeoGroup {
801
+ return brand<"Group">(BaseContract.serializeGroup(value, undefined));
802
+ },
803
+
804
+ scalar(value: bigint | number | string): LeoScalar {
805
+ return brand<"Scalar">(BaseContract.serializeScalar(value, undefined));
806
+ },
807
+
808
+ identifier(value: string): LeoIdentifier {
809
+ return brand<"Identifier">(BaseContract.parseIdentifier(BaseContract.serializeIdentifier(value, undefined)));
810
+ },
811
+
812
+ /**
813
+ * Build a typed Leo \`dyn record\` literal from a JS object and a
814
+ * per-field type+visibility schema. Schema entries are validated at
815
+ * compile time via the \`\${LeoPrimitiveType}.\${LeoVisibility}\` template
816
+ * union; values are validated and range-checked at runtime.
817
+ *
818
+ * Example:
819
+ * const token = Leo.dynamicRecord({
820
+ * owner: Leo.address(addr),
821
+ * amount: 100n,
822
+ * _nonce: Leo.group("0group"),
823
+ * _version: 0,
824
+ * }, {
825
+ * owner: "address.private",
826
+ * amount: "u128.private",
827
+ * _nonce: "group.public",
828
+ * _version: "u8.public",
829
+ * });
830
+ */
831
+ dynamicRecord<T extends object>(value: T, schema: DynamicRecordSchema<T>): LeoDynamicRecord {
832
+ return brand<"DynamicRecord">(BaseContract.encodeDynamicRecord(
833
+ value as unknown as Record<string, unknown>,
834
+ schema as unknown as Record<string, LeoFieldSchemaEntry>,
835
+ ));
836
+ },
837
+
838
+ unsafe: {
839
+ dynamicRecord(value: string): LeoDynamicRecord {
840
+ const literal = expectString(value, "DynamicRecord literal");
841
+ if (literal.length === 0) {
842
+ throw createInputError("DynamicRecord literal", value);
843
+ }
844
+ return brand<"DynamicRecord">(literal);
845
+ },
846
+
847
+ plaintext(value: string): LeoPlaintext {
848
+ const literal = expectString(value, "Leo plaintext literal");
849
+ if (literal.length === 0) {
850
+ throw createInputError("Leo plaintext literal", value);
851
+ }
852
+ return brand<"Plaintext">(literal);
853
+ },
854
+ },
855
+ } as const;
856
+
857
+ export abstract class BaseContract {
858
+ static readonly RECORD_RAW: typeof RECORD_RAW = RECORD_RAW;
859
+
860
+ readonly sourceProgramId: string;
861
+ readonly programId: string;
862
+ protected readonly instanceImports: readonly string[];
863
+ protected lre: LionDenRuntimeEnvironment | null = null;
864
+ protected signer?: SignerInput;
865
+
866
+ constructor(sourceProgramId: string, options?: BaseContractOptions) {
867
+ this.sourceProgramId = normalizeProgramId(sourceProgramId);
868
+ this.programId = normalizeProgramId(options?.programId ?? sourceProgramId);
869
+ this.instanceImports = options?.imports ?? [];
870
+ }
871
+
872
+ /** Connect this contract wrapper to an LRE instance. */
873
+ connect(lre: LionDenRuntimeEnvironment): this {
874
+ this.lre = lre;
875
+ return this;
876
+ }
877
+
878
+ /** Deterministic Aleo address for this program id. */
879
+ address(): LeoAddress {
880
+ return programAddressFromProgramId(this.programId) as LeoAddress;
881
+ }
882
+
883
+ /**
884
+ * Return a new contract instance bound to a specific signer.
885
+ * The returned instance shares the same LRE connection and any
886
+ * instance-level runtime imports, but all transitions will execute
887
+ * as the given signer.
888
+ */
889
+ withSigner(signer: SignerInput): this {
890
+ const ContractClass = this.constructor as new (options?: BaseContractOptions) => this;
891
+ const instance = new ContractClass({
892
+ programId: this.programId,
893
+ imports: this.instanceImports,
894
+ });
895
+ instance.lre = this.lre;
896
+ instance.signer = signer;
897
+ return instance;
898
+ }
899
+
900
+ static childInputContext(
901
+ context: TransitionInputContext | undefined,
902
+ segment: string,
903
+ ): TransitionInputContext | undefined {
904
+ if (!context) return undefined;
905
+ return { ...context, path: childPath(context.path, segment) };
906
+ }
907
+
908
+ protected inputContext(transition: string, input: string): TransitionInputContext {
909
+ return { programId: this.programId, transition, input };
910
+ }
911
+
912
+ protected getLre(): LionDenRuntimeEnvironment {
913
+ if (!this.lre) {
914
+ throw new TransactionShapeError(
915
+ "Contract " + this.programId + " is not connected to an LRE. Call .connect(lre) before executing transitions.",
916
+ { programId: this.programId },
917
+ );
918
+ }
919
+ return this.lre;
920
+ }
921
+
922
+ protected getNetwork(): any {
923
+ const lre = this.getLre();
924
+ const network = (lre as any).network;
925
+ if (!network || typeof network.execute !== "function") {
926
+ throw new TransactionShapeError(
927
+ "Network is not available for " + this.programId + ". Ensure @lionden/plugin-network is loaded and connected before executing transitions.",
928
+ { programId: this.programId },
929
+ );
930
+ }
931
+ return network;
932
+ }
933
+
934
+ /**
935
+ * Execute a transition locally and return raw Leo outputs.
936
+ * Generated transition helpers deserialize this path into JS values.
937
+ */
938
+ protected async executeLocal(
939
+ transitionName: string,
940
+ args: string[],
941
+ options: LocalExecutionOptions = {},
942
+ ): Promise<TransitionExecutionResult> {
943
+ this.beginTransitionLogBlock();
944
+ this.logTransitionStart("Executing", transitionName, args, {
945
+ ...options,
946
+ mode: "local",
947
+ });
948
+ try {
949
+ const result = await this.executeRaw(transitionName, args, {
950
+ ...options,
951
+ mode: "local",
952
+ });
953
+ this.logTransitionDone(
954
+ "Executed",
955
+ transitionName,
956
+ "(" + result.outputs.length + " " + pluralize("output", result.outputs.length) + ")",
957
+ );
958
+ return result;
959
+ } catch (error) {
960
+ if (error instanceof LionDenTypechainError) throw error;
961
+ throw new LocalTransitionError(
962
+ this.programId + "/" + transitionName + " failed during local execution. This usually means a transition assertion or local runtime check failed. Cause: " + errorMessage(error),
963
+ {
964
+ programId: this.programId,
965
+ transition: transitionName,
966
+ cause: error,
967
+ },
968
+ );
969
+ }
970
+ }
971
+
972
+ protected async expectLocalFailure(
973
+ transitionName: string,
974
+ args: string[],
975
+ options: LocalExecutionOptions = {},
976
+ ): Promise<LocalTransitionError> {
977
+ const network = this.getNetwork();
978
+ if (typeof network.checkLocalExecution !== "function") {
979
+ throw new TransactionShapeError(
980
+ "Network for " + this.programId + " does not expose checkLocalExecution(). Cannot assert local failure for " + transitionName + ".",
981
+ { programId: this.programId, transition: transitionName },
982
+ );
983
+ }
984
+ this.beginTransitionLogBlock();
985
+ this.logTransitionStart("Expecting local failure for", transitionName, args, {
986
+ ...options,
987
+ mode: "local",
988
+ });
989
+ try {
990
+ await network.checkLocalExecution(
991
+ this.programId,
992
+ transitionName,
993
+ args,
994
+ this.buildEffectiveOptions({ ...options, mode: "local" }),
995
+ );
996
+ } catch (error) {
997
+ if (error instanceof LocalVmExecutionError) {
998
+ this.logTransitionDone(
999
+ "Observed expected local failure for",
1000
+ transitionName,
1001
+ "",
1002
+ );
1003
+ return new LocalTransitionError(
1004
+ this.programId + "/" + transitionName + " failed during local execution. This usually means a transition assertion or local runtime check failed. Cause: " + errorMessage(error),
1005
+ {
1006
+ programId: this.programId,
1007
+ transition: transitionName,
1008
+ cause: error,
1009
+ },
1010
+ );
1011
+ }
1012
+ throw error;
1013
+ }
1014
+ throw new UnexpectedLocalSuccessError(
1015
+ this.programId + "/" + transitionName + " was expected to fail during local execution, but it succeeded.",
1016
+ { programId: this.programId, transition: transitionName },
1017
+ );
1018
+ }
1019
+
1020
+ protected async submitTransition(
1021
+ transitionName: string,
1022
+ args: string[],
1023
+ options: OnChainExecutionOptions = {},
1024
+ logStart = true,
1025
+ ): Promise<SubmittedTransition> {
1026
+ if (logStart) {
1027
+ this.beginTransitionLogBlock();
1028
+ this.logTransitionStart("Submitting", transitionName, args, {
1029
+ ...options,
1030
+ mode: "onchain",
1031
+ });
1032
+ }
1033
+ try {
1034
+ const result = await this.executeRaw(transitionName, args, {
1035
+ ...options,
1036
+ mode: "onchain",
1037
+ });
1038
+ if (!result.txId) {
1039
+ throw new TransactionShapeError(
1040
+ this.programId + "/" + transitionName + " was submitted on-chain but no transaction ID was returned.",
1041
+ { programId: this.programId, transition: transitionName },
1042
+ );
1043
+ }
1044
+ this.logTransitionDone("Submitted", transitionName, "(tx: " + result.txId + ")");
1045
+ return { txId: result.txId };
1046
+ } catch (error) {
1047
+ if (error instanceof LionDenTypechainError) throw error;
1048
+ throw new TransitionSubmissionError(
1049
+ this.programId + "/" + transitionName + " failed before confirmation while building or submitting the transaction. Cause: " + errorMessage(error),
1050
+ {
1051
+ programId: this.programId,
1052
+ transition: transitionName,
1053
+ cause: error,
1054
+ },
1055
+ );
1056
+ }
1057
+ }
1058
+
1059
+ protected async settleTransition(
1060
+ transitionName: string,
1061
+ args: string[],
1062
+ options: OnChainExecutionOptions = {},
1063
+ ): Promise<SettledTransition> {
1064
+ const submitted = await this.submitTransition(transitionName, args, options);
1065
+ const network = this.getNetwork();
1066
+ if (typeof network.waitForConfirmation !== "function") {
1067
+ throw new TransactionShapeError(
1068
+ "Network for " + this.programId + " does not expose waitForConfirmation(). Cannot settle " + transitionName + ".",
1069
+ { programId: this.programId, transition: transitionName },
1070
+ );
1071
+ }
1072
+
1073
+ try {
1074
+ this.logTransitionDone(
1075
+ "Waiting for confirmation of",
1076
+ transitionName,
1077
+ "(tx: " + submitted.txId + ")",
1078
+ );
1079
+ const confirmed = await network.waitForConfirmation(submitted.txId, options.confirmTimeout);
1080
+ if (
1081
+ !confirmed ||
1082
+ confirmed.txId !== submitted.txId ||
1083
+ typeof confirmed.blockHeight !== "number" ||
1084
+ (confirmed.status !== "accepted" && confirmed.status !== "rejected")
1085
+ ) {
1086
+ throw new TransactionShapeError(
1087
+ this.programId + "/" + transitionName + " confirmation returned an unexpected shape.",
1088
+ { programId: this.programId, transition: transitionName },
1089
+ );
1090
+ }
1091
+ if (confirmed.status === "accepted") {
1092
+ const { rawOutputs, transitionPublicKey } =
1093
+ this.selectAcceptedTransition(transitionName, confirmed.transitions);
1094
+ this.logTransitionDone(
1095
+ "Accepted",
1096
+ transitionName,
1097
+ "(tx: " + confirmed.txId + ", block: " + confirmed.blockHeight + ")",
1098
+ );
1099
+ return {
1100
+ txId: confirmed.txId,
1101
+ blockHeight: confirmed.blockHeight,
1102
+ status: "accepted",
1103
+ rawOutputs,
1104
+ transitionPublicKey,
1105
+ transitions: confirmed.transitions ?? [],
1106
+ };
1107
+ }
1108
+ const rawOutputs = this.selectRejectedTransitionOutputs(
1109
+ transitionName,
1110
+ confirmed.transitions,
1111
+ );
1112
+ this.logTransitionDone(
1113
+ "Rejected",
1114
+ transitionName,
1115
+ "(tx: " + confirmed.txId + ", block: " + confirmed.blockHeight + ")",
1116
+ );
1117
+ return {
1118
+ txId: confirmed.txId,
1119
+ blockHeight: confirmed.blockHeight,
1120
+ status: "rejected",
1121
+ rawOutputs,
1122
+ };
1123
+ } catch (error) {
1124
+ if (error instanceof LionDenTypechainError) throw error;
1125
+ if (isNetworkConfirmationTimeoutError(error)) {
1126
+ throw new TransactionConfirmationTimeoutError(
1127
+ this.programId + "/" + transitionName + " submitted as " + submitted.txId + " but did not confirm in time. Cause: " + errorMessage(error),
1128
+ {
1129
+ programId: this.programId,
1130
+ transition: transitionName,
1131
+ cause: error,
1132
+ },
1133
+ );
1134
+ }
1135
+ const message = errorMessage(error);
1136
+ throw new TransactionShapeError(
1137
+ this.programId + "/" + transitionName + " could not resolve confirmation status for " + submitted.txId + ". Cause: " + message,
1138
+ {
1139
+ programId: this.programId,
1140
+ transition: transitionName,
1141
+ cause: error,
1142
+ },
1143
+ );
1144
+ }
1145
+ }
1146
+
1147
+ protected async expectAccepted(
1148
+ transitionName: string,
1149
+ args: string[],
1150
+ options: OnChainExecutionOptions = {},
1151
+ ): Promise<AcceptedTransitionBase> {
1152
+ const settled = await this.settleTransition(transitionName, args, options);
1153
+ if (settled.status !== "accepted") {
1154
+ throw new OnChainRejectedError(
1155
+ this.programId + "/" + transitionName + " confirmed rejected as " + settled.txId + ". This is an on-chain rejection, commonly from a finalizer assertion or network execution rule, not a local transition failure.",
1156
+ { programId: this.programId, transition: transitionName },
1157
+ );
1158
+ }
1159
+ return settled;
1160
+ }
1161
+
1162
+ protected async expectRejected(
1163
+ transitionName: string,
1164
+ args: string[],
1165
+ options: OnChainExecutionOptions = {},
1166
+ ): Promise<RejectedTransition> {
1167
+ const settled = await this.settleTransition(transitionName, args, options);
1168
+ if (settled.status !== "rejected") {
1169
+ throw new UnexpectedTransactionStatusError(
1170
+ this.programId + "/" + transitionName + " was expected to be rejected on-chain, but " + settled.txId + " was accepted.",
1171
+ { programId: this.programId, transition: transitionName },
1172
+ );
1173
+ }
1174
+ return {
1175
+ txId: settled.txId,
1176
+ blockHeight: settled.blockHeight,
1177
+ status: "rejected",
1178
+ rawOutputs: settled.rawOutputs,
1179
+ };
1180
+ }
1181
+
1182
+ /**
1183
+ * Typed-projection variant of \`settleTransition\`. Runs the projector only
1184
+ * on the accepted branch. Rejected settlements pass through with no typed
1185
+ * outputs.
1186
+ *
1187
+ * Error policy: \`TransactionShapeError\` from the projector (typically from
1188
+ * \`rawOutputAt\`) is rethrown unchanged so the precise outputIndex/context
1189
+ * survives. Any other error — including LionDenTypechainError subclasses
1190
+ * like TransitionInputError (e.g. malformed on-chain plaintext failing a
1191
+ * primitive parser) and native Errors — is wrapped as TransactionShapeError
1192
+ * with the original via \`.cause\`. This keeps "bad on-chain data" failures
1193
+ * classified as a shape error rather than misleading the caller that they
1194
+ * provided bad input.
1195
+ */
1196
+ protected async settleTyped<TOutputs>(
1197
+ transitionName: string,
1198
+ args: string[],
1199
+ options: OnChainExecutionOptions,
1200
+ project: (
1201
+ rawOutputs: readonly RawTransitionOutput[],
1202
+ tpk: string,
1203
+ transitions: readonly ConfirmedTransitionRecord[],
1204
+ ) => TOutputs,
1205
+ ): Promise<AcceptedTransition<TOutputs> | RejectedTransition> {
1206
+ const settled = await this.settleTransition(transitionName, args, options);
1207
+ if (settled.status === "accepted") {
1208
+ const outputs = this.runProjector(
1209
+ transitionName,
1210
+ settled.rawOutputs,
1211
+ settled.transitionPublicKey,
1212
+ settled.transitions,
1213
+ project,
1214
+ );
1215
+ return {
1216
+ txId: settled.txId,
1217
+ blockHeight: settled.blockHeight,
1218
+ status: "accepted",
1219
+ rawOutputs: settled.rawOutputs,
1220
+ transitionPublicKey: settled.transitionPublicKey,
1221
+ transitions: settled.transitions,
1222
+ outputs,
1223
+ };
1224
+ }
1225
+ return {
1226
+ txId: settled.txId,
1227
+ blockHeight: settled.blockHeight,
1228
+ status: "rejected",
1229
+ rawOutputs: settled.rawOutputs,
1230
+ };
1231
+ }
1232
+
1233
+ /**
1234
+ * Typed-projection variant of \`expectAccepted\`. Same error policy as
1235
+ * \`settleTyped\` for projector failures; rejections still throw
1236
+ * \`OnChainRejectedError\`.
1237
+ */
1238
+ protected async expectAcceptedTyped<TOutputs>(
1239
+ transitionName: string,
1240
+ args: string[],
1241
+ options: OnChainExecutionOptions,
1242
+ project: (
1243
+ rawOutputs: readonly RawTransitionOutput[],
1244
+ tpk: string,
1245
+ transitions: readonly ConfirmedTransitionRecord[],
1246
+ ) => TOutputs,
1247
+ ): Promise<AcceptedTransition<TOutputs>> {
1248
+ const accepted = await this.expectAccepted(transitionName, args, options);
1249
+ const outputs = this.runProjector(
1250
+ transitionName,
1251
+ accepted.rawOutputs,
1252
+ accepted.transitionPublicKey,
1253
+ accepted.transitions,
1254
+ project,
1255
+ );
1256
+ return {
1257
+ txId: accepted.txId,
1258
+ blockHeight: accepted.blockHeight,
1259
+ status: "accepted",
1260
+ rawOutputs: accepted.rawOutputs,
1261
+ transitionPublicKey: accepted.transitionPublicKey,
1262
+ transitions: accepted.transitions,
1263
+ outputs,
1264
+ };
1265
+ }
1266
+
1267
+ private runProjector<TOutputs>(
1268
+ transitionName: string,
1269
+ rawOutputs: readonly RawTransitionOutput[],
1270
+ tpk: string,
1271
+ transitions: readonly ConfirmedTransitionRecord[],
1272
+ project: (
1273
+ rawOutputs: readonly RawTransitionOutput[],
1274
+ tpk: string,
1275
+ transitions: readonly ConfirmedTransitionRecord[],
1276
+ ) => TOutputs,
1277
+ ): TOutputs {
1278
+ try {
1279
+ return project(rawOutputs, tpk, transitions);
1280
+ } catch (cause: unknown) {
1281
+ if (cause instanceof TransactionShapeError) throw cause;
1282
+ throw new TransactionShapeError(
1283
+ "On-chain output decoding failed for " + this.programId + "/" + transitionName + ": " + errorMessage(cause),
1284
+ { programId: this.programId, transition: transitionName, cause },
1285
+ );
1286
+ }
1287
+ }
1288
+
1289
+ // Transition lifecycle wrappers funnel through these entry points; putting the
1290
+ // separator here avoids duplicate blank lines for settled/accepted/rejected calls.
1291
+ private beginTransitionLogBlock(): void {
1292
+ if (!shouldRenderDivider()) return;
1293
+ console.log(logDivider());
1294
+ }
1295
+
1296
+ private logTransitionStart(
1297
+ kind: string,
1298
+ transitionName: string,
1299
+ args: readonly string[],
1300
+ options: BaseCallOptions & { readonly mode: ExecutionMode },
1301
+ ): void {
1302
+ console.log(
1303
+ styleLogRole(kind, transitionLogKindRole(kind)) +
1304
+ " " +
1305
+ this.formatTransitionCall(transitionName, args) +
1306
+ this.formatSignerSuffix(options),
1307
+ );
1308
+ }
1309
+
1310
+ private logTransitionDone(kind: string, transitionName: string, details: string): void {
1311
+ console.log(
1312
+ details.length > 0
1313
+ ? styleLogRole(kind, transitionLogKindRole(kind)) +
1314
+ " " +
1315
+ this.programId +
1316
+ "/" +
1317
+ transitionName +
1318
+ this.formatTransitionDetails(details)
1319
+ : styleLogRole(kind, transitionLogKindRole(kind)) +
1320
+ " " +
1321
+ this.programId +
1322
+ "/" +
1323
+ transitionName,
1324
+ );
1325
+ }
1326
+
1327
+ private formatTransitionDetails(details: string): string {
1328
+ if (details.startsWith("(") && details.endsWith(")")) {
1329
+ return " " + logMetadata(details);
1330
+ }
1331
+ const metadataStart = details.lastIndexOf(" (");
1332
+ if (metadataStart >= 0 && details.endsWith(")")) {
1333
+ const outcome = details.slice(0, metadataStart);
1334
+ const metadata = details.slice(metadataStart + 1);
1335
+ return " " + outcome + " " + logMetadata(metadata);
1336
+ }
1337
+ return " " + details;
1338
+ }
1339
+
1340
+ private formatTransitionCall(transitionName: string, args: readonly string[]): string {
1341
+ return (
1342
+ this.programId +
1343
+ "/" +
1344
+ transitionName +
1345
+ "(" +
1346
+ formatLogArgs(args) +
1347
+ ")"
1348
+ );
1349
+ }
1350
+
1351
+ private formatSignerSuffix(
1352
+ options: BaseCallOptions & { readonly mode: ExecutionMode },
1353
+ ): string {
1354
+ const effectiveOptions = this.buildEffectiveOptions(options);
1355
+ const signer = effectiveOptions.signer;
1356
+ if (!signer) return "";
1357
+ if (typeof signer.address === "string" && signer.address.length > 0) {
1358
+ return logMetadata(" (signer: " + signer.address + ")");
1359
+ }
1360
+ return logMetadata(" (signer override)");
1361
+ }
1362
+
1363
+ /**
1364
+ * Fail-fast indexed access into a confirmed transition's rawOutputs. Throws
1365
+ * \`TransactionShapeError\` with outputIndex populated when the entry is
1366
+ * missing or not a string. Used by generated projectors.
1367
+ *
1368
+ * The index parameter is the ORIGINAL ABI output position (Futures still
1369
+ * occupy their position in rawOutputs even though they're excluded from
1370
+ * typed projections).
1371
+ */
1372
+ static rawOutputAt(
1373
+ rawOutputs: readonly RawTransitionOutput[],
1374
+ programId: string,
1375
+ transitionName: string,
1376
+ abiIndex: number,
1377
+ ): string {
1378
+ const value = rawOutputs[abiIndex];
1379
+ if (typeof value !== "string") {
1380
+ const kind = value === undefined
1381
+ ? "undefined"
1382
+ : value === null
1383
+ ? "null"
1384
+ : typeof value === "object" && "kind" in value && value.kind === "idOnly"
1385
+ ? "id-only output " + value.id
1386
+ : typeof value;
1387
+ throw new TransactionShapeError(
1388
+ "Expected " + programId + "/" + transitionName + " to have raw output at ABI index " + abiIndex + ", got " + kind + ".",
1389
+ { programId, transition: transitionName, outputIndex: abiIndex },
1390
+ );
1391
+ }
1392
+ return value;
1393
+ }
1394
+
1395
+ /**
1396
+ * Build a typed EncryptedRecord<T> handle from a ciphertext. The handle's
1397
+ * \`.decrypt(key)\` routes through \`BaseContract.decryptRecord\` with the
1398
+ * supplied deserializer so it works equally for local and imported records.
1399
+ *
1400
+ * \`program\` and \`recordName\` are stored on the handle so
1401
+ * \`.match(matcher)\` can verify the matcher's identity at decrypt time.
1402
+ */
1403
+ static makeEncryptedRecord<T>(
1404
+ program: string,
1405
+ recordName: string,
1406
+ ciphertext: string,
1407
+ deserialize: (plaintext: string) => T,
1408
+ sourceProgramId?: string,
1409
+ ): EncryptedRecord<T> {
1410
+ return {
1411
+ program,
1412
+ recordName,
1413
+ ciphertext,
1414
+ decrypt(key: DecryptionKey): Promise<T> {
1415
+ return BaseContract.decryptRecord(ciphertext, key, deserialize);
1416
+ },
1417
+ match<TOut = T>(
1418
+ matcher: RecordOutputMatcher<TOut, "unbound"> | RecordOutputMatcher<TOut, "bound">,
1419
+ ): CapturedRecord<TOut> {
1420
+ const runtimeMatcher =
1421
+ sourceProgramId !== undefined && sourceProgramId !== program && matcher.program === sourceProgramId
1422
+ ? BaseContract.bindRecordOutputMatcherProgram(matcher, program)
1423
+ : matcher;
1424
+ return {
1425
+ async decrypt(key: DecryptionKey): Promise<TOut> {
1426
+ if (runtimeMatcher.program !== program || runtimeMatcher.recordName !== recordName) {
1427
+ throw new TransactionShapeError(
1428
+ "Matcher identity " + matcher.program + "/" + matcher.recordName + " does not match the encrypted record's identity " + program + "/" + recordName + ". Pass the matcher whose helper corresponds to this record's type.",
1429
+ { programId: program, transition: recordName },
1430
+ );
1431
+ }
1432
+ return BaseContract.decryptRecord(ciphertext, key, runtimeMatcher.deserialize);
1433
+ },
1434
+ };
1435
+ },
1436
+ };
1437
+ }
1438
+
1439
+ /**
1440
+ * Fail-fast indexed access for id-only record output slots. Parallel to
1441
+ * \`rawOutputAt\`, but expects the entry at \`abiIndex\` to be an
1442
+ * \`IdOnlyRawOutput\` (not a ciphertext string). Throws
1443
+ * \`TransactionShapeError\` with \`outputIndex\` populated on every other
1444
+ * shape.
1445
+ *
1446
+ * Used by generated projectors for \`dyn record\` and external \`Record\`
1447
+ * output positions, both of which the chain surfaces as id-only on the
1448
+ * caller's transition.
1449
+ */
1450
+ static idOnlyRecordOutputAt(
1451
+ rawOutputs: readonly RawTransitionOutput[],
1452
+ programId: string,
1453
+ transitionName: string,
1454
+ abiIndex: number,
1455
+ ): IdOnlyRawOutput {
1456
+ const value = rawOutputs[abiIndex];
1457
+ if (
1458
+ value !== null &&
1459
+ typeof value === "object" &&
1460
+ "kind" in value &&
1461
+ (value as { kind?: unknown }).kind === "idOnly"
1462
+ ) {
1463
+ return value as IdOnlyRawOutput;
1464
+ }
1465
+ const kind = value === undefined
1466
+ ? "undefined"
1467
+ : value === null
1468
+ ? "null"
1469
+ : typeof value === "string"
1470
+ ? "ciphertext string"
1471
+ : typeof value;
1472
+ throw new TransactionShapeError(
1473
+ "Expected " + programId + "/" + transitionName + " to have an id-only record output at ABI index " + abiIndex + ", got " + kind + ".",
1474
+ { programId, transition: transitionName, outputIndex: abiIndex },
1475
+ );
1476
+ }
1477
+
1478
+ /**
1479
+ * Resolve a bound matcher's source against the callgraph and decrypt the
1480
+ * referenced record ciphertext. Shared by \`makeIdOnlyDynamicRecordHandle\`
1481
+ * and \`makeIdOnlyExternalRecordHandle\`; both arms use the same selector
1482
+ * + program-mismatch + ciphertext-presence checks.
1483
+ *
1484
+ * \`notACiphertextHint\` is the arm-specific tail of the not-a-ciphertext
1485
+ * error message — the dyn handle hints at V15 sibling-record materialization,
1486
+ * the external handle hints at callee-transition selection.
1487
+ */
1488
+ static async resolveAndDecryptIdOnly<TOut>(
1489
+ transitions: readonly ConfirmedTransitionRecord[],
1490
+ matcher: RecordOutputMatcher<TOut, "bound">,
1491
+ key: DecryptionKey,
1492
+ notACiphertextHint: string,
1493
+ ): Promise<TOut> {
1494
+ const source = matcher.source;
1495
+ const selected = BaseContract.resolveIdOnlySource(transitions, source);
1496
+ if (selected.transition.programId !== matcher.program) {
1497
+ throw new IdOnlyRecordResolutionError(
1498
+ "program-mismatch",
1499
+ "Selected transition " + selected.transition.programId + "/" + selected.transition.transitionName + " does not match matcher program " + matcher.program + ". Pass \`<helper>.output.from(...)\` for the program that emitted the record, or use \`.at(transitionIndex, outputIndex)\` to point at the correct callee transition.",
1500
+ {
1501
+ expectedProgram: matcher.program,
1502
+ actualProgram: selected.transition.programId,
1503
+ programId: selected.transition.programId,
1504
+ transition: selected.transition.transitionName,
1505
+ outputIndex: source.outputIndex,
1506
+ },
1507
+ );
1508
+ }
1509
+ const ciphertext = selected.transition.rawOutputs[source.outputIndex];
1510
+ if (typeof ciphertext !== "string") {
1511
+ const kind = ciphertext === undefined
1512
+ ? "undefined"
1513
+ : ciphertext === null
1514
+ ? "null"
1515
+ : typeof ciphertext === "object" && "kind" in ciphertext && (ciphertext as { kind?: unknown }).kind === "idOnly"
1516
+ ? "id-only output " + (ciphertext as IdOnlyRawOutput).id
1517
+ : typeof ciphertext;
1518
+ throw new IdOnlyRecordResolutionError(
1519
+ "not-a-ciphertext",
1520
+ "Selected output at " + matcher.program + "/" + selected.transition.transitionName + " index " + source.outputIndex + " is not a record ciphertext (got " + kind + "). " + notACiphertextHint,
1521
+ {
1522
+ programId: selected.transition.programId,
1523
+ transition: selected.transition.transitionName,
1524
+ outputIndex: source.outputIndex,
1525
+ },
1526
+ );
1527
+ }
1528
+ return BaseContract.decryptRecord(ciphertext, key, matcher.deserialize);
1529
+ }
1530
+
1531
+ static bindRecordOutputMatcherProgram<T, S extends "unbound" | "bound">(
1532
+ matcher: RecordOutputMatcher<T, S>,
1533
+ programId: string,
1534
+ ): RecordOutputMatcher<T, S> {
1535
+ if (matcher.program === programId) {
1536
+ return matcher;
1537
+ }
1538
+ return buildRecordOutputMatcher(
1539
+ {
1540
+ program: programId,
1541
+ recordName: matcher.recordName,
1542
+ deserialize: matcher.deserialize,
1543
+ },
1544
+ rebindMatcherSource(matcher.source, matcher.program, programId),
1545
+ ) as RecordOutputMatcher<T, S>;
1546
+ }
1547
+
1548
+ private static bindOwnRuntimeMatcher<T>(
1549
+ matcher: RecordOutputMatcher<T, "bound">,
1550
+ sourceProgramId: string | undefined,
1551
+ runtimeProgramId: string | undefined,
1552
+ ): RecordOutputMatcher<T, "bound"> {
1553
+ if (
1554
+ sourceProgramId === undefined ||
1555
+ runtimeProgramId === undefined ||
1556
+ sourceProgramId === runtimeProgramId ||
1557
+ matcher.program !== sourceProgramId
1558
+ ) {
1559
+ return matcher;
1560
+ }
1561
+ return BaseContract.bindRecordOutputMatcherProgram(matcher, runtimeProgramId);
1562
+ }
1563
+
1564
+ /**
1565
+ * Build an \`IdOnlyDynamicRecordHandle\` for a \`dyn record\` output. The
1566
+ * chain never exposes a ciphertext for the dynamic-record id itself, so
1567
+ * \`.match(matcher.from(...)|.at(...)).decrypt(key)\` does NOT dereference
1568
+ * the id — it selects an explicit sibling concrete output in the same
1569
+ * callgraph and decrypts that. See the type's docstring for the V15
1570
+ * record-existence rule that makes a sibling concrete output available in
1571
+ * compliant programs.
1572
+ */
1573
+ static makeIdOnlyDynamicRecordHandle(
1574
+ entry: IdOnlyRawOutput,
1575
+ transitions: readonly ConfirmedTransitionRecord[],
1576
+ sourceProgramId?: string,
1577
+ runtimeProgramId?: string,
1578
+ ): IdOnlyDynamicRecordHandle {
1579
+ return {
1580
+ kind: "idOnlyDynamicRecord",
1581
+ type: "record_dynamic",
1582
+ id: entry.id,
1583
+ transitions,
1584
+ match<TOut>(matcher: RecordOutputMatcher<TOut, "bound">): CapturedRecord<TOut> {
1585
+ const runtimeMatcher = BaseContract.bindOwnRuntimeMatcher(matcher, sourceProgramId, runtimeProgramId);
1586
+ return {
1587
+ decrypt(key: DecryptionKey): Promise<TOut> {
1588
+ return BaseContract.resolveAndDecryptIdOnly(
1589
+ transitions,
1590
+ runtimeMatcher,
1591
+ key,
1592
+ "The dyn-handle's \`.match(...).decrypt(...)\` does not dereference the dynamic-record id — it expects \`.from(transition, outputIndex)\` or \`.at(...)\` pointing at a sibling concrete record output materialized by a V15-compliant callee.",
1593
+ );
1594
+ },
1595
+ };
1596
+ },
1597
+ };
1598
+ }
1599
+
1600
+ /**
1601
+ * Build an \`IdOnlyExternalRecordHandle<T>\` for an external \`Record\`
1602
+ * output. The handle's \`.match(matcher.from(...)|.at(...)).decrypt(key)\`
1603
+ * selects the callee transition that actually emitted the ciphertext and
1604
+ * deserializes via the matcher.
1605
+ *
1606
+ * Source selection is explicit (named via \`.from\` or positional via
1607
+ * \`.at\`). See \`IdOnlyRecordResolutionError.reason\` for the specific
1608
+ * failure modes.
1609
+ */
1610
+ static makeIdOnlyExternalRecordHandle<T>(
1611
+ entry: IdOnlyRawOutput,
1612
+ transitions: readonly ConfirmedTransitionRecord[],
1613
+ sourceProgramId?: string,
1614
+ runtimeProgramId?: string,
1615
+ ): IdOnlyExternalRecordHandle<T> {
1616
+ return {
1617
+ kind: "idOnlyExternalRecord",
1618
+ type: "external_record",
1619
+ id: entry.id,
1620
+ transitions,
1621
+ match<TOut = T>(matcher: RecordOutputMatcher<TOut, "bound">): CapturedRecord<TOut> {
1622
+ const runtimeMatcher = BaseContract.bindOwnRuntimeMatcher(matcher, sourceProgramId, runtimeProgramId);
1623
+ return {
1624
+ decrypt(key: DecryptionKey): Promise<TOut> {
1625
+ return BaseContract.resolveAndDecryptIdOnly(
1626
+ transitions,
1627
+ runtimeMatcher,
1628
+ key,
1629
+ "The callee transition you selected may not actually hold the source ciphertext for this id-only record.",
1630
+ );
1631
+ },
1632
+ };
1633
+ },
1634
+ };
1635
+ }
1636
+
1637
+ /**
1638
+ * Resolve an \`IdOnlyRecordSource\` to a specific transition in the
1639
+ * callgraph. Throws the appropriate \`IdOnlyRecordResolutionError\` reason
1640
+ * when the selector is ambiguous, out of range, or has no match. Internal
1641
+ * helper for \`makeIdOnlyExternalRecordHandle\`.
1642
+ */
1643
+ private static resolveIdOnlySource(
1644
+ transitions: readonly ConfirmedTransitionRecord[],
1645
+ source: IdOnlyRecordSource,
1646
+ ): { readonly transition: ConfirmedTransitionRecord; readonly transitionIndex: number } {
1647
+ if ("transitionIndex" in source) {
1648
+ const idx = source.transitionIndex;
1649
+ const t = transitions[idx];
1650
+ if (!t) {
1651
+ throw new IdOnlyRecordResolutionError(
1652
+ "transition-index-out-of-range",
1653
+ "transitionIndex " + idx + " is out of range; transactions has " + transitions.length + " transition(s).",
1654
+ { outputIndex: source.outputIndex },
1655
+ );
1656
+ }
1657
+ return { transition: t, transitionIndex: idx };
1658
+ }
1659
+ const matchesWithIndex: { transition: ConfirmedTransitionRecord; index: number }[] = [];
1660
+ for (let i = 0; i < transitions.length; i++) {
1661
+ const t = transitions[i]!;
1662
+ if (t.programId === source.programId && t.transitionName === source.transitionName) {
1663
+ matchesWithIndex.push({ transition: t, index: i });
1664
+ }
1665
+ }
1666
+ if (matchesWithIndex.length === 0) {
1667
+ const available = transitions.map((t) => t.programId + "/" + t.transitionName).join(", ");
1668
+ throw new IdOnlyRecordResolutionError(
1669
+ "transition-not-found",
1670
+ "No transition matching " + source.programId + "/" + source.transitionName + " in confirmed transaction. Available: " + (available || "(none)") + ".",
1671
+ {
1672
+ programId: source.programId,
1673
+ transition: source.transitionName,
1674
+ outputIndex: source.outputIndex,
1675
+ },
1676
+ );
1677
+ }
1678
+ if (source.transitionMatchIndex === undefined) {
1679
+ if (matchesWithIndex.length > 1) {
1680
+ throw new IdOnlyRecordResolutionError(
1681
+ "transition-not-unique",
1682
+ matchesWithIndex.length + " transitions match " + source.programId + "/" + source.transitionName + "; pass \`.from(name, outputIndex, { match: n })\` to disambiguate (0-based within matches) or use \`.at(transitionIndex, outputIndex)\` to index positionally.",
1683
+ {
1684
+ programId: source.programId,
1685
+ transition: source.transitionName,
1686
+ outputIndex: source.outputIndex,
1687
+ },
1688
+ );
1689
+ }
1690
+ const only = matchesWithIndex[0]!;
1691
+ return { transition: only.transition, transitionIndex: only.index };
1692
+ }
1693
+ const m = matchesWithIndex[source.transitionMatchIndex];
1694
+ if (!m) {
1695
+ throw new IdOnlyRecordResolutionError(
1696
+ "transition-match-index-out-of-range",
1697
+ "match index " + source.transitionMatchIndex + " (from \`.from(..., { match })\`) is out of range; " + matchesWithIndex.length + " transition(s) match " + source.programId + "/" + source.transitionName + ".",
1698
+ {
1699
+ programId: source.programId,
1700
+ transition: source.transitionName,
1701
+ outputIndex: source.outputIndex,
1702
+ },
1703
+ );
1704
+ }
1705
+ return { transition: m.transition, transitionIndex: m.index };
1706
+ }
1707
+
1708
+ /**
1709
+ * Build a typed EncryptedValue<T> handle from a value ciphertext. The
1710
+ * handle's \`.decrypt(key)\` routes through the value-ciphertext decryption
1711
+ * path: it normalizes the key, calls the SDK's
1712
+ * \`Ciphertext.decryptWithTransitionInfo\`, then runs the supplied
1713
+ * deserializer over the resulting Leo literal.
1714
+ *
1715
+ * Error policy mirrors \`decryptRecord\` but with a NARROW pass-through:
1716
+ * only \`RecordDecryptionKeyError\` (caller-input shape) escapes unwrapped.
1717
+ * Everything else — including other \`LionDenTypechainError\` subclasses
1718
+ * (e.g. \`TransitionInputError\` from a primitive parser on a malformed
1719
+ * decrypted plaintext), \`NetworkValueDecryptionError\`, and native errors
1720
+ * — wraps as \`LocalValueDecryptionError\` so the user-facing error name
1721
+ * matches the decryption phase.
1722
+ */
1723
+ static makeEncryptedValue<T>(
1724
+ ciphertext: string,
1725
+ tpk: string,
1726
+ programId: string,
1727
+ transitionName: string,
1728
+ globalIndex: number,
1729
+ deserialize: (plaintext: string) => T,
1730
+ ): EncryptedValue<T> {
1731
+ return {
1732
+ ciphertext,
1733
+ async decrypt(key: DecryptionKey): Promise<T> {
1734
+ try {
1735
+ const viewKey = await BaseContract.normalizeRecordDecryptionKey(key);
1736
+ const plaintext = await decryptValueCiphertext(
1737
+ ciphertext, viewKey, tpk, programId, transitionName, globalIndex,
1738
+ );
1739
+ return deserialize(plaintext);
1740
+ } catch (cause: unknown) {
1741
+ if (cause instanceof RecordDecryptionKeyError) throw cause;
1742
+ throw new LocalValueDecryptionError(
1743
+ "Failed to decrypt value ciphertext for " + programId + "/" + transitionName + " output #" + globalIndex + ". Cause: " + errorMessage(cause),
1744
+ { programId, transition: transitionName, outputIndex: globalIndex, cause },
1745
+ );
1746
+ }
1747
+ },
1748
+ };
1749
+ }
1750
+
1751
+ protected outputAt(
1752
+ result: TransitionExecutionResult,
1753
+ transitionName: string,
1754
+ index: number,
1755
+ ): string {
1756
+ const value = result.outputs[index];
1757
+ if (typeof value !== "string") {
1758
+ throw new TransactionShapeError(
1759
+ this.programId + "/" + transitionName + " local execution did not return output #" + index + ".",
1760
+ { programId: this.programId, transition: transitionName },
1761
+ );
1762
+ }
1763
+ return value;
1764
+ }
1765
+
1766
+ private async executeRaw(
1767
+ transitionName: string,
1768
+ args: string[],
1769
+ options: BaseCallOptions & { readonly mode: ExecutionMode },
1770
+ ): Promise<TransitionExecutionResult> {
1771
+ const network = this.getNetwork();
1772
+ return network.execute(this.programId, transitionName, args, this.buildEffectiveOptions(options));
1773
+ }
1774
+
1775
+ private buildEffectiveOptions(
1776
+ options: BaseCallOptions & { readonly mode: ExecutionMode },
1777
+ ): BaseCallOptions & { readonly mode: ExecutionMode } {
1778
+ const effectiveOptions: BaseCallOptions & { readonly mode: ExecutionMode } = { ...options };
1779
+ if (this.signer && !effectiveOptions.signer) {
1780
+ effectiveOptions.signer = this.signer;
1781
+ }
1782
+ if (effectiveOptions.prove === undefined) {
1783
+ const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;
1784
+ if (env?.["LIONDEN_PROVE"] === "true") {
1785
+ effectiveOptions.prove = true;
1786
+ }
1787
+ }
1788
+ const mergedImports = [...this.instanceImports, ...(options.imports ?? [])];
1789
+ if (mergedImports.length > 0) {
1790
+ effectiveOptions.imports = mergedImports;
1791
+ }
1792
+ return effectiveOptions;
1793
+ }
1794
+
1795
+ protected async queryMapping(
1796
+ mappingName: string,
1797
+ key: string,
1798
+ ): Promise<string | null> {
1799
+ const lre = this.getLre();
1800
+ const network = (lre as any).network;
1801
+
1802
+ if (!network || typeof network.getMappingValue !== "function") {
1803
+ throw new TransactionShapeError(
1804
+ "Network is not available for " + this.programId + ". Ensure @lionden/plugin-network is loaded and connected before querying mappings.",
1805
+ { programId: this.programId },
1806
+ );
1807
+ }
1808
+
1809
+ return network.getMappingValue(this.programId, mappingName, key);
1810
+ }
1811
+
1812
+ protected async mappingContains(
1813
+ mappingName: string,
1814
+ key: string,
1815
+ ): Promise<boolean> {
1816
+ return (await this.queryMapping(mappingName, key)) !== null;
1817
+ }
1818
+
1819
+ protected async requireMappingRaw(
1820
+ mappingName: string,
1821
+ key: string,
1822
+ ): Promise<string> {
1823
+ const raw = await this.queryMapping(mappingName, key);
1824
+ if (raw === null) {
1825
+ throw new MappingKeyNotFoundError(
1826
+ 'Mapping "' + mappingName + '" on ' + this.programId + ' has no entry for key ' + key + '.',
1827
+ { programId: this.programId, mapping: mappingName, key },
1828
+ );
1829
+ }
1830
+ return raw;
1831
+ }
1832
+
1833
+ protected async queryStorage(variableName: string): Promise<string | null> {
1834
+ const lre = this.getLre();
1835
+ const network = (lre as any).network;
1836
+
1837
+ if (!network || typeof network.getStorageValue !== "function") {
1838
+ throw new TransactionShapeError(
1839
+ "Network is not available for " + this.programId + ". Ensure @lionden/plugin-network is loaded and connected before querying storage variables.",
1840
+ { programId: this.programId },
1841
+ );
1842
+ }
1843
+
1844
+ return network.getStorageValue(this.programId, variableName);
1845
+ }
1846
+
1847
+ protected async requireStorageRaw(variableName: string): Promise<string> {
1848
+ const raw = await this.queryStorage(variableName);
1849
+ if (raw === null) {
1850
+ throw new StorageValueNotFoundError(
1851
+ 'Storage variable "' + variableName + '" on ' + this.programId + ' has no value.',
1852
+ { programId: this.programId, storage: variableName },
1853
+ );
1854
+ }
1855
+ return raw;
1856
+ }
1857
+
1858
+ protected async queryStorageVectorLength(variableName: string): Promise<number> {
1859
+ const lre = this.getLre();
1860
+ const network = (lre as any).network;
1861
+
1862
+ if (!network || typeof network.getStorageVectorLength !== "function") {
1863
+ throw new TransactionShapeError(
1864
+ "Network is not available for " + this.programId + ". Ensure @lionden/plugin-network is loaded and connected before querying storage vectors.",
1865
+ { programId: this.programId },
1866
+ );
1867
+ }
1868
+
1869
+ return network.getStorageVectorLength(this.programId, variableName);
1870
+ }
1871
+
1872
+ protected async queryStorageVector(variableName: string, index: number): Promise<string | null> {
1873
+ BaseContract.serializeUInt(index, 32, { programId: this.programId, input: variableName + " index" });
1874
+ const length = await this.queryStorageVectorLength(variableName);
1875
+ if (index >= length) return null;
1876
+
1877
+ const lre = this.getLre();
1878
+ const network = (lre as any).network;
1879
+
1880
+ if (!network || typeof network.getStorageVectorValue !== "function") {
1881
+ throw new TransactionShapeError(
1882
+ "Network is not available for " + this.programId + ". Ensure @lionden/plugin-network is loaded and connected before querying storage vectors.",
1883
+ { programId: this.programId },
1884
+ );
1885
+ }
1886
+
1887
+ return network.getStorageVectorValue(this.programId, variableName, index);
1888
+ }
1889
+
1890
+ protected async requireStorageVectorRaw(variableName: string, index: number): Promise<string> {
1891
+ const raw = await this.queryStorageVector(variableName, index);
1892
+ if (raw === null) {
1893
+ throw new StorageValueNotFoundError(
1894
+ 'Storage vector "' + variableName + '" on ' + this.programId + ' has no entry at index ' + index + '.',
1895
+ { programId: this.programId, storage: variableName + "[" + index + "]" },
1896
+ );
1897
+ }
1898
+ return raw;
1899
+ }
1900
+
1901
+ /**
1902
+ * Read every element of a storage vector in logical order. Resolves the
1903
+ * length once, then reads indices [0, length) sequentially (1 + N
1904
+ * round-trips, not 2N), so stale lowered entries beyond the logical length
1905
+ * are never read. A null at any in-range index is a torn read and throws
1906
+ * StorageValueNotFoundError rather than silently truncating.
1907
+ */
1908
+ protected async queryStorageVectorAll(variableName: string): Promise<string[]> {
1909
+ const length = await this.queryStorageVectorLength(variableName);
1910
+ const out: string[] = [];
1911
+ const lre = this.getLre();
1912
+ const network = (lre as any).network;
1913
+
1914
+ if (!network || typeof network.getStorageVectorValue !== "function") {
1915
+ throw new TransactionShapeError(
1916
+ "Network is not available for " + this.programId + ". Ensure @lionden/plugin-network is loaded and connected before querying storage vectors.",
1917
+ { programId: this.programId },
1918
+ );
1919
+ }
1920
+
1921
+ for (let i = 0; i < length; i++) {
1922
+ const raw = await network.getStorageVectorValue(this.programId, variableName, i);
1923
+ if (raw === null) {
1924
+ throw new StorageValueNotFoundError(
1925
+ 'Storage vector "' + variableName + '" on ' + this.programId + ' is missing element at index ' + i + ' (length ' + length + ').',
1926
+ { programId: this.programId, storage: variableName + "[" + i + "]" },
1927
+ );
1928
+ }
1929
+ out.push(raw);
1930
+ }
1931
+ return out;
1932
+ }
1933
+
1934
+ // ---------------------------------------------------------------------------
1935
+ // Leo string to JS value parsers and JS value to Leo string serializers
1936
+ // ---------------------------------------------------------------------------
1937
+
1938
+ static stripSuffix(value: string): string {
1939
+ return value.replace(/(?:u(?:8|16|32|64|128)|i(?:8|16|32|64|128)|field|group|scalar|bool|address)(?:\.(?:public|private))?$/i, "");
1940
+ }
1941
+
1942
+ static parseBoolean(value: string): boolean {
1943
+ return stripVisibility(value) === "true";
1944
+ }
1945
+
1946
+ static parseNumber(value: string): number {
1947
+ return Number(BaseContract.stripSuffix(value));
1948
+ }
1949
+
1950
+ static parseBigInt(value: string): bigint {
1951
+ return BigInt(BaseContract.stripSuffix(value));
1952
+ }
1953
+
1954
+ static parseString(value: string): string {
1955
+ return stripVisibility(value);
1956
+ }
1957
+
1958
+ static assertObject(value: unknown, context?: TransitionInputContext): asserts value is Record<string, unknown> {
1959
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1960
+ throw createInputError("object", value, context);
1961
+ }
1962
+ }
1963
+
1964
+ static serializeBoolean(value: unknown, context?: TransitionInputContext): string {
1965
+ if (typeof value !== "boolean") {
1966
+ throw createInputError("boolean", value, context);
1967
+ }
1968
+ return String(value);
1969
+ }
1970
+
1971
+ static serializeArray(
1972
+ value: unknown,
1973
+ context: TransitionInputContext | undefined,
1974
+ serializeElement: (value: unknown, context: TransitionInputContext | undefined) => string,
1975
+ ): string {
1976
+ if (!Array.isArray(value)) {
1977
+ throw createInputError("array", value, context);
1978
+ }
1979
+ return "[" + value.map((element, index) =>
1980
+ serializeElement(element, BaseContract.childInputContext(context, String(index))),
1981
+ ).join(", ") + "]";
1982
+ }
1983
+
1984
+ static serializeUnsupportedOptionalNone(context?: TransitionInputContext): never {
1985
+ throw createInputError(
1986
+ "non-null Optional value",
1987
+ null,
1988
+ context,
1989
+ "This Optional inner type has no generated zero value, so None cannot be represented.",
1990
+ );
1991
+ }
1992
+
1993
+ static serializeUInt(
1994
+ value: unknown,
1995
+ bits: 8 | 16 | 32 | 64 | 128,
1996
+ context?: TransitionInputContext,
1997
+ ): string {
1998
+ const expectedType = bits <= 32 ? "number" : "bigint";
1999
+ if (bits <= 32) {
2000
+ if (typeof value !== "number" || !Number.isInteger(value)) {
2001
+ throw createInputError("u" + bits + " " + expectedType, value, context);
2002
+ }
2003
+ const max = 2 ** bits - 1;
2004
+ if (value < 0 || value > max) {
2005
+ throw createInputError("u" + bits + " in range 0.." + max, value, context);
2006
+ }
2007
+ return value.toString() + "u" + bits;
2008
+ }
2009
+ if (typeof value !== "bigint") {
2010
+ throw createInputError("u" + bits + " " + expectedType, value, context);
2011
+ }
2012
+ const max = (1n << BigInt(bits)) - 1n;
2013
+ if (value < 0n || value > max) {
2014
+ throw createInputError("u" + bits + " in range 0.." + max.toString(), value, context);
2015
+ }
2016
+ return value.toString() + "u" + bits;
2017
+ }
2018
+
2019
+ static serializeInt(
2020
+ value: unknown,
2021
+ bits: 8 | 16 | 32 | 64 | 128,
2022
+ context?: TransitionInputContext,
2023
+ ): string {
2024
+ if (bits <= 32) {
2025
+ if (typeof value !== "number" || !Number.isInteger(value)) {
2026
+ throw createInputError("i" + bits + " number", value, context);
2027
+ }
2028
+ const min = -(2 ** (bits - 1));
2029
+ const max = 2 ** (bits - 1) - 1;
2030
+ if (value < min || value > max) {
2031
+ throw createInputError("i" + bits + " in range " + min + ".." + max, value, context);
2032
+ }
2033
+ return value.toString() + "i" + bits;
2034
+ }
2035
+ if (typeof value !== "bigint") {
2036
+ throw createInputError("i" + bits + " bigint", value, context);
2037
+ }
2038
+ const min = -(1n << BigInt(bits - 1));
2039
+ const max = (1n << BigInt(bits - 1)) - 1n;
2040
+ if (value < min || value > max) {
2041
+ throw createInputError("i" + bits + " in range " + min.toString() + ".." + max.toString(), value, context);
2042
+ }
2043
+ return value.toString() + "i" + bits;
2044
+ }
2045
+
2046
+ /**
2047
+ * Normalize a non-negative integer "scalar-like" Leo literal (field, group,
2048
+ * scalar) from a bigint, number, or string. Numbers/bigints are formatted
2049
+ * with the type suffix; bare-numeric strings ("12") are suffixed; already
2050
+ * suffixed strings ("12field") pass through unchanged. Visibility-suffixed
2051
+ * strings ("12field.public") are rejected on the input path, matching the
2052
+ * pre-existing per-type serializers. Group literals are limited to integer
2053
+ * forms — coordinate/affine literals are not supported here.
2054
+ */
2055
+ private static serializeScalarLike(
2056
+ value: unknown,
2057
+ suffix: "field" | "group" | "scalar",
2058
+ context?: TransitionInputContext,
2059
+ ): string {
2060
+ const label = suffix.charAt(0).toUpperCase() + suffix.slice(1);
2061
+ const expected = label + " literal like 99" + suffix;
2062
+ if (typeof value === "bigint") {
2063
+ if (value < 0n) {
2064
+ throw createInputError(label + " (non-negative integer)", value, context, "Use Leo." + suffix + "(...).");
2065
+ }
2066
+ return value.toString() + suffix;
2067
+ }
2068
+ if (typeof value === "number") {
2069
+ if (!Number.isInteger(value) || value < 0) {
2070
+ throw createInputError(label + " (non-negative integer)", value, context, "Use Leo." + suffix + "(...).");
2071
+ }
2072
+ if (!Number.isSafeInteger(value)) {
2073
+ throw createInputError(label + " (use bigint or string above 2^53)", value, context, "Use Leo." + suffix + "(...).");
2074
+ }
2075
+ return value.toString() + suffix;
2076
+ }
2077
+ const literal = expectString(value, expected, context, "Use Leo." + suffix + "(...).");
2078
+ if (new RegExp("^[0-9]+" + suffix + "$", "i").test(literal)) {
2079
+ return literal;
2080
+ }
2081
+ if (/^[0-9]+$/.test(literal)) {
2082
+ return literal + suffix;
2083
+ }
2084
+ throw createInputError(expected, value, context, "Use Leo." + suffix + "(...).");
2085
+ }
2086
+
2087
+ static serializeAddress(value: unknown, context?: TransitionInputContext): string {
2088
+ const raw = typeof value === "string"
2089
+ ? value
2090
+ : value && typeof value === "object" && "address" in value
2091
+ ? value.address
2092
+ : value;
2093
+ const address = expectString(raw, "Address", context, "Use Leo.address(...) or pass a named/devnode account.");
2094
+ if (!/^aleo1[0-9a-z]+$/i.test(address)) {
2095
+ throw createInputError("Address", raw, context, "Use Leo.address(...) or pass a named/devnode account.");
2096
+ }
2097
+ return stripVisibility(address);
2098
+ }
2099
+
2100
+ static parseAddress(value: string): LeoAddress {
2101
+ return brand<"Address">(BaseContract.serializeAddress(stripVisibility(value), undefined));
2102
+ }
2103
+
2104
+ static serializeField(value: unknown, context?: TransitionInputContext): string {
2105
+ return BaseContract.serializeScalarLike(value, "field", context);
2106
+ }
2107
+
2108
+ static parseField(value: string): LeoField {
2109
+ return brand<"Field">(BaseContract.serializeField(stripVisibility(value), undefined));
2110
+ }
2111
+
2112
+ static serializeGroup(value: unknown, context?: TransitionInputContext): string {
2113
+ return BaseContract.serializeScalarLike(value, "group", context);
2114
+ }
2115
+
2116
+ static parseGroup(value: string): LeoGroup {
2117
+ return brand<"Group">(BaseContract.serializeGroup(stripVisibility(value), undefined));
2118
+ }
2119
+
2120
+ static serializeScalar(value: unknown, context?: TransitionInputContext): string {
2121
+ return BaseContract.serializeScalarLike(value, "scalar", context);
2122
+ }
2123
+
2124
+ static parseScalar(value: string): LeoScalar {
2125
+ return brand<"Scalar">(BaseContract.serializeScalar(stripVisibility(value), undefined));
2126
+ }
2127
+
2128
+ static serializeIdentifier(value: unknown, context?: TransitionInputContext): string {
2129
+ const trimmed = expectString(value, "Identifier", context, "Use Leo.identifier(...).");
2130
+ if (trimmed.length === 0) {
2131
+ throw createInputError("Identifier", value, context, "Use Leo.identifier(...).");
2132
+ }
2133
+ if (trimmed.startsWith("'") && trimmed.endsWith("'")) {
2134
+ const name = trimmed.slice(1, -1);
2135
+ BaseContract.assertIdentifierName(name, context);
2136
+ return "'" + name + "'";
2137
+ }
2138
+ BaseContract.assertIdentifierName(trimmed, context);
2139
+ return "'" + trimmed + "'";
2140
+ }
2141
+
2142
+ static parseIdentifier(value: string): LeoIdentifier {
2143
+ const trimmed = stripVisibility(value);
2144
+ if (trimmed.startsWith("'") && trimmed.endsWith("'")) {
2145
+ return brand<"Identifier">(trimmed.slice(1, -1));
2146
+ }
2147
+ BaseContract.assertIdentifierName(trimmed, undefined);
2148
+ return brand<"Identifier">(trimmed);
2149
+ }
2150
+
2151
+ static serializeDynamicRecord(value: unknown, context?: TransitionInputContext): string {
2152
+ const literal = expectString(value, "DynamicRecord literal", context, "Use Leo.unsafe.dynamicRecord(...).");
2153
+ if (literal.length === 0) {
2154
+ throw createInputError("DynamicRecord literal", value, context, "Use Leo.unsafe.dynamicRecord(...).");
2155
+ }
2156
+ return literal;
2157
+ }
2158
+
2159
+ static parseDynamicRecord(value: string): LeoDynamicRecord {
2160
+ return brand<"DynamicRecord">(value);
2161
+ }
2162
+
2163
+ static serializePlaintext(value: unknown, context?: TransitionInputContext): string {
2164
+ const literal = expectString(value, "Leo plaintext literal", context, "Use Leo.unsafe.plaintext(...).");
2165
+ if (literal.length === 0) {
2166
+ throw createInputError("Leo plaintext literal", value, context, "Use Leo.unsafe.plaintext(...).");
2167
+ }
2168
+ return literal;
2169
+ }
2170
+
2171
+ static parsePlaintext(value: string): LeoPlaintext {
2172
+ return brand<"Plaintext">(value);
2173
+ }
2174
+
2175
+ private static assertIdentifierName(value: string, context?: TransitionInputContext): void {
2176
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
2177
+ throw createInputError("Identifier matching /^[A-Za-z_][A-Za-z0-9_]*$/", value, context, "Use Leo.identifier(...).");
2178
+ }
2179
+ }
2180
+
2181
+ static parseArray(value: string): string[] {
2182
+ const trimmed = value.trim();
2183
+ const inner = trimmed.startsWith("[") && trimmed.endsWith("]")
2184
+ ? trimmed.slice(1, -1).trim()
2185
+ : trimmed;
2186
+
2187
+ if (inner.length === 0) return [];
2188
+
2189
+ const elements: string[] = [];
2190
+ let depth = 0;
2191
+ let current = "";
2192
+
2193
+ for (let i = 0; i < inner.length; i++) {
2194
+ const ch = inner[i]!;
2195
+ if (ch === "{" || ch === "[") depth++;
2196
+ else if (ch === "}" || ch === "]") depth--;
2197
+
2198
+ if (depth === 0 && ch === ",") {
2199
+ elements.push(current.trim());
2200
+ current = "";
2201
+ } else {
2202
+ current += ch;
2203
+ }
2204
+ }
2205
+ if (current.trim()) {
2206
+ elements.push(current.trim());
2207
+ }
2208
+
2209
+ return elements;
2210
+ }
2211
+
2212
+ /**
2213
+ * Filter the confirmed transaction's transitions[] to the specific
2214
+ * (programId, transitionName) the caller invoked on the ACCEPTED branch,
2215
+ * returning the matched record's rawOutputs and transitionPublicKey.
2216
+ *
2217
+ * Fail-fast on 0 or >1 matches — the caller cannot safely pick the right
2218
+ * outputs without unambiguous identity. Reentrant or recursive transitions
2219
+ * hit this; reach for the raw escape hatch instead.
2220
+ */
2221
+ protected selectAcceptedTransition(
2222
+ transitionName: string,
2223
+ transitions: readonly ConfirmedTransitionRecord[] | undefined,
2224
+ ): { readonly rawOutputs: readonly RawTransitionOutput[]; readonly transitionPublicKey: string } {
2225
+ const list = transitions ?? [];
2226
+ const matches = list.filter(
2227
+ (t) => t.programId === this.programId && t.transitionName === transitionName,
2228
+ );
2229
+ if (matches.length === 0) {
2230
+ throw new TransactionShapeError(
2231
+ "Confirmed transaction did not contain a matching transition for " + this.programId + "/" + transitionName + ". Available: " + list.map((t) => t.programId + "/" + t.transitionName).join(", ") + ".",
2232
+ { programId: this.programId, transition: transitionName },
2233
+ );
2234
+ }
2235
+ if (matches.length > 1) {
2236
+ throw new TransactionShapeError(
2237
+ "Confirmed transaction contained " + matches.length + " transitions matching " + this.programId + "/" + transitionName + ". Cannot pick outputs unambiguously; use raw.execute(...) for reentrant or recursive flows.",
2238
+ { programId: this.programId, transition: transitionName },
2239
+ );
2240
+ }
2241
+ const match = matches[0]!;
2242
+ return { rawOutputs: match.rawOutputs, transitionPublicKey: match.transitionPublicKey };
2243
+ }
2244
+
2245
+ /**
2246
+ * Permissive selector for the REJECTED branch. Aleo converts rejected
2247
+ * executes to fee-only on inclusion, so transitions[] is usually empty —
2248
+ * returns []. If a matching transition entry happens to be present (e.g.
2249
+ * finalizer-failure case), its rawOutputs are surfaced. No tpk plumbing
2250
+ * because rejected outputs aren't decoded by the typed projection.
2251
+ */
2252
+ protected selectRejectedTransitionOutputs(
2253
+ transitionName: string,
2254
+ transitions: readonly ConfirmedTransitionRecord[] | undefined,
2255
+ ): readonly RawTransitionOutput[] {
2256
+ const list = transitions ?? [];
2257
+ const matches = list.filter(
2258
+ (t) => t.programId === this.programId && t.transitionName === transitionName,
2259
+ );
2260
+ return matches.length > 0 ? matches[0]!.rawOutputs : [];
2261
+ }
2262
+
2263
+ /**
2264
+ * Decrypt an Aleo record ciphertext into a typed record. Used by generated
2265
+ * per-record \`decryptXxx\` free functions; can also be invoked directly
2266
+ * for advanced cases (custom deserializers).
2267
+ *
2268
+ * Accepts a polymorphic key — string (auto-detected prefix), {viewKey},
2269
+ * or {privateKey}. Throws RecordDecryptionKeyError on unrecognized shapes
2270
+ * and LocalRecordDecryptionError when the SDK rejects the ciphertext or
2271
+ * view-key combo (wrong account, malformed ciphertext, etc.).
2272
+ */
2273
+ static async decryptRecord<T>(
2274
+ ciphertext: string,
2275
+ key: RecordDecryptionKey,
2276
+ deserialize: (plaintext: string) => T,
2277
+ ): Promise<T> {
2278
+ // Shape errors (bad object/string) are RecordDecryptionKeyError — caller
2279
+ // input bug, surface as-is. SDK-level errors (bad APrivateKey1 string
2280
+ // failing deriveViewKey, bad ciphertext, mismatched view key) are
2281
+ // re-wrapped as LocalRecordDecryptionError so test assertions can match
2282
+ // a single typechain-layer error class.
2283
+ try {
2284
+ const viewKey = await BaseContract.normalizeRecordDecryptionKey(key);
2285
+ const plaintext = await decryptRecordCiphertext(ciphertext, viewKey);
2286
+ return deserialize(plaintext);
2287
+ } catch (cause: unknown) {
2288
+ // RecordDecryptionKeyError and other typechain errors pass through.
2289
+ if (cause instanceof LionDenTypechainError) throw cause;
2290
+ const isNetworkErr =
2291
+ cause instanceof NetworkRecordDecryptionError ||
2292
+ (cause && typeof cause === "object" && (cause as { kind?: unknown }).kind === "NetworkRecordDecryptionError");
2293
+ if (isNetworkErr) {
2294
+ throw new LocalRecordDecryptionError(
2295
+ "Failed to decrypt record ciphertext. The view key may not match the record's owner, or the ciphertext is malformed. Cause: " + errorMessage(cause),
2296
+ { cause },
2297
+ );
2298
+ }
2299
+ throw cause;
2300
+ }
2301
+ }
2302
+
2303
+ private static async normalizeRecordDecryptionKey(key: RecordDecryptionKey): Promise<string> {
2304
+ if (typeof key === "string") {
2305
+ const trimmed = key.trim();
2306
+ if (trimmed.startsWith("AViewKey1")) return trimmed;
2307
+ if (trimmed.startsWith("APrivateKey1")) return deriveViewKey(trimmed);
2308
+ throw new RecordDecryptionKeyError(
2309
+ "Decryption key string must start with \"APrivateKey1\" or \"AViewKey1\". Received prefix " + JSON.stringify(trimmed.slice(0, 16)) + ". To pass an opaque string, wrap in { viewKey } or { privateKey }.",
2310
+ );
2311
+ }
2312
+ if (key && typeof key === "object") {
2313
+ const viewKey = (key as { readonly viewKey?: unknown }).viewKey;
2314
+ if (typeof viewKey === "string" && viewKey.length > 0) {
2315
+ if (!viewKey.startsWith("AViewKey1")) {
2316
+ throw new RecordDecryptionKeyError(
2317
+ "{ viewKey } must start with \"AViewKey1\". Received prefix " + JSON.stringify(viewKey.slice(0, 16)) + ".",
2318
+ );
2319
+ }
2320
+ return viewKey;
2321
+ }
2322
+ const privateKey = (key as { readonly privateKey?: unknown }).privateKey;
2323
+ if (typeof privateKey === "string" && privateKey.length > 0) {
2324
+ if (!privateKey.startsWith("APrivateKey1")) {
2325
+ throw new RecordDecryptionKeyError(
2326
+ "{ privateKey } must start with \"APrivateKey1\". Received prefix " + JSON.stringify(privateKey.slice(0, 16)) + ".",
2327
+ );
2328
+ }
2329
+ return deriveViewKey(privateKey);
2330
+ }
2331
+ }
2332
+ throw new RecordDecryptionKeyError(
2333
+ "Decryption key must be a non-empty AViewKey1/APrivateKey1 string, or an object with a \`viewKey\` or \`privateKey\` field. Received " + (key === null ? "null" : typeof key) + ".",
2334
+ );
2335
+ }
2336
+
2337
+ /**
2338
+ * Compose a Leo \`dyn record\` literal from a JS object and a per-field
2339
+ * schema. Validates that schema and value have matching keys; dispatches
2340
+ * each field through the existing typed serializer; appends the visibility
2341
+ * suffix; brands the result. Synchronous — no SDK call.
2342
+ */
2343
+ static encodeDynamicRecord(
2344
+ value: Record<string, unknown>,
2345
+ schema: Record<string, LeoFieldSchemaEntry>,
2346
+ ): string {
2347
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
2348
+ throw new TransitionInputError(
2349
+ "Leo.dynamicRecord expected an object value. Received " + (value === null ? "null" : Array.isArray(value) ? "array" : typeof value) + ".",
2350
+ );
2351
+ }
2352
+ if (typeof schema !== "object" || schema === null || Array.isArray(schema)) {
2353
+ throw new TransitionInputError(
2354
+ "Leo.dynamicRecord expected an object schema mapping field name to \"<type>.<visibility>\".",
2355
+ );
2356
+ }
2357
+ const valueKeys = Object.keys(value);
2358
+ const schemaKeys = Object.keys(schema);
2359
+ const missing = schemaKeys.filter((k) => !valueKeys.includes(k));
2360
+ const extra = valueKeys.filter((k) => !schemaKeys.includes(k));
2361
+ if (missing.length > 0 || extra.length > 0) {
2362
+ throw new TransitionInputError(
2363
+ "Leo.dynamicRecord value and schema keys must match exactly. Missing in value: [" + missing.join(", ") + "]. Extra in value: [" + extra.join(", ") + "].",
2364
+ );
2365
+ }
2366
+ const parts: string[] = [];
2367
+ for (const fieldName of schemaKeys) {
2368
+ const entry = schema[fieldName]!;
2369
+ const split = entry.lastIndexOf(".");
2370
+ if (split <= 0) {
2371
+ throw new TransitionInputError(
2372
+ "Leo.dynamicRecord schema entry for \"" + fieldName + "\" must be \"<type>.<visibility>\". Received " + JSON.stringify(entry) + ".",
2373
+ );
2374
+ }
2375
+ const ty = entry.slice(0, split);
2376
+ const viz = entry.slice(split + 1);
2377
+ if (viz !== "public" && viz !== "private") {
2378
+ throw new TransitionInputError(
2379
+ "Leo.dynamicRecord schema entry for \"" + fieldName + "\" has invalid visibility \"" + viz + "\". Expected \"public\" or \"private\".",
2380
+ );
2381
+ }
2382
+ const ctx: TransitionInputContext = { path: fieldName };
2383
+ const serialized = BaseContract.serializeDynamicRecordField(value[fieldName], ty, ctx);
2384
+ parts.push(fieldName + ": " + serialized + "." + viz);
2385
+ }
2386
+ return "{ " + parts.join(", ") + " }";
2387
+ }
2388
+
2389
+ private static serializeDynamicRecordField(
2390
+ value: unknown,
2391
+ leoType: string,
2392
+ ctx: TransitionInputContext,
2393
+ ): string {
2394
+ switch (leoType) {
2395
+ case "address":
2396
+ return BaseContract.serializeAddress(value, ctx);
2397
+ case "boolean":
2398
+ return BaseContract.serializeBoolean(value, ctx);
2399
+ case "field":
2400
+ return BaseContract.serializeField(value, ctx);
2401
+ case "group":
2402
+ return BaseContract.serializeGroup(value, ctx);
2403
+ case "scalar":
2404
+ return BaseContract.serializeScalar(value, ctx);
2405
+ case "u8":
2406
+ case "u16":
2407
+ case "u32":
2408
+ case "u64":
2409
+ case "u128": {
2410
+ const bits = parseInt(leoType.slice(1), 10) as 8 | 16 | 32 | 64 | 128;
2411
+ return BaseContract.serializeUInt(value, bits, ctx);
2412
+ }
2413
+ case "i8":
2414
+ case "i16":
2415
+ case "i32":
2416
+ case "i64":
2417
+ case "i128": {
2418
+ const bits = parseInt(leoType.slice(1), 10) as 8 | 16 | 32 | 64 | 128;
2419
+ return BaseContract.serializeInt(value, bits, ctx);
2420
+ }
2421
+ default:
2422
+ throw new TransitionInputError(
2423
+ "Leo.dynamicRecord schema entry uses unsupported type \"" + leoType + "\". Supported: address, boolean, field, group, scalar, u8/u16/u32/u64/u128, i8/i16/i32/i64/i128.",
2424
+ );
2425
+ }
2426
+ }
2427
+
2428
+ static parseStruct(value: string): Record<string, string> {
2429
+ const trimmed = value.trim();
2430
+ const inner = trimmed.startsWith("{") && trimmed.endsWith("}")
2431
+ ? trimmed.slice(1, -1).trim()
2432
+ : trimmed;
2433
+
2434
+ const result: Record<string, string> = {};
2435
+ let depth = 0;
2436
+ let current = "";
2437
+ let key = "";
2438
+
2439
+ for (let i = 0; i < inner.length; i++) {
2440
+ const ch = inner[i]!;
2441
+ if (ch === "{" || ch === "[") depth++;
2442
+ else if (ch === "}" || ch === "]") depth--;
2443
+
2444
+ if (depth === 0 && ch === ":" && !key) {
2445
+ key = current.trim();
2446
+ current = "";
2447
+ } else if (depth === 0 && ch === ",") {
2448
+ if (key) {
2449
+ result[key] = current.trim();
2450
+ key = "";
2451
+ }
2452
+ current = "";
2453
+ } else {
2454
+ current += ch;
2455
+ }
2456
+ }
2457
+ if (key) {
2458
+ result[key] = current.trim();
2459
+ }
2460
+
2461
+ return result;
2462
+ }
2463
+ }
2464
+
2465
+ function errorMessage(error: unknown): string {
2466
+ return error instanceof Error ? error.message : String(error);
2467
+ }
2468
+
2469
+ function isNetworkConfirmationTimeoutError(error: unknown): boolean {
2470
+ if (!error || typeof error !== "object") return false;
2471
+ const candidate = error as { readonly kind?: unknown; readonly name?: unknown };
2472
+ return candidate.kind === "NetworkConfirmationTimeoutError" ||
2473
+ candidate.name === "NetworkConfirmationTimeoutError";
2474
+ }
2475
+ `
2476
+ // String.raw preserves backslash sequences as literals, so the template
2477
+ // literal type for LeoFieldSchemaEntry cannot live inline (it would
2478
+ // require unescaped backticks and ${} that close the outer template).
2479
+ // Substitute the marker post-construction with a single-quoted literal
2480
+ // that JS does NOT process as a template substitution.
2481
+ .replace("__LEO_FIELD_SCHEMA_ENTRY__", "`${LeoPrimitiveType}.${LeoVisibility}`");
2482
+ //# sourceMappingURL=contract-wrapper.js.map