@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.
- package/LICENSE +201 -0
- package/README.md +23 -0
- package/dist/abi-hash.d.ts +15 -0
- package/dist/abi-hash.d.ts.map +1 -0
- package/dist/abi-hash.js +75 -0
- package/dist/abi-hash.js.map +1 -0
- package/dist/abi-parser.d.ts +38 -0
- package/dist/abi-parser.d.ts.map +1 -0
- package/dist/abi-parser.js +513 -0
- package/dist/abi-parser.js.map +1 -0
- package/dist/abi-types.d.ts +111 -0
- package/dist/abi-types.d.ts.map +1 -0
- package/dist/abi-types.js +5 -0
- package/dist/abi-types.js.map +1 -0
- package/dist/cache.d.ts +27 -0
- package/dist/cache.d.ts.map +1 -0
- package/dist/cache.js +74 -0
- package/dist/cache.js.map +1 -0
- package/dist/codegen/codegen-error.d.ts +10 -0
- package/dist/codegen/codegen-error.d.ts.map +1 -0
- package/dist/codegen/codegen-error.js +14 -0
- package/dist/codegen/codegen-error.js.map +1 -0
- package/dist/codegen/contract-wrapper.d.ts +6 -0
- package/dist/codegen/contract-wrapper.d.ts.map +1 -0
- package/dist/codegen/contract-wrapper.js +2482 -0
- package/dist/codegen/contract-wrapper.js.map +1 -0
- package/dist/codegen/type-mapper.d.ts +46 -0
- package/dist/codegen/type-mapper.d.ts.map +1 -0
- package/dist/codegen/type-mapper.js +132 -0
- package/dist/codegen/type-mapper.js.map +1 -0
- package/dist/codegen/typescript-generator.d.ts +65 -0
- package/dist/codegen/typescript-generator.d.ts.map +1 -0
- package/dist/codegen/typescript-generator.js +2076 -0
- package/dist/codegen/typescript-generator.js.map +1 -0
- package/dist/compiler.d.ts +43 -0
- package/dist/compiler.d.ts.map +1 -0
- package/dist/compiler.js +532 -0
- package/dist/compiler.js.map +1 -0
- package/dist/dependency-resolver.d.ts +33 -0
- package/dist/dependency-resolver.d.ts.map +1 -0
- package/dist/dependency-resolver.js +142 -0
- package/dist/dependency-resolver.js.map +1 -0
- package/dist/import-parser.d.ts +17 -0
- package/dist/import-parser.d.ts.map +1 -0
- package/dist/import-parser.js +46 -0
- package/dist/import-parser.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -0
- package/dist/package-materializer.d.ts +29 -0
- package/dist/package-materializer.d.ts.map +1 -0
- package/dist/package-materializer.js +160 -0
- package/dist/package-materializer.js.map +1 -0
- package/dist/source-discovery.d.ts +24 -0
- package/dist/source-discovery.d.ts.map +1 -0
- package/dist/source-discovery.js +131 -0
- package/dist/source-discovery.js.map +1 -0
- package/dist/source-scrubber.d.ts +22 -0
- package/dist/source-scrubber.d.ts.map +1 -0
- package/dist/source-scrubber.js +71 -0
- package/dist/source-scrubber.js.map +1 -0
- package/dist/types.d.ts +72 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +8 -0
- package/dist/types.js.map +1 -0
- package/package.json +34 -0
|
@@ -0,0 +1,2076 @@
|
|
|
1
|
+
import { CodegenError } from "./codegen-error.js";
|
|
2
|
+
import { CONTRACT_WRAPPER_TEMPLATE } from "./contract-wrapper.js";
|
|
3
|
+
import { disambiguateInputName, isBigIntType, pathToTsName, recordRefName, structRefName, } from "./type-mapper.js";
|
|
4
|
+
const SUPPORTED_DYNAMIC_RECORD_PRIMITIVES = new Set([
|
|
5
|
+
"address",
|
|
6
|
+
"boolean",
|
|
7
|
+
"field",
|
|
8
|
+
"group",
|
|
9
|
+
"scalar",
|
|
10
|
+
"u8",
|
|
11
|
+
"u16",
|
|
12
|
+
"u32",
|
|
13
|
+
"u64",
|
|
14
|
+
"u128",
|
|
15
|
+
"i8",
|
|
16
|
+
"i16",
|
|
17
|
+
"i32",
|
|
18
|
+
"i64",
|
|
19
|
+
"i128",
|
|
20
|
+
]);
|
|
21
|
+
/**
|
|
22
|
+
* Generate TypeScript bindings from a ProgramABI.
|
|
23
|
+
* Produces a single .ts file with:
|
|
24
|
+
* - Struct/record interfaces
|
|
25
|
+
* - Storage variable interface
|
|
26
|
+
* - Serializer/deserializer functions
|
|
27
|
+
* - Typed contract wrapper class
|
|
28
|
+
*/
|
|
29
|
+
export function generateBindings(abi, allAbis = [abi], options = {}) {
|
|
30
|
+
const lines = [];
|
|
31
|
+
const helpers = (options.dynamicRecords ?? []).filter((helper) => helper.sourceProgram === abi.program);
|
|
32
|
+
const includeLeoValueImport = helpers.length > 0;
|
|
33
|
+
const className = resolveContractClassName(abi, { includeLeoValueImport });
|
|
34
|
+
// Helper names are module-level `export const`s; reserve them for generated
|
|
35
|
+
// input aliases so they do not redeclare a helper value binding.
|
|
36
|
+
const ctx = createGenerationContext(abi, allAbis, helpers.map((helper) => helper.helperName), includeLeoValueImport);
|
|
37
|
+
assertCodegenSupportedTypes(abi);
|
|
38
|
+
assertNoExecutableConstParameters(abi);
|
|
39
|
+
assertNoReservedLocalTypeNames(abi, className);
|
|
40
|
+
assertNoReservedContractMembers(abi);
|
|
41
|
+
assertNoReservedHelperNames(abi, className, includeLeoValueImport, helpers, ctx.externalInfoByKey.values());
|
|
42
|
+
const hasExternalRefs = ctx.externalStructRefs.size + ctx.externalRecordRefs.size > 0;
|
|
43
|
+
lines.push("// Auto-generated by @lionden/leo-compiler — do not edit");
|
|
44
|
+
lines.push(`// Program: ${abi.program}`);
|
|
45
|
+
lines.push("");
|
|
46
|
+
lines.push(baseContractImport(includeLeoValueImport, hasExternalRefs ? ctx.widenInputAlias : null));
|
|
47
|
+
lines.push(...generateExternalImports(ctx));
|
|
48
|
+
lines.push("");
|
|
49
|
+
for (const struct of abi.structs) {
|
|
50
|
+
lines.push(...generateStructInterface(struct, ctx));
|
|
51
|
+
lines.push("");
|
|
52
|
+
lines.push(...generateStructInputInterface(struct, ctx));
|
|
53
|
+
lines.push("");
|
|
54
|
+
}
|
|
55
|
+
for (const record of abi.records) {
|
|
56
|
+
lines.push(...generateRecordInterface(record, ctx));
|
|
57
|
+
lines.push("");
|
|
58
|
+
lines.push(...generateRecordInputInterface(record, ctx));
|
|
59
|
+
lines.push("");
|
|
60
|
+
}
|
|
61
|
+
if (abi.storage_variables.length > 0) {
|
|
62
|
+
lines.push(...generateStorageInterface(className, abi.storage_variables, ctx));
|
|
63
|
+
lines.push("");
|
|
64
|
+
}
|
|
65
|
+
if (abi.structs.length > 0 || abi.records.length > 0) {
|
|
66
|
+
lines.push("// ---------------------------------------------------------------------------");
|
|
67
|
+
lines.push("// Serialization / deserialization helpers");
|
|
68
|
+
lines.push("// ---------------------------------------------------------------------------");
|
|
69
|
+
lines.push("");
|
|
70
|
+
for (const struct of abi.structs) {
|
|
71
|
+
lines.push(...generateStructSerializer(struct, ctx));
|
|
72
|
+
lines.push("");
|
|
73
|
+
lines.push(...generateStructDeserializer(struct, ctx));
|
|
74
|
+
lines.push("");
|
|
75
|
+
}
|
|
76
|
+
for (const record of abi.records) {
|
|
77
|
+
lines.push(...generateRecordSerializer(record, ctx));
|
|
78
|
+
lines.push("");
|
|
79
|
+
lines.push(...generateRecordDeserializer(record, ctx));
|
|
80
|
+
lines.push("");
|
|
81
|
+
lines.push(...generateRecordDecryptor(record));
|
|
82
|
+
lines.push("");
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (helpers.length > 0) {
|
|
86
|
+
lines.push("// ---------------------------------------------------------------------------");
|
|
87
|
+
lines.push("// Interface conversion helpers");
|
|
88
|
+
lines.push("// ---------------------------------------------------------------------------");
|
|
89
|
+
lines.push("");
|
|
90
|
+
for (const helper of helpers) {
|
|
91
|
+
lines.push(...generateDynamicRecordHelper(helper, abi, ctx));
|
|
92
|
+
lines.push("");
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
lines.push("// ---------------------------------------------------------------------------");
|
|
96
|
+
lines.push(`// ${className} contract wrapper`);
|
|
97
|
+
lines.push("// ---------------------------------------------------------------------------");
|
|
98
|
+
lines.push("");
|
|
99
|
+
lines.push(...generateContractClass(abi, className, ctx));
|
|
100
|
+
return lines.join("\n") + "\n";
|
|
101
|
+
}
|
|
102
|
+
function assertNoExecutableConstParameters(abi) {
|
|
103
|
+
for (const transition of abi.transitions) {
|
|
104
|
+
if (transition.const_parameters && transition.const_parameters.length > 0) {
|
|
105
|
+
throw new CodegenError(`Code generation for ${abi.program}/${transition.name} is unsupported: ` +
|
|
106
|
+
"executable functions with const_parameters are not yet supported.", {
|
|
107
|
+
programId: abi.program,
|
|
108
|
+
phase: "generate",
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function assertCodegenSupportedTypes(abi) {
|
|
114
|
+
// Keep this allowlist in sync with the primitive branches that actually emit
|
|
115
|
+
// bindings and serializer/parser calls below. The validation pass exists so
|
|
116
|
+
// those lower-level helpers never fall through to unsafe generic codegen.
|
|
117
|
+
const visitPrimitive = (prim, abiPath) => {
|
|
118
|
+
if (typeof prim === "string") {
|
|
119
|
+
switch (prim) {
|
|
120
|
+
case "Address":
|
|
121
|
+
case "Boolean":
|
|
122
|
+
case "Field":
|
|
123
|
+
case "Group":
|
|
124
|
+
case "Identifier":
|
|
125
|
+
case "Scalar":
|
|
126
|
+
return;
|
|
127
|
+
default:
|
|
128
|
+
throwUnsupportedPrimitive(abi.program, abiPath, prim);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (typeof prim === "object" && prim !== null) {
|
|
132
|
+
if ("UInt" in prim) {
|
|
133
|
+
switch (prim.UInt) {
|
|
134
|
+
case "U8":
|
|
135
|
+
case "U16":
|
|
136
|
+
case "U32":
|
|
137
|
+
case "U64":
|
|
138
|
+
case "U128":
|
|
139
|
+
return;
|
|
140
|
+
default:
|
|
141
|
+
throwUnsupportedPrimitive(abi.program, abiPath, `UInt(${String(prim.UInt)})`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if ("Int" in prim) {
|
|
145
|
+
switch (prim.Int) {
|
|
146
|
+
case "I8":
|
|
147
|
+
case "I16":
|
|
148
|
+
case "I32":
|
|
149
|
+
case "I64":
|
|
150
|
+
case "I128":
|
|
151
|
+
return;
|
|
152
|
+
default:
|
|
153
|
+
throwUnsupportedPrimitive(abi.program, abiPath, `Int(${String(prim.Int)})`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
throwUnsupportedPrimitive(abi.program, abiPath, JSON.stringify(prim));
|
|
158
|
+
};
|
|
159
|
+
const visitPlaintext = (ty, abiPath) => {
|
|
160
|
+
if ("Primitive" in ty) {
|
|
161
|
+
visitPrimitive(ty.Primitive, `${abiPath}.Primitive`);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
// Struct references are validated at their declaration site in the owning
|
|
165
|
+
// program's generateBindings() call; unresolved external refs intentionally
|
|
166
|
+
// remain dynamic/plaintext fallback surfaces.
|
|
167
|
+
if ("Struct" in ty)
|
|
168
|
+
return;
|
|
169
|
+
if ("Array" in ty) {
|
|
170
|
+
visitPlaintext(ty.Array[0], `${abiPath}.Array[0]`);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if ("Optional" in ty) {
|
|
174
|
+
visitPlaintext(ty.Optional, `${abiPath}.Optional`);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
const visitAleo = (ty, abiPath) => {
|
|
178
|
+
if (ty === "DynamicRecord")
|
|
179
|
+
return;
|
|
180
|
+
if ("Plaintext" in ty) {
|
|
181
|
+
visitPlaintext(ty.Plaintext, `${abiPath}.Plaintext`);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
// Record references follow the same declaration-site validation contract
|
|
185
|
+
// as struct references.
|
|
186
|
+
if ("Record" in ty)
|
|
187
|
+
return;
|
|
188
|
+
if ("Future" in ty)
|
|
189
|
+
return;
|
|
190
|
+
};
|
|
191
|
+
const visitStorage = (ty, abiPath) => {
|
|
192
|
+
if ("Plaintext" in ty) {
|
|
193
|
+
visitPlaintext(ty.Plaintext, `${abiPath}.Plaintext`);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if ("Vector" in ty) {
|
|
197
|
+
visitStorage(ty.Vector, `${abiPath}.Vector`);
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
abi.structs.forEach((struct, structIndex) => {
|
|
201
|
+
struct.fields.forEach((field, fieldIndex) => {
|
|
202
|
+
visitPlaintext(field.ty, `structs[${structIndex}].fields[${fieldIndex}].ty`);
|
|
203
|
+
});
|
|
204
|
+
});
|
|
205
|
+
abi.records.forEach((record, recordIndex) => {
|
|
206
|
+
record.fields.forEach((field, fieldIndex) => {
|
|
207
|
+
visitPlaintext(field.ty, `records[${recordIndex}].fields[${fieldIndex}].ty`);
|
|
208
|
+
});
|
|
209
|
+
});
|
|
210
|
+
abi.mappings.forEach((mapping, mappingIndex) => {
|
|
211
|
+
visitPlaintext(mapping.key, `mappings[${mappingIndex}].key`);
|
|
212
|
+
visitPlaintext(mapping.value, `mappings[${mappingIndex}].value`);
|
|
213
|
+
});
|
|
214
|
+
abi.storage_variables.forEach((variable, variableIndex) => {
|
|
215
|
+
visitStorage(variable.ty, `storage_variables[${variableIndex}].ty`);
|
|
216
|
+
});
|
|
217
|
+
abi.transitions.forEach((transition, transitionIndex) => {
|
|
218
|
+
transition.inputs.forEach((input, inputIndex) => {
|
|
219
|
+
visitAleo(input.ty, `transitions[${transitionIndex}].inputs[${inputIndex}].ty`);
|
|
220
|
+
});
|
|
221
|
+
transition.outputs.forEach((output, outputIndex) => {
|
|
222
|
+
visitAleo(output.ty, `transitions[${transitionIndex}].outputs[${outputIndex}].ty`);
|
|
223
|
+
});
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
function throwUnsupportedPrimitive(programId, abiPath, primitive) {
|
|
227
|
+
throw new CodegenError(`Code generation for program ${programId} is unsupported at ABI path ${abiPath}: ` +
|
|
228
|
+
`Primitive::${primitive} is not supported by generated bindings yet.`, {
|
|
229
|
+
programId,
|
|
230
|
+
abiPath,
|
|
231
|
+
primitive,
|
|
232
|
+
phase: "generate",
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Generate the BaseContract file content.
|
|
237
|
+
*/
|
|
238
|
+
export function generateBaseContract() {
|
|
239
|
+
return CONTRACT_WRAPPER_TEMPLATE;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Type-level bindings `baseContractImport` always imports from
|
|
243
|
+
* `./BaseContract.js`, in the historically-emitted alphabetical order. Single
|
|
244
|
+
* source of truth shared by `baseContractImport` (which prefixes each with
|
|
245
|
+
* `type `) and `RESERVED_BASE_CONTRACT_TYPE_IMPORT_NAMES`, so the emitted import
|
|
246
|
+
* list and the collision-guard list cannot drift apart.
|
|
247
|
+
*
|
|
248
|
+
* Excludes `BaseContract` (imported as a value, reserved separately) and
|
|
249
|
+
* `WidenInput` (conditional + alias-aware, deliberately not reserved).
|
|
250
|
+
*/
|
|
251
|
+
const BASE_CONTRACT_TYPE_IMPORT_NAMES = [
|
|
252
|
+
"AcceptedTransition",
|
|
253
|
+
"AddressInput",
|
|
254
|
+
"BaseContractOptions",
|
|
255
|
+
"CapturedRecord",
|
|
256
|
+
"ConfirmedTransitionRecord",
|
|
257
|
+
"DecryptionKey",
|
|
258
|
+
"DynamicRecordInput",
|
|
259
|
+
"EncryptedRecord",
|
|
260
|
+
"EncryptedValue",
|
|
261
|
+
"FieldInput",
|
|
262
|
+
"GroupInput",
|
|
263
|
+
"IdentifierInput",
|
|
264
|
+
"IdOnlyDynamicRecordHandle",
|
|
265
|
+
"IdOnlyExternalRecordHandle",
|
|
266
|
+
"IdOnlyRecordSource",
|
|
267
|
+
"LeoAddress",
|
|
268
|
+
"LeoDynamicRecord",
|
|
269
|
+
"LeoField",
|
|
270
|
+
"LeoGroup",
|
|
271
|
+
"LeoIdentifier",
|
|
272
|
+
"LeoPlaintext",
|
|
273
|
+
"LeoScalar",
|
|
274
|
+
"LocalExecutionOptions",
|
|
275
|
+
"LocalTransitionError",
|
|
276
|
+
"OnChainExecutionOptions",
|
|
277
|
+
"PlaintextInput",
|
|
278
|
+
"RawTransitionOutput",
|
|
279
|
+
"RecordDecryptionKey",
|
|
280
|
+
"RecordOutputMatcher",
|
|
281
|
+
"RejectedTransition",
|
|
282
|
+
"ScalarInput",
|
|
283
|
+
"SettledTransition",
|
|
284
|
+
"SubmittedTransition",
|
|
285
|
+
"TransitionInputContext",
|
|
286
|
+
];
|
|
287
|
+
/**
|
|
288
|
+
* Build the fixed `import { … } from "./BaseContract.js"` line. `Leo` is added
|
|
289
|
+
* only when the module emits dynamic-record helpers; `WidenInput` only when the
|
|
290
|
+
* module has external struct/record refs (which alias to `WidenInput<…>`), and
|
|
291
|
+
* under a collision-safe local name (`widenImport`, normally `"WidenInput"`).
|
|
292
|
+
* The value names come from `baseContractValueImportNames` (the single source
|
|
293
|
+
* shared with the collision guard); the type list is alphabetical, matching the
|
|
294
|
+
* historically-emitted order so modules without those features produce
|
|
295
|
+
* byte-identical imports.
|
|
296
|
+
*/
|
|
297
|
+
function baseContractImport(includeLeo, widenImport) {
|
|
298
|
+
const names = [
|
|
299
|
+
...baseContractValueImportNames(includeLeo),
|
|
300
|
+
...BASE_CONTRACT_TYPE_IMPORT_NAMES.map((name) => `type ${name}`),
|
|
301
|
+
...(widenImport === null
|
|
302
|
+
? []
|
|
303
|
+
: [widenImport === "WidenInput" ? "type WidenInput" : `type WidenInput as ${widenImport}`]),
|
|
304
|
+
];
|
|
305
|
+
return `import { ${names.join(", ")} } from "./BaseContract.js";`;
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Bare value-binding names introduced by `baseContractImport`, in emitted order:
|
|
309
|
+
* `BaseContract`, then `Leo` (only when the module emits dynamic-record helpers),
|
|
310
|
+
* then dynamic-record helper support, then `createRecordOutputMatcher`. Single
|
|
311
|
+
* source of truth shared by `baseContractImport` (the emitted import line) and
|
|
312
|
+
* the collision guard (`reservedBaseContractImportNames` /
|
|
313
|
+
* `assertNoReservedHelperNames`), so the emitted value imports and the reserved
|
|
314
|
+
* set cannot drift apart — the same single-source treatment the type list gets
|
|
315
|
+
* via `BASE_CONTRACT_TYPE_IMPORT_NAMES`.
|
|
316
|
+
*
|
|
317
|
+
* A generated contract class or its `create${class}` factory must avoid all of
|
|
318
|
+
* these; local interfaces can still coexist with the value-only imports.
|
|
319
|
+
*/
|
|
320
|
+
function baseContractValueImportNames(includeLeo) {
|
|
321
|
+
return [
|
|
322
|
+
"BaseContract",
|
|
323
|
+
...(includeLeo ? ["Leo", "bindDynamicRecordHelperProgram"] : []),
|
|
324
|
+
"createRecordOutputMatcher",
|
|
325
|
+
];
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Bare type-binding names introduced by `baseContractImport`. A local
|
|
329
|
+
* struct/record interface whose name equals one of these collides with the
|
|
330
|
+
* import (TS2440 / TS2300). Keep in sync with `baseContractImport`.
|
|
331
|
+
*
|
|
332
|
+
* `WidenInput` is deliberately excluded: it is the one fixed import that is
|
|
333
|
+
* already alias-aware (`widenInputAlias` re-imports it as `WidenInput_` when a
|
|
334
|
+
* local declaration shadows it), so a local `WidenInput` is handled, not
|
|
335
|
+
* rejected.
|
|
336
|
+
*/
|
|
337
|
+
const RESERVED_BASE_CONTRACT_TYPE_IMPORT_NAMES = [
|
|
338
|
+
// `BaseContract` is imported as a value but is also usable as a type (a local
|
|
339
|
+
// `interface BaseContract` collides with it), so reserve it here too.
|
|
340
|
+
"BaseContract",
|
|
341
|
+
...BASE_CONTRACT_TYPE_IMPORT_NAMES,
|
|
342
|
+
];
|
|
343
|
+
function reservedBaseContractImportNames(includeLeoValueImport) {
|
|
344
|
+
return [
|
|
345
|
+
...new Set([
|
|
346
|
+
...baseContractValueImportNames(includeLeoValueImport),
|
|
347
|
+
...RESERVED_BASE_CONTRACT_TYPE_IMPORT_NAMES,
|
|
348
|
+
]),
|
|
349
|
+
];
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Instance members (public + protected + private) of the `BaseContract` class
|
|
353
|
+
* in contract-wrapper.ts. A transition whose generated `readonly ${name}`
|
|
354
|
+
* accessor equals one of these redeclares an inherited member (TS2416/2425),
|
|
355
|
+
* and several are also called by generated transition bodies via `this.${name}`.
|
|
356
|
+
* The `mappings`/`storage` containers are reserved separately (only when the
|
|
357
|
+
* program actually emits them). Kept in sync with the BaseContract class by the
|
|
358
|
+
* "stays in sync with BaseContract instance members" test in
|
|
359
|
+
* typescript-generator.test.ts, which derives the member set from the emitted
|
|
360
|
+
* class source and asserts every member is rejected here.
|
|
361
|
+
*/
|
|
362
|
+
const RESERVED_CONTRACT_INSTANCE_MEMBERS = [
|
|
363
|
+
// the generated class always emits `constructor(options?)`, so a transition
|
|
364
|
+
// named `constructor` would redeclare it
|
|
365
|
+
"constructor",
|
|
366
|
+
// properties
|
|
367
|
+
"sourceProgramId",
|
|
368
|
+
"programId",
|
|
369
|
+
"instanceImports",
|
|
370
|
+
"lre",
|
|
371
|
+
"signer",
|
|
372
|
+
// public methods
|
|
373
|
+
"connect",
|
|
374
|
+
"address",
|
|
375
|
+
"withSigner",
|
|
376
|
+
// protected / private methods
|
|
377
|
+
"inputContext",
|
|
378
|
+
"getLre",
|
|
379
|
+
"getNetwork",
|
|
380
|
+
"executeLocal",
|
|
381
|
+
"expectLocalFailure",
|
|
382
|
+
"submitTransition",
|
|
383
|
+
"settleTransition",
|
|
384
|
+
"expectAccepted",
|
|
385
|
+
"expectRejected",
|
|
386
|
+
"settleTyped",
|
|
387
|
+
"expectAcceptedTyped",
|
|
388
|
+
"runProjector",
|
|
389
|
+
"beginTransitionLogBlock",
|
|
390
|
+
"logTransitionStart",
|
|
391
|
+
"logTransitionDone",
|
|
392
|
+
"formatTransitionDetails",
|
|
393
|
+
"formatTransitionCall",
|
|
394
|
+
"formatSignerSuffix",
|
|
395
|
+
"outputAt",
|
|
396
|
+
"executeRaw",
|
|
397
|
+
"buildEffectiveOptions",
|
|
398
|
+
"queryMapping",
|
|
399
|
+
"mappingContains",
|
|
400
|
+
"requireMappingRaw",
|
|
401
|
+
"queryStorage",
|
|
402
|
+
"requireStorageRaw",
|
|
403
|
+
"queryStorageVectorLength",
|
|
404
|
+
"queryStorageVector",
|
|
405
|
+
"requireStorageVectorRaw",
|
|
406
|
+
"queryStorageVectorAll",
|
|
407
|
+
"selectAcceptedTransition",
|
|
408
|
+
"selectRejectedTransitionOutputs",
|
|
409
|
+
];
|
|
410
|
+
/**
|
|
411
|
+
* A local struct/record whose generated interface name equals a fixed
|
|
412
|
+
* BaseContract import (e.g. `LeoField`, `BaseContract`) collides with that
|
|
413
|
+
* import (TS2440). Interface names mirror the Leo declaration and can't be
|
|
414
|
+
* silently renamed like the contract class, so fail with a clear message.
|
|
415
|
+
*/
|
|
416
|
+
function assertNoReservedLocalTypeNames(abi, className) {
|
|
417
|
+
const reserved = new Set(RESERVED_BASE_CONTRACT_TYPE_IMPORT_NAMES);
|
|
418
|
+
const check = (kind, path) => {
|
|
419
|
+
const name = pathToTsName(path);
|
|
420
|
+
if (reserved.has(name)) {
|
|
421
|
+
throw new CodegenError(`Program ${abi.program} declares a ${kind} '${name}', whose generated interface collides with the reserved binding '${name}' imported from BaseContract. Rename the ${kind}.`, { programId: abi.program, typeName: name, kind, phase: "generate" });
|
|
422
|
+
}
|
|
423
|
+
const storageInterfaceName = `${className}Storage`;
|
|
424
|
+
if (abi.storage_variables.length > 0 && name === storageInterfaceName) {
|
|
425
|
+
throw new CodegenError(`Program ${abi.program} declares a ${kind} '${name}', whose generated interface collides with the generated storage interface '${storageInterfaceName}'. Rename the ${kind}.`, { programId: abi.program, typeName: name, kind, phase: "generate" });
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
for (const struct of abi.structs)
|
|
429
|
+
check("struct", struct.path);
|
|
430
|
+
for (const record of abi.records)
|
|
431
|
+
check("record", record.path);
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* A transition whose generated `readonly ${name}` accessor collides with an
|
|
435
|
+
* inherited BaseContract member, or with the `mappings`/`storage` container when
|
|
436
|
+
* the program has mappings/storage. These can't be auto-renamed without changing
|
|
437
|
+
* the public call API (`contract.${name}`), so fail with a clear message.
|
|
438
|
+
*/
|
|
439
|
+
function assertNoReservedContractMembers(abi) {
|
|
440
|
+
const reserved = new Set(RESERVED_CONTRACT_INSTANCE_MEMBERS);
|
|
441
|
+
if (abi.mappings.length > 0)
|
|
442
|
+
reserved.add("mappings");
|
|
443
|
+
if (abi.storage_variables.length > 0)
|
|
444
|
+
reserved.add("storage");
|
|
445
|
+
for (const transition of abi.transitions) {
|
|
446
|
+
if (reserved.has(transition.name)) {
|
|
447
|
+
throw new CodegenError(`Program ${abi.program} has a transition '${transition.name}' whose generated accessor collides with a reserved contract member (inherited BaseContract members such as connect/withSigner/address/programId, or the mappings/storage container). Rename the transition.`, { programId: abi.program, transition: transition.name, phase: "generate" });
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* A dynamic-record helper is emitted as a module-level `export const
|
|
453
|
+
* ${helperName} = Object.assign(_${helperName}Impl, …)`, backed by a sibling
|
|
454
|
+
* `function _${helperName}Impl(…)`. Reject a helper whose name equals any other
|
|
455
|
+
* module-level value binding the generator emits, since two `const`s (or a
|
|
456
|
+
* `const`/`function` and an imported value) of the same name is a duplicate
|
|
457
|
+
* declaration (TS2451/TS2440):
|
|
458
|
+
* - the fixed BaseContract value imports (`BaseContract`,
|
|
459
|
+
* `createRecordOutputMatcher`, and `Leo` whenever helpers are emitted),
|
|
460
|
+
* - the contract class and its `create${class}` factory,
|
|
461
|
+
* - the per-type `serialize`/`deserialize`/`decrypt` consts,
|
|
462
|
+
* - the external ref serializer/deserializer aliases and record value bindings
|
|
463
|
+
* imported/re-exported for cross-program types (e.g. `serializeGoldToken_Token`),
|
|
464
|
+
* - the `_${otherHelper}Impl` backing function of any other helper (e.g. a
|
|
465
|
+
* helper `_asReceiptImpl` clashes with helper `asReceipt`'s impl function).
|
|
466
|
+
* The contract class is silently suffixed away from such collisions, but a
|
|
467
|
+
* helper name is user-chosen config (`codegen.dynamicRecords`) that can't be
|
|
468
|
+
* renamed without changing the call API, so fail with a clear message instead.
|
|
469
|
+
*/
|
|
470
|
+
function assertNoReservedHelperNames(abi, className, includeLeoValueImport, helpers, externalInfos) {
|
|
471
|
+
if (helpers.length === 0)
|
|
472
|
+
return;
|
|
473
|
+
// Reserved value-binding name -> short description of what it would clash with.
|
|
474
|
+
const reserved = new Map();
|
|
475
|
+
for (const name of baseContractValueImportNames(includeLeoValueImport)) {
|
|
476
|
+
reserved.set(name, `the '${name}' value imported from BaseContract`);
|
|
477
|
+
}
|
|
478
|
+
reserved.set(className, `the contract class '${className}'`);
|
|
479
|
+
reserved.set(`create${className}`, `the contract factory 'create${className}'`);
|
|
480
|
+
for (const struct of abi.structs) {
|
|
481
|
+
const name = pathToTsName(struct.path);
|
|
482
|
+
reserved.set(`serialize${name}`, `the generated 'serialize${name}'`);
|
|
483
|
+
reserved.set(`deserialize${name}`, `the generated 'deserialize${name}'`);
|
|
484
|
+
}
|
|
485
|
+
for (const record of abi.records) {
|
|
486
|
+
const name = pathToTsName(record.path);
|
|
487
|
+
reserved.set(`serialize${name}`, `the generated 'serialize${name}'`);
|
|
488
|
+
reserved.set(`deserialize${name}`, `the generated 'deserialize${name}'`);
|
|
489
|
+
reserved.set(`decrypt${name}`, `the generated 'decrypt${name}'`);
|
|
490
|
+
}
|
|
491
|
+
// External refs import `serialize${Base} as ${serializerName}` /
|
|
492
|
+
// `deserialize${Base} as ${deserializerName}` and external records re-export
|
|
493
|
+
// `export const ${typeName}`. Struct type-only aliases can share a helper
|
|
494
|
+
// value name, but serializer/deserializer aliases and record value bindings
|
|
495
|
+
// cannot.
|
|
496
|
+
for (const info of externalInfos) {
|
|
497
|
+
reserved.set(info.serializerName, `the imported external serializer '${info.serializerName}'`);
|
|
498
|
+
reserved.set(info.deserializerName, `the imported external deserializer '${info.deserializerName}'`);
|
|
499
|
+
if (info.emitsValueBinding) {
|
|
500
|
+
reserved.set(info.typeName, `the external record binding '${info.typeName}'`);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
// Each helper also emits a `function _${helperName}Impl` backing declaration.
|
|
504
|
+
// `_${helperName}Impl` is never equal to its own helper's name, so this only
|
|
505
|
+
// catches one helper's name colliding with another helper's impl function.
|
|
506
|
+
for (const helper of helpers) {
|
|
507
|
+
reserved.set(`_${helper.helperName}Impl`, `the backing function of dynamic-record helper '${helper.helperName}'`);
|
|
508
|
+
}
|
|
509
|
+
for (const helper of helpers) {
|
|
510
|
+
const clashesWith = reserved.get(helper.helperName);
|
|
511
|
+
if (clashesWith !== undefined) {
|
|
512
|
+
throw new CodegenError(`Program ${abi.program} configures a dynamic-record helper '${helper.helperName}', whose generated 'export const ${helper.helperName}' collides with ${clashesWith}. Rename the helper (codegen.dynamicRecords).`, { programId: abi.program, helperName: helper.helperName, phase: "generate" });
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
function createGenerationContext(abi, allAbis, reservedHelperNames = [], includeLeoValueImport = false) {
|
|
517
|
+
const programsById = new Map();
|
|
518
|
+
for (const programAbi of allAbis) {
|
|
519
|
+
programsById.set(programAbi.program, programAbi);
|
|
520
|
+
}
|
|
521
|
+
programsById.set(abi.program, abi);
|
|
522
|
+
const externalStructRefs = new Map();
|
|
523
|
+
const externalRecordRefs = new Map();
|
|
524
|
+
collectExternalRefs(abi, programsById, externalStructRefs, externalRecordRefs);
|
|
525
|
+
const externalInfoByKey = resolveExternalInfos(abi, externalStructRefs, externalRecordRefs, reservedHelperNames, includeLeoValueImport);
|
|
526
|
+
const { inputNameByKey, widenInputAlias } = resolveInputNames(abi, externalStructRefs, externalRecordRefs, externalInfoByKey, reservedHelperNames, includeLeoValueImport);
|
|
527
|
+
return {
|
|
528
|
+
programId: abi.program,
|
|
529
|
+
programsById,
|
|
530
|
+
structsByKey: new Map(abi.structs.map((struct) => [pathKey(struct.path), struct])),
|
|
531
|
+
recordsByKey: new Map(abi.records.map((record) => [pathKey(record.path), record])),
|
|
532
|
+
externalStructRefs,
|
|
533
|
+
externalRecordRefs,
|
|
534
|
+
externalInfoByKey,
|
|
535
|
+
inputNameByKey,
|
|
536
|
+
widenInputAlias,
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Names this module emits as top-level declarations from the program's own ABI:
|
|
541
|
+
* the contract class, its `${class}Storage` interface, and every local
|
|
542
|
+
* struct/record interface. Shared by the external-alias and input-name
|
|
543
|
+
* disambiguation passes so they reserve an identical base set. `${class}Storage`
|
|
544
|
+
* is reserved even when the program has no storage variables — harmless
|
|
545
|
+
* over-reservation that only ever yields more-unique names.
|
|
546
|
+
*/
|
|
547
|
+
function localDeclaredNames(abi, includeLeoValueImport) {
|
|
548
|
+
const className = resolveContractClassName(abi, { includeLeoValueImport });
|
|
549
|
+
return [
|
|
550
|
+
className,
|
|
551
|
+
`${className}Storage`,
|
|
552
|
+
...abi.structs.map((s) => pathToTsName(s.path)),
|
|
553
|
+
...abi.records.map((r) => pathToTsName(r.path)),
|
|
554
|
+
];
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Stable ordering for external refs by their `externalRefKey`, so underscore
|
|
558
|
+
* disambiguation is deterministic across runs.
|
|
559
|
+
*/
|
|
560
|
+
function sortRefsByKey(refs) {
|
|
561
|
+
return [...refs].sort((a, b) => externalRefKey(a).localeCompare(externalRefKey(b)));
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Build deterministic external type/helper aliases before emission so imports,
|
|
565
|
+
* type annotations, serializers, and deserializers all use the same resolved
|
|
566
|
+
* names. The preferred alias is `${ProgramClass}_${TypeName}`; underscores are
|
|
567
|
+
* appended only when needed to avoid a local declaration in this module.
|
|
568
|
+
*/
|
|
569
|
+
function resolveExternalInfos(abi, externalStructRefs, externalRecordRefs, reservedHelperNames = [], includeLeoValueImport = false) {
|
|
570
|
+
const reserved = new Set([...localDeclaredNames(abi, includeLeoValueImport)]);
|
|
571
|
+
// Structs and records share one map keyed by `externalRefKey` (program+path).
|
|
572
|
+
// Leo keeps structs and records in a single type namespace, so no struct and
|
|
573
|
+
// record can share a program+path — entries never alias each other here.
|
|
574
|
+
const infoByKey = new Map();
|
|
575
|
+
const claim = (ref, baseName, emitsValueBinding, extraReserved = []) => {
|
|
576
|
+
const programId = ref.program;
|
|
577
|
+
if (programId === null)
|
|
578
|
+
return;
|
|
579
|
+
const programClass = programIdToClassName(programId);
|
|
580
|
+
const preferred = `${programClass}_${baseName}`;
|
|
581
|
+
let typeName = preferred;
|
|
582
|
+
let underscores = 1;
|
|
583
|
+
while (reserved.has(typeName) || extraReserved.includes(typeName)) {
|
|
584
|
+
typeName = `${preferred}${"_".repeat(underscores)}`;
|
|
585
|
+
underscores++;
|
|
586
|
+
}
|
|
587
|
+
reserved.add(typeName);
|
|
588
|
+
infoByKey.set(externalRefKey(ref), {
|
|
589
|
+
programId,
|
|
590
|
+
className: programClass,
|
|
591
|
+
baseName,
|
|
592
|
+
typeName,
|
|
593
|
+
serializerName: `serialize${typeName}`,
|
|
594
|
+
deserializerName: `deserialize${typeName}`,
|
|
595
|
+
emitsValueBinding,
|
|
596
|
+
});
|
|
597
|
+
};
|
|
598
|
+
for (const ref of sortRefsByKey(externalStructRefs.values())) {
|
|
599
|
+
claim(ref, structRefName(ref), false, reservedHelperNames);
|
|
600
|
+
}
|
|
601
|
+
for (const ref of sortRefsByKey(externalRecordRefs.values())) {
|
|
602
|
+
claim(ref, recordRefName(ref), true);
|
|
603
|
+
}
|
|
604
|
+
return infoByKey;
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Identifiers imported from `BaseContract` that end in `Input` (the only fixed
|
|
608
|
+
* imports a `${name}Input` alias could collide with).
|
|
609
|
+
*/
|
|
610
|
+
const RESERVED_INPUT_IMPORTS = [
|
|
611
|
+
"AddressInput",
|
|
612
|
+
"FieldInput",
|
|
613
|
+
"GroupInput",
|
|
614
|
+
"ScalarInput",
|
|
615
|
+
"IdentifierInput",
|
|
616
|
+
"DynamicRecordInput",
|
|
617
|
+
"PlaintextInput",
|
|
618
|
+
"WidenInput",
|
|
619
|
+
];
|
|
620
|
+
/**
|
|
621
|
+
* Build the deterministic `${Name}Input` map for all local and external
|
|
622
|
+
* struct/record types. Runs before any emission; output is a pure function of
|
|
623
|
+
* the ABI set + the fixed import list, so it is reproducible across runs.
|
|
624
|
+
*/
|
|
625
|
+
function resolveInputNames(abi, externalStructRefs, externalRecordRefs, externalInfoByKey, reservedHelperNames = [], includeLeoValueImport = false) {
|
|
626
|
+
// `declared` = names this module emits as top-level declarations (interfaces,
|
|
627
|
+
// class, storage, external re-exports, dynamic-record helper consts, and the
|
|
628
|
+
// input aliases claimed below). Kept distinct from the fixed imports so the
|
|
629
|
+
// WidenInput import alias can be checked against genuine declaration
|
|
630
|
+
// collisions only.
|
|
631
|
+
const declared = new Set([
|
|
632
|
+
...localDeclaredNames(abi, includeLeoValueImport),
|
|
633
|
+
...reservedHelperNames,
|
|
634
|
+
]);
|
|
635
|
+
for (const ref of externalStructRefs.values()) {
|
|
636
|
+
declared.add(externalInfoByKey.get(externalRefKey(ref)).typeName);
|
|
637
|
+
}
|
|
638
|
+
for (const ref of externalRecordRefs.values()) {
|
|
639
|
+
declared.add(externalInfoByKey.get(externalRefKey(ref)).typeName);
|
|
640
|
+
}
|
|
641
|
+
const reserved = new Set([...RESERVED_INPUT_IMPORTS, ...declared]);
|
|
642
|
+
const inputNameByKey = new Map();
|
|
643
|
+
const claim = (key, base) => {
|
|
644
|
+
const name = disambiguateInputName(base, reserved);
|
|
645
|
+
reserved.add(name);
|
|
646
|
+
declared.add(name);
|
|
647
|
+
inputNameByKey.set(key, name);
|
|
648
|
+
};
|
|
649
|
+
// Deterministic order: local structs, then local records (ABI order), then
|
|
650
|
+
// external structs and records sorted by their stable ref key.
|
|
651
|
+
for (const struct of abi.structs)
|
|
652
|
+
claim(pathKey(struct.path), pathToTsName(struct.path));
|
|
653
|
+
for (const record of abi.records)
|
|
654
|
+
claim(pathKey(record.path), pathToTsName(record.path));
|
|
655
|
+
for (const ref of sortRefsByKey(externalStructRefs.values())) {
|
|
656
|
+
claim(externalRefKey(ref), externalInfoByKey.get(externalRefKey(ref)).typeName);
|
|
657
|
+
}
|
|
658
|
+
for (const ref of sortRefsByKey(externalRecordRefs.values())) {
|
|
659
|
+
claim(externalRefKey(ref), externalInfoByKey.get(externalRefKey(ref)).typeName);
|
|
660
|
+
}
|
|
661
|
+
// Choose a local name for the imported `WidenInput` that no generated
|
|
662
|
+
// declaration shadows (a local type/class literally named `WidenInput` would
|
|
663
|
+
// otherwise conflict with the import — TS2440). Checked against `declared`
|
|
664
|
+
// only, not the fixed imports.
|
|
665
|
+
const forbidden = declared;
|
|
666
|
+
let widenInputAlias = "WidenInput";
|
|
667
|
+
let underscores = 1;
|
|
668
|
+
while (forbidden.has(widenInputAlias)) {
|
|
669
|
+
widenInputAlias = `WidenInput${"_".repeat(underscores)}`;
|
|
670
|
+
underscores++;
|
|
671
|
+
}
|
|
672
|
+
return { inputNameByKey, widenInputAlias };
|
|
673
|
+
}
|
|
674
|
+
/** Resolved input-type name for a struct ref (local or external). */
|
|
675
|
+
function structInputName(ref, ctx) {
|
|
676
|
+
const key = isLocalStructRef(ref, ctx) ? pathKey(ref.path) : externalRefKey(ref);
|
|
677
|
+
return ctx.inputNameByKey.get(key) ?? `${structRefName(ref)}Input`;
|
|
678
|
+
}
|
|
679
|
+
/** Resolved input-type name for a record ref (local or external). */
|
|
680
|
+
function recordInputName(ref, ctx) {
|
|
681
|
+
const key = isLocalRecordRef(ref, ctx) ? pathKey(ref.path) : externalRefKey(ref);
|
|
682
|
+
return ctx.inputNameByKey.get(key) ?? `${recordRefName(ref)}Input`;
|
|
683
|
+
}
|
|
684
|
+
function collectExternalRefs(abi, programsById, structs, records) {
|
|
685
|
+
const addStruct = (ref) => {
|
|
686
|
+
if (!ref.program || ref.program === abi.program)
|
|
687
|
+
return;
|
|
688
|
+
const programAbi = programsById.get(ref.program);
|
|
689
|
+
if (!programAbi?.structs.some((struct) => pathKey(struct.path) === pathKey(ref.path)))
|
|
690
|
+
return;
|
|
691
|
+
structs.set(externalRefKey(ref), ref);
|
|
692
|
+
};
|
|
693
|
+
const addRecord = (ref) => {
|
|
694
|
+
if (!ref.program || ref.program === abi.program)
|
|
695
|
+
return;
|
|
696
|
+
const programAbi = programsById.get(ref.program);
|
|
697
|
+
if (!programAbi?.records.some((record) => pathKey(record.path) === pathKey(ref.path)))
|
|
698
|
+
return;
|
|
699
|
+
records.set(externalRefKey(ref), ref);
|
|
700
|
+
};
|
|
701
|
+
const visitPlaintext = (ty) => {
|
|
702
|
+
if ("Struct" in ty) {
|
|
703
|
+
addStruct(ty.Struct);
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
if ("Array" in ty) {
|
|
707
|
+
visitPlaintext(ty.Array[0]);
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
if ("Optional" in ty) {
|
|
711
|
+
visitPlaintext(ty.Optional);
|
|
712
|
+
}
|
|
713
|
+
};
|
|
714
|
+
const visitAleo = (ty) => {
|
|
715
|
+
if (ty === "DynamicRecord")
|
|
716
|
+
return;
|
|
717
|
+
if ("Plaintext" in ty) {
|
|
718
|
+
visitPlaintext(ty.Plaintext);
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
if ("Record" in ty) {
|
|
722
|
+
addRecord(ty.Record);
|
|
723
|
+
}
|
|
724
|
+
};
|
|
725
|
+
const visitStorage = (ty) => {
|
|
726
|
+
if ("Plaintext" in ty) {
|
|
727
|
+
visitPlaintext(ty.Plaintext);
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
if ("Vector" in ty) {
|
|
731
|
+
visitStorage(ty.Vector);
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
for (const struct of abi.structs) {
|
|
735
|
+
for (const field of struct.fields)
|
|
736
|
+
visitPlaintext(field.ty);
|
|
737
|
+
}
|
|
738
|
+
for (const record of abi.records) {
|
|
739
|
+
for (const field of record.fields)
|
|
740
|
+
visitPlaintext(field.ty);
|
|
741
|
+
}
|
|
742
|
+
for (const mapping of abi.mappings) {
|
|
743
|
+
visitPlaintext(mapping.key);
|
|
744
|
+
visitPlaintext(mapping.value);
|
|
745
|
+
}
|
|
746
|
+
for (const variable of abi.storage_variables)
|
|
747
|
+
visitStorage(variable.ty);
|
|
748
|
+
for (const transition of abi.transitions) {
|
|
749
|
+
for (const input of transition.inputs)
|
|
750
|
+
visitAleo(input.ty);
|
|
751
|
+
for (const output of transition.outputs)
|
|
752
|
+
visitAleo(output.ty);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
// ---------------------------------------------------------------------------
|
|
756
|
+
// Struct/Record/Storage interface generation
|
|
757
|
+
// ---------------------------------------------------------------------------
|
|
758
|
+
function generateStructInterface(struct, ctx) {
|
|
759
|
+
const name = pathToTsName(struct.path);
|
|
760
|
+
const lines = [];
|
|
761
|
+
lines.push(`export interface ${name} {`);
|
|
762
|
+
for (const field of struct.fields) {
|
|
763
|
+
lines.push(` readonly ${field.name}: ${plaintextToOutputBindingTs(field.ty, ctx)};`);
|
|
764
|
+
}
|
|
765
|
+
lines.push("}");
|
|
766
|
+
return lines;
|
|
767
|
+
}
|
|
768
|
+
function generateRecordInterface(record, ctx) {
|
|
769
|
+
const name = pathToTsName(record.path);
|
|
770
|
+
const lines = [];
|
|
771
|
+
lines.push(`export interface ${name} {`);
|
|
772
|
+
lines.push(" readonly owner: LeoAddress;");
|
|
773
|
+
for (const field of record.fields) {
|
|
774
|
+
if (["owner", "_nonce"].includes(field.name))
|
|
775
|
+
continue;
|
|
776
|
+
lines.push(` readonly ${field.name}: ${plaintextToOutputBindingTs(field.ty, ctx)};`);
|
|
777
|
+
}
|
|
778
|
+
lines.push(" readonly _nonce: LeoGroup;");
|
|
779
|
+
lines.push("}");
|
|
780
|
+
return lines;
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* Widened input interface mirroring `generateStructInterface` but typing every
|
|
784
|
+
* field via the input binding (scalar fields accept `bigint | number`, nested
|
|
785
|
+
* composites widen recursively). Used for transition args, mapping keys, and
|
|
786
|
+
* serializer inputs; the branded interface above is kept for outputs/reads.
|
|
787
|
+
*/
|
|
788
|
+
function generateStructInputInterface(struct, ctx) {
|
|
789
|
+
const name = ctx.inputNameByKey.get(pathKey(struct.path)) ?? `${pathToTsName(struct.path)}Input`;
|
|
790
|
+
const lines = [];
|
|
791
|
+
lines.push(`export interface ${name} {`);
|
|
792
|
+
for (const field of struct.fields) {
|
|
793
|
+
lines.push(` readonly ${field.name}: ${plaintextToInputBindingTs(field.ty, ctx)};`);
|
|
794
|
+
}
|
|
795
|
+
lines.push("}");
|
|
796
|
+
return lines;
|
|
797
|
+
}
|
|
798
|
+
/** Widened input interface for a record (`owner`/`_nonce` widened to their *Input aliases). */
|
|
799
|
+
function generateRecordInputInterface(record, ctx) {
|
|
800
|
+
const name = ctx.inputNameByKey.get(pathKey(record.path)) ?? `${pathToTsName(record.path)}Input`;
|
|
801
|
+
const lines = [];
|
|
802
|
+
lines.push(`export interface ${name} {`);
|
|
803
|
+
lines.push(" readonly owner: AddressInput;");
|
|
804
|
+
for (const field of record.fields) {
|
|
805
|
+
if (field.name === "owner")
|
|
806
|
+
continue;
|
|
807
|
+
lines.push(` readonly ${field.name}: ${plaintextToInputBindingTs(field.ty, ctx)};`);
|
|
808
|
+
}
|
|
809
|
+
lines.push(" readonly _nonce: GroupInput;");
|
|
810
|
+
lines.push("}");
|
|
811
|
+
return lines;
|
|
812
|
+
}
|
|
813
|
+
function generateStorageInterface(className, storageVariables, ctx) {
|
|
814
|
+
const lines = [];
|
|
815
|
+
lines.push(`export interface ${className}Storage {`);
|
|
816
|
+
for (const variable of storageVariables) {
|
|
817
|
+
lines.push(` readonly ${variable.name}: ${storageTypeToBindingTs(variable.ty, ctx)};`);
|
|
818
|
+
}
|
|
819
|
+
lines.push("}");
|
|
820
|
+
return lines;
|
|
821
|
+
}
|
|
822
|
+
// ---------------------------------------------------------------------------
|
|
823
|
+
// Serialization helpers
|
|
824
|
+
// ---------------------------------------------------------------------------
|
|
825
|
+
function generateStructSerializer(struct, ctx) {
|
|
826
|
+
const name = pathToTsName(struct.path);
|
|
827
|
+
const inputName = ctx.inputNameByKey.get(pathKey(struct.path)) ?? `${name}Input`;
|
|
828
|
+
const lines = [];
|
|
829
|
+
lines.push(`export function serialize${name}(value: ${inputName}, context?: TransitionInputContext): string {`);
|
|
830
|
+
lines.push(" BaseContract.assertObject(value, context);");
|
|
831
|
+
lines.push(" const fields: string[] = [];");
|
|
832
|
+
for (const field of struct.fields) {
|
|
833
|
+
const serialized = serializePlaintextExpr(`value.${field.name}`, field.ty, ctx, `BaseContract.childInputContext(context, "${field.name}")`);
|
|
834
|
+
lines.push(` fields.push("${field.name}: " + ${serialized});`);
|
|
835
|
+
}
|
|
836
|
+
lines.push(' return "{ " + fields.join(", ") + " }";');
|
|
837
|
+
lines.push("}");
|
|
838
|
+
return lines;
|
|
839
|
+
}
|
|
840
|
+
function generateRecordSerializer(record, ctx) {
|
|
841
|
+
const name = pathToTsName(record.path);
|
|
842
|
+
const inputName = ctx.inputNameByKey.get(pathKey(record.path)) ?? `${name}Input`;
|
|
843
|
+
const lines = [];
|
|
844
|
+
lines.push(`export function serialize${name}(value: ${inputName}, context?: TransitionInputContext): string {`);
|
|
845
|
+
lines.push(" BaseContract.assertObject(value, context);");
|
|
846
|
+
// Round-trip a record returned by a previous transition by replaying the
|
|
847
|
+
// original literal verbatim. Without this, per-field visibility suffixes
|
|
848
|
+
// mismatch on re-serialization and the runtime rejects the input. See
|
|
849
|
+
// BaseContract.RECORD_RAW.
|
|
850
|
+
lines.push(" const _raw = (value as unknown as { readonly [k: symbol]: unknown })[BaseContract.RECORD_RAW];");
|
|
851
|
+
lines.push(' if (typeof _raw === "string") return _raw;');
|
|
852
|
+
lines.push(" const fields: string[] = [];");
|
|
853
|
+
for (const field of record.fields) {
|
|
854
|
+
const serialized = serializePlaintextExpr(`value.${field.name}`, field.ty, ctx, `BaseContract.childInputContext(context, "${field.name}")`);
|
|
855
|
+
lines.push(` fields.push("${field.name}: " + ${serialized});`);
|
|
856
|
+
}
|
|
857
|
+
lines.push(' fields.push("_nonce: " + BaseContract.serializeGroup(value._nonce, BaseContract.childInputContext(context, "_nonce")));');
|
|
858
|
+
lines.push(' return "{ " + fields.join(", ") + " }";');
|
|
859
|
+
lines.push("}");
|
|
860
|
+
return lines;
|
|
861
|
+
}
|
|
862
|
+
function generateStructDeserializer(struct, ctx) {
|
|
863
|
+
const name = pathToTsName(struct.path);
|
|
864
|
+
const lines = [];
|
|
865
|
+
lines.push(`export function deserialize${name}(value: string): ${name} {`);
|
|
866
|
+
lines.push(" const _fields = BaseContract.parseStruct(value);");
|
|
867
|
+
lines.push(" return {");
|
|
868
|
+
for (const field of struct.fields) {
|
|
869
|
+
lines.push(` ${field.name}: ${deserializePlaintextExpr(`_fields["${field.name}"]!`, field.ty, ctx)},`);
|
|
870
|
+
}
|
|
871
|
+
lines.push(" };");
|
|
872
|
+
lines.push("}");
|
|
873
|
+
return lines;
|
|
874
|
+
}
|
|
875
|
+
function generateRecordDecryptor(record) {
|
|
876
|
+
const name = pathToTsName(record.path);
|
|
877
|
+
return [
|
|
878
|
+
`export async function decrypt${name}(ciphertext: string, key: RecordDecryptionKey): Promise<${name}> {`,
|
|
879
|
+
` return BaseContract.decryptRecord(ciphertext, key, deserialize${name});`,
|
|
880
|
+
"}",
|
|
881
|
+
];
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Emit a free function that converts a generated record value into a typed
|
|
885
|
+
* `LeoDynamicRecord` literal using `Leo.dynamicRecord(value, schema)`. The
|
|
886
|
+
* schema is fixed at codegen time from `helper.schema`; the generated
|
|
887
|
+
* function takes only the record value.
|
|
888
|
+
*
|
|
889
|
+
* Validates the helper config against the source record's generated shape:
|
|
890
|
+
* - implicit `owner: address` field
|
|
891
|
+
* - each ABI record field (excluding any explicit `owner` re-declaration)
|
|
892
|
+
* - implicit `_nonce: group` field
|
|
893
|
+
*
|
|
894
|
+
* Mismatches and unsupported primitive types throw `CodegenError` so users
|
|
895
|
+
* get a precise build-time failure instead of a runtime parser error.
|
|
896
|
+
*/
|
|
897
|
+
function generateDynamicRecordHelper(helper, abi, ctx) {
|
|
898
|
+
const record = abi.records.find((r) => pathToTsName(r.path) === helper.sourceRecord);
|
|
899
|
+
if (!record) {
|
|
900
|
+
throw new CodegenError(`codegen.dynamicRecords.${helper.helperName}: sourceRecord '${helper.sourceRecord}' is not a local record in '${abi.program}'.`, { helperName: helper.helperName, sourceRecord: helper.sourceRecord, program: abi.program });
|
|
901
|
+
}
|
|
902
|
+
const expectedFields = buildExpectedFieldsForHelper(helper, record);
|
|
903
|
+
const schemaKeys = Object.keys(helper.schema);
|
|
904
|
+
const missing = [...expectedFields.keys()].filter((k) => !Object.hasOwn(helper.schema, k));
|
|
905
|
+
const extra = schemaKeys.filter((k) => !expectedFields.has(k));
|
|
906
|
+
if (missing.length > 0 || extra.length > 0) {
|
|
907
|
+
throw new CodegenError(`codegen.dynamicRecords.${helper.helperName}: schema keys do not match record '${helper.sourceRecord}'. Missing: [${missing.join(", ")}]; Extra: [${extra.join(", ")}].`, {
|
|
908
|
+
helperName: helper.helperName,
|
|
909
|
+
sourceRecord: helper.sourceRecord,
|
|
910
|
+
missing,
|
|
911
|
+
extra,
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
for (const fieldName of schemaKeys) {
|
|
915
|
+
const entry = helper.schema[fieldName];
|
|
916
|
+
const dot = entry.lastIndexOf(".");
|
|
917
|
+
if (dot < 0) {
|
|
918
|
+
throw new CodegenError(`codegen.dynamicRecords.${helper.helperName}.schema.${fieldName}: '${entry}' is not a valid '<type>.<visibility>' schema entry.`, { helperName: helper.helperName, field: fieldName, schemaEntry: entry });
|
|
919
|
+
}
|
|
920
|
+
const schemaPrim = entry.slice(0, dot);
|
|
921
|
+
const expectedPrim = expectedFields.get(fieldName);
|
|
922
|
+
if (schemaPrim !== expectedPrim) {
|
|
923
|
+
throw new CodegenError(`codegen.dynamicRecords.${helper.helperName}.schema.${fieldName}: field has Leo type '${expectedPrim}' on record '${helper.sourceRecord}', but schema says '${schemaPrim}'.`, {
|
|
924
|
+
helperName: helper.helperName,
|
|
925
|
+
field: fieldName,
|
|
926
|
+
expected: expectedPrim,
|
|
927
|
+
actual: schemaPrim,
|
|
928
|
+
});
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
const lines = [];
|
|
932
|
+
const fnName = `_${helper.helperName}Impl`;
|
|
933
|
+
// `value` is widened to the record's resolved input interface so callers may
|
|
934
|
+
// pass raw field values; `.output` (below) stays the branded record type.
|
|
935
|
+
const inputName = ctx.inputNameByKey.get(pathKey(record.path)) ?? `${helper.sourceRecord}Input`;
|
|
936
|
+
lines.push(`function ${fnName}(value: ${inputName}): LeoDynamicRecord {`);
|
|
937
|
+
lines.push(" return Leo.dynamicRecord(value, {");
|
|
938
|
+
for (const [key, entry] of Object.entries(helper.schema)) {
|
|
939
|
+
lines.push(` ${key}: ${JSON.stringify(entry)} as const,`);
|
|
940
|
+
}
|
|
941
|
+
lines.push(" } as const);");
|
|
942
|
+
lines.push("}");
|
|
943
|
+
// Callable + namespace pattern: the helper is also a namespace carrying
|
|
944
|
+
// `output`, the output-side matcher. Used by callers refining record
|
|
945
|
+
// decryption via an id-only handle's `.match(matcher.from(...)|.at(...))`
|
|
946
|
+
// or the encrypted-record arm's `.match(matcher)`.
|
|
947
|
+
lines.push(`export const ${helper.helperName} = Object.assign(${fnName}, {`);
|
|
948
|
+
lines.push(` output: createRecordOutputMatcher<${helper.sourceRecord}>({`);
|
|
949
|
+
lines.push(` program: "${abi.program}",`);
|
|
950
|
+
lines.push(` recordName: "${helper.sourceRecord}",`);
|
|
951
|
+
lines.push(` deserialize: deserialize${helper.sourceRecord},`);
|
|
952
|
+
lines.push(` }),`);
|
|
953
|
+
lines.push(` forProgram(programId: string) {`);
|
|
954
|
+
lines.push(` return bindDynamicRecordHelperProgram(${fnName}, ${helper.helperName}.output, programId);`);
|
|
955
|
+
lines.push(" },");
|
|
956
|
+
lines.push("});");
|
|
957
|
+
return lines;
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Build the expected `<fieldName, primitive>` map matching the generated
|
|
961
|
+
* record interface shape:
|
|
962
|
+
* 1. implicit `owner: address`
|
|
963
|
+
* 2. each ABI field that isn't a re-declaration of `owner`
|
|
964
|
+
* 3. implicit `_nonce: group`
|
|
965
|
+
*
|
|
966
|
+
* Rejects unsupported ABI primitives (Identifier, Signature) and non-primitive
|
|
967
|
+
* fields (struct, array, optional). These cases cannot be encoded by
|
|
968
|
+
* `Leo.dynamicRecord` even though they may appear in a record's serialized form.
|
|
969
|
+
*/
|
|
970
|
+
function buildExpectedFieldsForHelper(helper, record) {
|
|
971
|
+
const expectedFields = new Map();
|
|
972
|
+
expectedFields.set("owner", "address");
|
|
973
|
+
for (const field of record.fields) {
|
|
974
|
+
if (field.name === "owner")
|
|
975
|
+
continue;
|
|
976
|
+
const prim = primitiveOfPlaintext(field.ty);
|
|
977
|
+
if (prim === null) {
|
|
978
|
+
throw new CodegenError(`codegen.dynamicRecords.${helper.helperName}: record '${helper.sourceRecord}' contains non-primitive field '${field.name}'. Interface conversion helpers only support primitive record fields.`, { helperName: helper.helperName, sourceRecord: helper.sourceRecord, field: field.name });
|
|
979
|
+
}
|
|
980
|
+
if (!SUPPORTED_DYNAMIC_RECORD_PRIMITIVES.has(prim)) {
|
|
981
|
+
throw new CodegenError(`codegen.dynamicRecords.${helper.helperName}: record '${helper.sourceRecord}' field '${field.name}' uses unsupported primitive '${prim}'. Leo.dynamicRecord only supports: ${[...SUPPORTED_DYNAMIC_RECORD_PRIMITIVES].join("/")}.`, {
|
|
982
|
+
helperName: helper.helperName,
|
|
983
|
+
sourceRecord: helper.sourceRecord,
|
|
984
|
+
field: field.name,
|
|
985
|
+
primitive: prim,
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
expectedFields.set(field.name, prim);
|
|
989
|
+
}
|
|
990
|
+
expectedFields.set("_nonce", "group");
|
|
991
|
+
return expectedFields;
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* Map a PlaintextType primitive to its Leo source-level name (lowercase),
|
|
995
|
+
* matching the keys of `serializeDynamicRecordField`'s dispatch table.
|
|
996
|
+
* Returns null for non-primitive types (struct, array, optional).
|
|
997
|
+
*/
|
|
998
|
+
function primitiveOfPlaintext(ty) {
|
|
999
|
+
if (typeof ty !== "object" || ty === null)
|
|
1000
|
+
return null;
|
|
1001
|
+
if (!("Primitive" in ty))
|
|
1002
|
+
return null;
|
|
1003
|
+
const prim = ty.Primitive;
|
|
1004
|
+
if (typeof prim === "string") {
|
|
1005
|
+
switch (prim) {
|
|
1006
|
+
case "Address":
|
|
1007
|
+
return "address";
|
|
1008
|
+
case "Boolean":
|
|
1009
|
+
return "boolean";
|
|
1010
|
+
case "Field":
|
|
1011
|
+
return "field";
|
|
1012
|
+
case "Group":
|
|
1013
|
+
return "group";
|
|
1014
|
+
case "Scalar":
|
|
1015
|
+
return "scalar";
|
|
1016
|
+
case "Identifier":
|
|
1017
|
+
return "identifier";
|
|
1018
|
+
}
|
|
1019
|
+
return null;
|
|
1020
|
+
}
|
|
1021
|
+
if (typeof prim === "object" && prim !== null) {
|
|
1022
|
+
if ("UInt" in prim)
|
|
1023
|
+
return prim.UInt.toLowerCase();
|
|
1024
|
+
if ("Int" in prim)
|
|
1025
|
+
return prim.Int.toLowerCase();
|
|
1026
|
+
}
|
|
1027
|
+
return null;
|
|
1028
|
+
}
|
|
1029
|
+
function generateRecordDeserializer(record, ctx) {
|
|
1030
|
+
const name = pathToTsName(record.path);
|
|
1031
|
+
const lines = [];
|
|
1032
|
+
lines.push(`export function deserialize${name}(value: string): ${name} {`);
|
|
1033
|
+
lines.push(" const _fields = BaseContract.parseStruct(value);");
|
|
1034
|
+
lines.push(` const _record: ${name} = {`);
|
|
1035
|
+
lines.push(' owner: BaseContract.parseAddress(_fields["owner"]!),');
|
|
1036
|
+
for (const field of record.fields) {
|
|
1037
|
+
if (field.name === "owner")
|
|
1038
|
+
continue;
|
|
1039
|
+
lines.push(` ${field.name}: ${deserializePlaintextExpr(`_fields["${field.name}"]!`, field.ty, ctx)},`);
|
|
1040
|
+
}
|
|
1041
|
+
lines.push(' _nonce: BaseContract.parseGroup(_fields["_nonce"] ?? ""),');
|
|
1042
|
+
lines.push(" };");
|
|
1043
|
+
// Stash the original literal so serialize${name} can replay it verbatim
|
|
1044
|
+
// and avoid mangling per-field visibility suffixes on round-trip.
|
|
1045
|
+
lines.push(" Object.defineProperty(_record, BaseContract.RECORD_RAW, { value, enumerable: false });");
|
|
1046
|
+
lines.push(" return _record;");
|
|
1047
|
+
lines.push("}");
|
|
1048
|
+
return lines;
|
|
1049
|
+
}
|
|
1050
|
+
// ---------------------------------------------------------------------------
|
|
1051
|
+
// Contract class generation
|
|
1052
|
+
// ---------------------------------------------------------------------------
|
|
1053
|
+
function generateContractClass(abi, className, ctx) {
|
|
1054
|
+
const lines = [];
|
|
1055
|
+
lines.push(`export class ${className} extends BaseContract {`);
|
|
1056
|
+
lines.push(" constructor(options?: BaseContractOptions) {");
|
|
1057
|
+
lines.push(` super("${abi.program}", options);`);
|
|
1058
|
+
lines.push(" }");
|
|
1059
|
+
for (const transition of abi.transitions) {
|
|
1060
|
+
lines.push("");
|
|
1061
|
+
lines.push(...indentLines(generateTransitionMethod(transition, ctx), " "));
|
|
1062
|
+
}
|
|
1063
|
+
if (abi.mappings.length > 0) {
|
|
1064
|
+
const propKeys = buildMappingPropKeys(abi.mappings);
|
|
1065
|
+
lines.push("");
|
|
1066
|
+
lines.push(" readonly mappings = {");
|
|
1067
|
+
for (const mapping of abi.mappings) {
|
|
1068
|
+
lines.push(...indentLines(generateMappingAccessor(mapping, propKeys, ctx), " "));
|
|
1069
|
+
}
|
|
1070
|
+
lines.push(" } as const;");
|
|
1071
|
+
}
|
|
1072
|
+
if (abi.storage_variables.length > 0) {
|
|
1073
|
+
const propKeys = buildStoragePropKeys(abi.storage_variables);
|
|
1074
|
+
lines.push("");
|
|
1075
|
+
lines.push(" readonly storage = {");
|
|
1076
|
+
for (const variable of abi.storage_variables) {
|
|
1077
|
+
lines.push(...indentLines(generateStorageAccessor(variable, propKeys, ctx), " "));
|
|
1078
|
+
}
|
|
1079
|
+
lines.push(" } as const;");
|
|
1080
|
+
}
|
|
1081
|
+
lines.push("}");
|
|
1082
|
+
lines.push("");
|
|
1083
|
+
lines.push(`export function create${className}(options?: BaseContractOptions): ${className} {`);
|
|
1084
|
+
lines.push(` return new ${className}(options);`);
|
|
1085
|
+
lines.push("}");
|
|
1086
|
+
return lines;
|
|
1087
|
+
}
|
|
1088
|
+
function generateTransitionMethod(transition, ctx) {
|
|
1089
|
+
const lines = [];
|
|
1090
|
+
const safeNames = buildSafeParamNames(transition.inputs);
|
|
1091
|
+
const returnType = formatReturnType(transition.outputs, ctx);
|
|
1092
|
+
lines.push(`readonly ${transition.name} = {`);
|
|
1093
|
+
lines.push(` locally: async (${formatTransitionMethodParams(transition.inputs, ctx, safeNames, "LocalExecutionOptions")}): Promise<${returnType}> => {`);
|
|
1094
|
+
lines.push(...generateSerializedArgsLines(transition, ctx, safeNames, " "));
|
|
1095
|
+
lines.push(` const _result = await this.executeLocal("${transition.name}", _args, options ?? {});`);
|
|
1096
|
+
if (transition.outputs.length === 1) {
|
|
1097
|
+
const output = transition.outputs[0];
|
|
1098
|
+
lines.push(` return ${deserializeOutputExpr(`this.outputAt(_result, "${transition.name}", 0)`, output.ty, ctx)};`);
|
|
1099
|
+
}
|
|
1100
|
+
else if (transition.outputs.length > 1) {
|
|
1101
|
+
const tupleType = formatReturnType(transition.outputs, ctx);
|
|
1102
|
+
const elems = transition.outputs.map((o, i) => deserializeOutputExpr(`this.outputAt(_result, "${transition.name}", ${i})`, o.ty, ctx));
|
|
1103
|
+
lines.push(` const _decoded: ${tupleType} = [${elems.join(", ")}];`);
|
|
1104
|
+
lines.push(" return _decoded;");
|
|
1105
|
+
}
|
|
1106
|
+
else {
|
|
1107
|
+
lines.push(" return undefined as any;");
|
|
1108
|
+
}
|
|
1109
|
+
lines.push(" },");
|
|
1110
|
+
lines.push("");
|
|
1111
|
+
lines.push(` failsLocally: async (${formatTransitionMethodParams(transition.inputs, ctx, safeNames, "LocalExecutionOptions")}): Promise<void> => {`);
|
|
1112
|
+
lines.push(...generateSerializedArgsLines(transition, ctx, safeNames, " "));
|
|
1113
|
+
lines.push(` await this.expectLocalFailure("${transition.name}", _args, options ?? {});`);
|
|
1114
|
+
lines.push(" },");
|
|
1115
|
+
lines.push("");
|
|
1116
|
+
lines.push(` captureLocalFailure: async (${formatTransitionMethodParams(transition.inputs, ctx, safeNames, "LocalExecutionOptions")}): Promise<LocalTransitionError> => {`);
|
|
1117
|
+
lines.push(...generateSerializedArgsLines(transition, ctx, safeNames, " "));
|
|
1118
|
+
lines.push(` return this.expectLocalFailure("${transition.name}", _args, options ?? {});`);
|
|
1119
|
+
lines.push(" },");
|
|
1120
|
+
lines.push("");
|
|
1121
|
+
const typedOutputType = formatTypedOutputType(transition.outputs, ctx);
|
|
1122
|
+
const projectorExpr = formatProjectorExpr(transition, ctx.programId, "this.sourceProgramId", "this.programId", ctx);
|
|
1123
|
+
lines.push(` submitted: async (${formatTransitionMethodParams(transition.inputs, ctx, safeNames, "OnChainExecutionOptions")}): Promise<SubmittedTransition> => {`);
|
|
1124
|
+
lines.push(...generateSerializedArgsLines(transition, ctx, safeNames, " "));
|
|
1125
|
+
lines.push(` return this.submitTransition("${transition.name}", _args, options ?? {});`);
|
|
1126
|
+
lines.push(" },");
|
|
1127
|
+
lines.push("");
|
|
1128
|
+
lines.push(` settled: async (${formatTransitionMethodParams(transition.inputs, ctx, safeNames, "OnChainExecutionOptions")}): Promise<AcceptedTransition<${typedOutputType}> | RejectedTransition> => {`);
|
|
1129
|
+
lines.push(...generateSerializedArgsLines(transition, ctx, safeNames, " "));
|
|
1130
|
+
lines.push(` return this.settleTyped("${transition.name}", _args, options ?? {}, ${projectorExpr});`);
|
|
1131
|
+
lines.push(" },");
|
|
1132
|
+
lines.push("");
|
|
1133
|
+
lines.push(` accepted: async (${formatTransitionMethodParams(transition.inputs, ctx, safeNames, "OnChainExecutionOptions")}): Promise<AcceptedTransition<${typedOutputType}>> => {`);
|
|
1134
|
+
lines.push(...generateSerializedArgsLines(transition, ctx, safeNames, " "));
|
|
1135
|
+
lines.push(` return this.expectAcceptedTyped("${transition.name}", _args, options ?? {}, ${projectorExpr});`);
|
|
1136
|
+
lines.push(" },");
|
|
1137
|
+
lines.push("");
|
|
1138
|
+
lines.push(` rejected: async (${formatTransitionMethodParams(transition.inputs, ctx, safeNames, "OnChainExecutionOptions")}): Promise<RejectedTransition> => {`);
|
|
1139
|
+
lines.push(...generateSerializedArgsLines(transition, ctx, safeNames, " "));
|
|
1140
|
+
lines.push(` return this.expectRejected("${transition.name}", _args, options ?? {});`);
|
|
1141
|
+
lines.push(" },");
|
|
1142
|
+
lines.push("} as const;");
|
|
1143
|
+
return lines;
|
|
1144
|
+
}
|
|
1145
|
+
function generateSerializedArgsLines(transition, ctx, safeNames, indent) {
|
|
1146
|
+
const lines = [`${indent}const _args: string[] = [`];
|
|
1147
|
+
for (const input of transition.inputs) {
|
|
1148
|
+
lines.push(`${indent} ${serializeInputExpr(input, transition.name, safeNames, ctx)},`);
|
|
1149
|
+
}
|
|
1150
|
+
lines.push(`${indent}];`);
|
|
1151
|
+
return lines;
|
|
1152
|
+
}
|
|
1153
|
+
function generateMappingAccessor(mapping, propKeys, ctx) {
|
|
1154
|
+
const propKey = propKeys.get(mapping.name) ?? JSON.stringify(mapping.name);
|
|
1155
|
+
const keyType = plaintextToInputBindingTs(mapping.key, ctx);
|
|
1156
|
+
const valueType = plaintextToOutputBindingTs(mapping.value, ctx);
|
|
1157
|
+
const keySerializer = serializePlaintextExpr("key", mapping.key, ctx, `{ programId: this.programId, input: "${mapping.name} key" }`);
|
|
1158
|
+
const valueDeserializer = deserializePlaintextExpr("_result", mapping.value, ctx);
|
|
1159
|
+
return [
|
|
1160
|
+
`${propKey}: {`,
|
|
1161
|
+
` contains: async (key: ${keyType}): Promise<boolean> => {`,
|
|
1162
|
+
` return this.mappingContains("${mapping.name}", ${keySerializer});`,
|
|
1163
|
+
` },`,
|
|
1164
|
+
` get: async (key: ${keyType}): Promise<${valueType}> => {`,
|
|
1165
|
+
` const _result = await this.requireMappingRaw("${mapping.name}", ${keySerializer});`,
|
|
1166
|
+
` return ${valueDeserializer};`,
|
|
1167
|
+
` },`,
|
|
1168
|
+
` getOrUse: async (key: ${keyType}, def: ${valueType}): Promise<${valueType}> => {`,
|
|
1169
|
+
` const _result = await this.queryMapping("${mapping.name}", ${keySerializer});`,
|
|
1170
|
+
` if (_result === null) return def;`,
|
|
1171
|
+
` return ${valueDeserializer};`,
|
|
1172
|
+
` },`,
|
|
1173
|
+
` tryGet: async (key: ${keyType}): Promise<${valueType} | null> => {`,
|
|
1174
|
+
` const _result = await this.queryMapping("${mapping.name}", ${keySerializer});`,
|
|
1175
|
+
` if (_result === null) return null;`,
|
|
1176
|
+
` return ${valueDeserializer};`,
|
|
1177
|
+
` },`,
|
|
1178
|
+
`},`,
|
|
1179
|
+
];
|
|
1180
|
+
}
|
|
1181
|
+
function generateStorageAccessor(variable, propKeys, ctx) {
|
|
1182
|
+
const propKey = propKeys.get(variable.name) ?? JSON.stringify(variable.name);
|
|
1183
|
+
if ("Vector" in variable.ty) {
|
|
1184
|
+
const valueType = storageTypeToBindingTs(variable.ty.Vector, ctx);
|
|
1185
|
+
const valueDeserializer = deserializeStorageExpr("_result", variable.ty.Vector, ctx);
|
|
1186
|
+
const elementDeserializer = deserializeStorageExpr("e", variable.ty.Vector, ctx);
|
|
1187
|
+
return [
|
|
1188
|
+
`${propKey}: {`,
|
|
1189
|
+
` len: async (): Promise<number> => {`,
|
|
1190
|
+
` return this.queryStorageVectorLength("${variable.name}");`,
|
|
1191
|
+
` },`,
|
|
1192
|
+
` get: async (index: number): Promise<${valueType}> => {`,
|
|
1193
|
+
` const _result = await this.requireStorageVectorRaw("${variable.name}", index);`,
|
|
1194
|
+
` return ${valueDeserializer};`,
|
|
1195
|
+
` },`,
|
|
1196
|
+
` getOrUse: async (index: number, def: ${valueType}): Promise<${valueType}> => {`,
|
|
1197
|
+
` const _result = await this.queryStorageVector("${variable.name}", index);`,
|
|
1198
|
+
` if (_result === null) return def;`,
|
|
1199
|
+
` return ${valueDeserializer};`,
|
|
1200
|
+
` },`,
|
|
1201
|
+
` tryGet: async (index: number): Promise<${valueType} | null> => {`,
|
|
1202
|
+
` const _result = await this.queryStorageVector("${variable.name}", index);`,
|
|
1203
|
+
` if (_result === null) return null;`,
|
|
1204
|
+
` return ${valueDeserializer};`,
|
|
1205
|
+
` },`,
|
|
1206
|
+
` getAll: async (): Promise<${valueType}[]> => {`,
|
|
1207
|
+
` const _results = await this.queryStorageVectorAll("${variable.name}");`,
|
|
1208
|
+
` return _results.map((e: string) => ${elementDeserializer});`,
|
|
1209
|
+
` },`,
|
|
1210
|
+
` toArray: async (): Promise<${valueType}[]> => {`,
|
|
1211
|
+
` const _results = await this.queryStorageVectorAll("${variable.name}");`,
|
|
1212
|
+
` return _results.map((e: string) => ${elementDeserializer});`,
|
|
1213
|
+
` },`,
|
|
1214
|
+
`},`,
|
|
1215
|
+
];
|
|
1216
|
+
}
|
|
1217
|
+
const valueType = storageTypeToBindingTs(variable.ty, ctx);
|
|
1218
|
+
const valueDeserializer = deserializeStorageExpr("_result", variable.ty, ctx);
|
|
1219
|
+
return [
|
|
1220
|
+
`${propKey}: {`,
|
|
1221
|
+
` get: async (): Promise<${valueType}> => {`,
|
|
1222
|
+
` const _result = await this.requireStorageRaw("${variable.name}");`,
|
|
1223
|
+
` return ${valueDeserializer};`,
|
|
1224
|
+
` },`,
|
|
1225
|
+
` getOrUse: async (def: ${valueType}): Promise<${valueType}> => {`,
|
|
1226
|
+
` const _result = await this.queryStorage("${variable.name}");`,
|
|
1227
|
+
` if (_result === null) return def;`,
|
|
1228
|
+
` return ${valueDeserializer};`,
|
|
1229
|
+
` },`,
|
|
1230
|
+
` tryGet: async (): Promise<${valueType} | null> => {`,
|
|
1231
|
+
` const _result = await this.queryStorage("${variable.name}");`,
|
|
1232
|
+
` if (_result === null) return null;`,
|
|
1233
|
+
` return ${valueDeserializer};`,
|
|
1234
|
+
` },`,
|
|
1235
|
+
`},`,
|
|
1236
|
+
];
|
|
1237
|
+
}
|
|
1238
|
+
// ---------------------------------------------------------------------------
|
|
1239
|
+
// Type mapping helpers used by code generation
|
|
1240
|
+
// ---------------------------------------------------------------------------
|
|
1241
|
+
function plaintextToOutputBindingTs(pt, ctx) {
|
|
1242
|
+
if ("Primitive" in pt)
|
|
1243
|
+
return primitiveOutputBindingTs(pt.Primitive);
|
|
1244
|
+
if ("Struct" in pt) {
|
|
1245
|
+
if (isLocalStructRef(pt.Struct, ctx))
|
|
1246
|
+
return structRefName(pt.Struct);
|
|
1247
|
+
const external = externalStructInfo(pt.Struct, ctx);
|
|
1248
|
+
return external?.typeName ?? "LeoPlaintext";
|
|
1249
|
+
}
|
|
1250
|
+
if ("Array" in pt) {
|
|
1251
|
+
const [elemType] = pt.Array;
|
|
1252
|
+
return `ReadonlyArray<${plaintextToOutputBindingTs(elemType, ctx)}>`;
|
|
1253
|
+
}
|
|
1254
|
+
if ("Optional" in pt)
|
|
1255
|
+
return `${plaintextToOutputBindingTs(pt.Optional, ctx)} | null`;
|
|
1256
|
+
return "unknown";
|
|
1257
|
+
}
|
|
1258
|
+
function plaintextToInputBindingTs(pt, ctx) {
|
|
1259
|
+
if ("Primitive" in pt)
|
|
1260
|
+
return primitiveInputBindingTs(pt.Primitive);
|
|
1261
|
+
if ("Struct" in pt) {
|
|
1262
|
+
if (isLocalStructRef(pt.Struct, ctx))
|
|
1263
|
+
return structInputName(pt.Struct, ctx);
|
|
1264
|
+
const external = externalStructInfo(pt.Struct, ctx);
|
|
1265
|
+
return external ? structInputName(pt.Struct, ctx) : "PlaintextInput";
|
|
1266
|
+
}
|
|
1267
|
+
if ("Array" in pt) {
|
|
1268
|
+
const [elemType] = pt.Array;
|
|
1269
|
+
return `ReadonlyArray<${plaintextToInputBindingTs(elemType, ctx)}>`;
|
|
1270
|
+
}
|
|
1271
|
+
if ("Optional" in pt)
|
|
1272
|
+
return `${plaintextToInputBindingTs(pt.Optional, ctx)} | null`;
|
|
1273
|
+
return "unknown";
|
|
1274
|
+
}
|
|
1275
|
+
function aleoTypeToOutputBindingTs(ty, ctx) {
|
|
1276
|
+
if (ty === "DynamicRecord")
|
|
1277
|
+
return "LeoDynamicRecord";
|
|
1278
|
+
if ("Plaintext" in ty)
|
|
1279
|
+
return plaintextToOutputBindingTs(ty.Plaintext, ctx);
|
|
1280
|
+
if ("Record" in ty) {
|
|
1281
|
+
if (isLocalRecordRef(ty.Record, ctx))
|
|
1282
|
+
return recordRefName(ty.Record);
|
|
1283
|
+
const external = externalRecordInfo(ty.Record, ctx);
|
|
1284
|
+
return external?.typeName ?? "LeoDynamicRecord";
|
|
1285
|
+
}
|
|
1286
|
+
if ("Future" in ty)
|
|
1287
|
+
return "void";
|
|
1288
|
+
return "unknown";
|
|
1289
|
+
}
|
|
1290
|
+
function aleoTypeToInputBindingTs(ty, ctx) {
|
|
1291
|
+
if (ty === "DynamicRecord")
|
|
1292
|
+
return "DynamicRecordInput";
|
|
1293
|
+
if ("Plaintext" in ty)
|
|
1294
|
+
return plaintextToInputBindingTs(ty.Plaintext, ctx);
|
|
1295
|
+
if ("Record" in ty) {
|
|
1296
|
+
if (isLocalRecordRef(ty.Record, ctx))
|
|
1297
|
+
return recordInputName(ty.Record, ctx);
|
|
1298
|
+
const external = externalRecordInfo(ty.Record, ctx);
|
|
1299
|
+
return external ? recordInputName(ty.Record, ctx) : "DynamicRecordInput";
|
|
1300
|
+
}
|
|
1301
|
+
if ("Future" in ty)
|
|
1302
|
+
return "void";
|
|
1303
|
+
return "unknown";
|
|
1304
|
+
}
|
|
1305
|
+
function storageTypeToBindingTs(ty, ctx) {
|
|
1306
|
+
if ("Plaintext" in ty)
|
|
1307
|
+
return plaintextToOutputBindingTs(ty.Plaintext, ctx);
|
|
1308
|
+
if ("Vector" in ty)
|
|
1309
|
+
return `${storageTypeToBindingTs(ty.Vector, ctx)}[]`;
|
|
1310
|
+
return "unknown";
|
|
1311
|
+
}
|
|
1312
|
+
function primitiveOutputBindingTs(prim) {
|
|
1313
|
+
if (typeof prim === "string") {
|
|
1314
|
+
switch (prim) {
|
|
1315
|
+
case "Address":
|
|
1316
|
+
return "LeoAddress";
|
|
1317
|
+
case "Boolean":
|
|
1318
|
+
return "boolean";
|
|
1319
|
+
case "Field":
|
|
1320
|
+
return "LeoField";
|
|
1321
|
+
case "Group":
|
|
1322
|
+
return "LeoGroup";
|
|
1323
|
+
case "Identifier":
|
|
1324
|
+
return "LeoIdentifier";
|
|
1325
|
+
case "Scalar":
|
|
1326
|
+
return "LeoScalar";
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
if (isBigIntType(prim))
|
|
1330
|
+
return "bigint";
|
|
1331
|
+
return "number";
|
|
1332
|
+
}
|
|
1333
|
+
function primitiveInputBindingTs(prim) {
|
|
1334
|
+
if (typeof prim === "string") {
|
|
1335
|
+
switch (prim) {
|
|
1336
|
+
case "Address":
|
|
1337
|
+
return "AddressInput";
|
|
1338
|
+
case "Boolean":
|
|
1339
|
+
return "boolean";
|
|
1340
|
+
case "Field":
|
|
1341
|
+
return "FieldInput";
|
|
1342
|
+
case "Group":
|
|
1343
|
+
return "GroupInput";
|
|
1344
|
+
case "Identifier":
|
|
1345
|
+
return "IdentifierInput";
|
|
1346
|
+
case "Scalar":
|
|
1347
|
+
return "ScalarInput";
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
if (isBigIntType(prim))
|
|
1351
|
+
return "bigint";
|
|
1352
|
+
return "number";
|
|
1353
|
+
}
|
|
1354
|
+
// ---------------------------------------------------------------------------
|
|
1355
|
+
// Serialization expression generators (JS value → Leo string)
|
|
1356
|
+
// ---------------------------------------------------------------------------
|
|
1357
|
+
function serializeInputExpr(input, transitionName, safeNames, ctx) {
|
|
1358
|
+
return serializeAleoTypeExpr(safeNames.get(input.name), input.ty, ctx, `this.inputContext("${transitionName}", "${input.name}")`);
|
|
1359
|
+
}
|
|
1360
|
+
function serializeAleoTypeExpr(expr, ty, ctx, contextExpr = "undefined") {
|
|
1361
|
+
if (ty === "DynamicRecord")
|
|
1362
|
+
return `BaseContract.serializeDynamicRecord(${expr}, ${contextExpr})`;
|
|
1363
|
+
if ("Plaintext" in ty)
|
|
1364
|
+
return serializePlaintextExpr(expr, ty.Plaintext, ctx, contextExpr);
|
|
1365
|
+
if ("Record" in ty) {
|
|
1366
|
+
if (isLocalRecordRef(ty.Record, ctx)) {
|
|
1367
|
+
const typeName = recordRefName(ty.Record);
|
|
1368
|
+
return `serialize${typeName}(${expr} as ${recordInputName(ty.Record, ctx)}, ${contextExpr})`;
|
|
1369
|
+
}
|
|
1370
|
+
const external = externalRecordInfo(ty.Record, ctx);
|
|
1371
|
+
return external
|
|
1372
|
+
? `${external.serializerName}(${expr} as ${recordInputName(ty.Record, ctx)}, ${contextExpr})`
|
|
1373
|
+
: `BaseContract.serializeDynamicRecord(${expr}, ${contextExpr})`;
|
|
1374
|
+
}
|
|
1375
|
+
return `BaseContract.serializePlaintext(${expr}, ${contextExpr})`;
|
|
1376
|
+
}
|
|
1377
|
+
function serializePlaintextExpr(expr, ty, ctx, contextExpr = "undefined") {
|
|
1378
|
+
if ("Primitive" in ty)
|
|
1379
|
+
return serializePrimitive(expr, ty.Primitive, contextExpr);
|
|
1380
|
+
if ("Struct" in ty) {
|
|
1381
|
+
if (isLocalStructRef(ty.Struct, ctx)) {
|
|
1382
|
+
const typeName = structRefName(ty.Struct);
|
|
1383
|
+
return `serialize${typeName}(${expr} as ${structInputName(ty.Struct, ctx)}, ${contextExpr})`;
|
|
1384
|
+
}
|
|
1385
|
+
const external = externalStructInfo(ty.Struct, ctx);
|
|
1386
|
+
return external
|
|
1387
|
+
? `${external.serializerName}(${expr} as ${structInputName(ty.Struct, ctx)}, ${contextExpr})`
|
|
1388
|
+
: `BaseContract.serializePlaintext(${expr}, ${contextExpr})`;
|
|
1389
|
+
}
|
|
1390
|
+
if ("Array" in ty) {
|
|
1391
|
+
const [elemType] = ty.Array;
|
|
1392
|
+
const elemSer = serializePlaintextExpr("e", elemType, ctx, "context");
|
|
1393
|
+
return `BaseContract.serializeArray(${expr}, ${contextExpr}, (e: unknown, context: TransitionInputContext | undefined) => ${elemSer})`;
|
|
1394
|
+
}
|
|
1395
|
+
if ("Optional" in ty) {
|
|
1396
|
+
const innerSer = serializePlaintextExpr(expr, ty.Optional, ctx, contextExpr);
|
|
1397
|
+
const zero = zeroLeoValue(ty.Optional, ctx);
|
|
1398
|
+
if (zero !== null) {
|
|
1399
|
+
return `(${expr} != null ? "{ is_some: true, val: " + ${innerSer} + " }" : "{ is_some: false, val: ${zero} }")`;
|
|
1400
|
+
}
|
|
1401
|
+
return `(${expr} != null ? "{ is_some: true, val: " + ${innerSer} + " }" : BaseContract.serializeUnsupportedOptionalNone(${contextExpr}))`;
|
|
1402
|
+
}
|
|
1403
|
+
return `BaseContract.serializePlaintext(${expr}, ${contextExpr})`;
|
|
1404
|
+
}
|
|
1405
|
+
// ---------------------------------------------------------------------------
|
|
1406
|
+
// Deserialization expression generators (Leo string → JS value)
|
|
1407
|
+
// ---------------------------------------------------------------------------
|
|
1408
|
+
function deserializeOutputExpr(expr, ty, ctx) {
|
|
1409
|
+
if (ty === "DynamicRecord")
|
|
1410
|
+
return `BaseContract.parseDynamicRecord(${expr})`;
|
|
1411
|
+
if ("Plaintext" in ty)
|
|
1412
|
+
return deserializePlaintextExpr(expr, ty.Plaintext, ctx);
|
|
1413
|
+
if ("Record" in ty) {
|
|
1414
|
+
if (isLocalRecordRef(ty.Record, ctx))
|
|
1415
|
+
return `deserialize${recordRefName(ty.Record)}(${expr})`;
|
|
1416
|
+
const external = externalRecordInfo(ty.Record, ctx);
|
|
1417
|
+
return external
|
|
1418
|
+
? `${external.deserializerName}(${expr})`
|
|
1419
|
+
: `BaseContract.parseDynamicRecord(${expr})`;
|
|
1420
|
+
}
|
|
1421
|
+
if ("Future" in ty)
|
|
1422
|
+
return "undefined as any";
|
|
1423
|
+
return expr;
|
|
1424
|
+
}
|
|
1425
|
+
/**
|
|
1426
|
+
* Emit a `(plaintext: string) => T` function reference (or arrow) suitable
|
|
1427
|
+
* for passing as a deserializer callback — e.g. to
|
|
1428
|
+
* `BaseContract.makeEncryptedValue`. For primitive types we pass the
|
|
1429
|
+
* `BaseContract.parseXxx` method directly; for compound types we wrap in
|
|
1430
|
+
* an arrow so the deserialize logic stays at the callsite.
|
|
1431
|
+
*/
|
|
1432
|
+
function plaintextDeserializerFn(ty, ctx) {
|
|
1433
|
+
if ("Primitive" in ty) {
|
|
1434
|
+
const prim = ty.Primitive;
|
|
1435
|
+
if (typeof prim === "string") {
|
|
1436
|
+
switch (prim) {
|
|
1437
|
+
case "Address":
|
|
1438
|
+
return "BaseContract.parseAddress";
|
|
1439
|
+
case "Field":
|
|
1440
|
+
return "BaseContract.parseField";
|
|
1441
|
+
case "Group":
|
|
1442
|
+
return "BaseContract.parseGroup";
|
|
1443
|
+
case "Scalar":
|
|
1444
|
+
return "BaseContract.parseScalar";
|
|
1445
|
+
case "Identifier":
|
|
1446
|
+
return "BaseContract.parseIdentifier";
|
|
1447
|
+
case "Boolean":
|
|
1448
|
+
return "BaseContract.parseBoolean";
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
if (typeof prim === "object" && prim !== null && ("UInt" in prim || "Int" in prim)) {
|
|
1452
|
+
return isBigIntType(prim) ? "BaseContract.parseBigInt" : "BaseContract.parseNumber";
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
return `(_p: string) => ${deserializePlaintextExpr("_p", ty, ctx)}`;
|
|
1456
|
+
}
|
|
1457
|
+
function deserializePlaintextExpr(expr, ty, ctx) {
|
|
1458
|
+
if ("Primitive" in ty)
|
|
1459
|
+
return deserializePrimitiveExpr(expr, ty.Primitive);
|
|
1460
|
+
if ("Struct" in ty) {
|
|
1461
|
+
if (isLocalStructRef(ty.Struct, ctx))
|
|
1462
|
+
return `deserialize${structRefName(ty.Struct)}(${expr})`;
|
|
1463
|
+
const external = externalStructInfo(ty.Struct, ctx);
|
|
1464
|
+
return external
|
|
1465
|
+
? `${external.deserializerName}(${expr})`
|
|
1466
|
+
: `BaseContract.parsePlaintext(${expr})`;
|
|
1467
|
+
}
|
|
1468
|
+
if ("Array" in ty) {
|
|
1469
|
+
const [elemType] = ty.Array;
|
|
1470
|
+
return `BaseContract.parseArray(${expr}).map((e: string) => ${deserializePlaintextExpr("e", elemType, ctx)})`;
|
|
1471
|
+
}
|
|
1472
|
+
if ("Optional" in ty) {
|
|
1473
|
+
return `(() => { const _opt = BaseContract.parseStruct(${expr}); return BaseContract.parseBoolean(_opt["is_some"]!) ? ${deserializePlaintextExpr('_opt["val"]!', ty.Optional, ctx)} : null; })()`;
|
|
1474
|
+
}
|
|
1475
|
+
return expr;
|
|
1476
|
+
}
|
|
1477
|
+
function deserializeStorageExpr(expr, ty, ctx) {
|
|
1478
|
+
if ("Plaintext" in ty)
|
|
1479
|
+
return deserializePlaintextExpr(expr, ty.Plaintext, ctx);
|
|
1480
|
+
if ("Vector" in ty) {
|
|
1481
|
+
return `BaseContract.parseArray(${expr}).map((e: string) => ${deserializeStorageExpr("e", ty.Vector, ctx)})`;
|
|
1482
|
+
}
|
|
1483
|
+
return expr;
|
|
1484
|
+
}
|
|
1485
|
+
function deserializePrimitiveExpr(expr, prim) {
|
|
1486
|
+
if (typeof prim === "string") {
|
|
1487
|
+
switch (prim) {
|
|
1488
|
+
case "Address":
|
|
1489
|
+
return `BaseContract.parseAddress(${expr})`;
|
|
1490
|
+
case "Field":
|
|
1491
|
+
return `BaseContract.parseField(${expr})`;
|
|
1492
|
+
case "Group":
|
|
1493
|
+
return `BaseContract.parseGroup(${expr})`;
|
|
1494
|
+
case "Scalar":
|
|
1495
|
+
return `BaseContract.parseScalar(${expr})`;
|
|
1496
|
+
case "Identifier":
|
|
1497
|
+
return `BaseContract.parseIdentifier(${expr})`;
|
|
1498
|
+
case "Boolean":
|
|
1499
|
+
return `BaseContract.parseBoolean(${expr})`;
|
|
1500
|
+
}
|
|
1501
|
+
return expr;
|
|
1502
|
+
}
|
|
1503
|
+
if (typeof prim === "object" && prim !== null && ("UInt" in prim || "Int" in prim)) {
|
|
1504
|
+
if (isBigIntType(prim)) {
|
|
1505
|
+
return `BaseContract.parseBigInt(${expr})`;
|
|
1506
|
+
}
|
|
1507
|
+
return `BaseContract.parseNumber(${expr})`;
|
|
1508
|
+
}
|
|
1509
|
+
return expr;
|
|
1510
|
+
}
|
|
1511
|
+
function serializePrimitive(expr, prim, contextExpr = "undefined") {
|
|
1512
|
+
if (typeof prim === "string") {
|
|
1513
|
+
switch (prim) {
|
|
1514
|
+
case "Address":
|
|
1515
|
+
return `BaseContract.serializeAddress(${expr}, ${contextExpr})`;
|
|
1516
|
+
case "Field":
|
|
1517
|
+
return `BaseContract.serializeField(${expr}, ${contextExpr})`;
|
|
1518
|
+
case "Group":
|
|
1519
|
+
return `BaseContract.serializeGroup(${expr}, ${contextExpr})`;
|
|
1520
|
+
case "Scalar":
|
|
1521
|
+
return `BaseContract.serializeScalar(${expr}, ${contextExpr})`;
|
|
1522
|
+
case "Identifier":
|
|
1523
|
+
return `BaseContract.serializeIdentifier(${expr}, ${contextExpr})`;
|
|
1524
|
+
case "Boolean":
|
|
1525
|
+
return `BaseContract.serializeBoolean(${expr}, ${contextExpr})`;
|
|
1526
|
+
}
|
|
1527
|
+
return `BaseContract.serializePlaintext(${expr}, ${contextExpr})`;
|
|
1528
|
+
}
|
|
1529
|
+
if (typeof prim === "object" && prim !== null && "UInt" in prim) {
|
|
1530
|
+
const bits = Number(prim.UInt.slice(1));
|
|
1531
|
+
return `BaseContract.serializeUInt(${expr}, ${bits}, ${contextExpr})`;
|
|
1532
|
+
}
|
|
1533
|
+
if (typeof prim === "object" && prim !== null && "Int" in prim) {
|
|
1534
|
+
const bits = Number(prim.Int.slice(1));
|
|
1535
|
+
return `BaseContract.serializeInt(${expr}, ${bits}, ${contextExpr})`;
|
|
1536
|
+
}
|
|
1537
|
+
return `BaseContract.serializePlaintext(${expr}, ${contextExpr})`;
|
|
1538
|
+
}
|
|
1539
|
+
// ---------------------------------------------------------------------------
|
|
1540
|
+
// Zero-value helpers (for Optional None serialization)
|
|
1541
|
+
// ---------------------------------------------------------------------------
|
|
1542
|
+
function zeroLeoValue(ty, ctx, seen = new Set()) {
|
|
1543
|
+
if ("Primitive" in ty) {
|
|
1544
|
+
const prim = ty.Primitive;
|
|
1545
|
+
if (typeof prim === "string") {
|
|
1546
|
+
switch (prim) {
|
|
1547
|
+
case "Address":
|
|
1548
|
+
return "aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc";
|
|
1549
|
+
case "Boolean":
|
|
1550
|
+
return "false";
|
|
1551
|
+
case "Field":
|
|
1552
|
+
return "0field";
|
|
1553
|
+
case "Group":
|
|
1554
|
+
return "0group";
|
|
1555
|
+
case "Identifier":
|
|
1556
|
+
// Leo has no canonical zero identifier; Optional::None ignores val.
|
|
1557
|
+
return "'lionden_zero'";
|
|
1558
|
+
case "Scalar":
|
|
1559
|
+
return "0scalar";
|
|
1560
|
+
}
|
|
1561
|
+
return null;
|
|
1562
|
+
}
|
|
1563
|
+
if (typeof prim === "object" && prim !== null && "UInt" in prim)
|
|
1564
|
+
return `0${prim.UInt.toLowerCase()}`;
|
|
1565
|
+
if (typeof prim === "object" && prim !== null && "Int" in prim)
|
|
1566
|
+
return `0${prim.Int.toLowerCase()}`;
|
|
1567
|
+
}
|
|
1568
|
+
if ("Array" in ty) {
|
|
1569
|
+
const [elemType, length] = ty.Array;
|
|
1570
|
+
const elemZero = zeroLeoValue(elemType, ctx, seen);
|
|
1571
|
+
if (elemZero === null)
|
|
1572
|
+
return null;
|
|
1573
|
+
return `[${Array.from({ length }, () => elemZero).join(", ")}]`;
|
|
1574
|
+
}
|
|
1575
|
+
if ("Optional" in ty) {
|
|
1576
|
+
const innerZero = zeroLeoValue(ty.Optional, ctx, seen);
|
|
1577
|
+
if (innerZero === null)
|
|
1578
|
+
return null;
|
|
1579
|
+
return `{ is_some: false, val: ${innerZero} }`;
|
|
1580
|
+
}
|
|
1581
|
+
if ("Struct" in ty) {
|
|
1582
|
+
if (!isLocalStructRef(ty.Struct, ctx))
|
|
1583
|
+
return null;
|
|
1584
|
+
const key = pathKey(ty.Struct.path);
|
|
1585
|
+
if (seen.has(key))
|
|
1586
|
+
return null;
|
|
1587
|
+
const struct = ctx.structsByKey.get(key);
|
|
1588
|
+
if (!struct)
|
|
1589
|
+
return null;
|
|
1590
|
+
const nextSeen = new Set(seen);
|
|
1591
|
+
nextSeen.add(key);
|
|
1592
|
+
const fieldValues = [];
|
|
1593
|
+
for (const field of struct.fields) {
|
|
1594
|
+
const fieldZero = zeroLeoValue(field.ty, ctx, nextSeen);
|
|
1595
|
+
if (fieldZero === null)
|
|
1596
|
+
return null;
|
|
1597
|
+
fieldValues.push(`${field.name}: ${fieldZero}`);
|
|
1598
|
+
}
|
|
1599
|
+
return `{ ${fieldValues.join(", ")} }`;
|
|
1600
|
+
}
|
|
1601
|
+
return null;
|
|
1602
|
+
}
|
|
1603
|
+
function generateExternalImports(ctx) {
|
|
1604
|
+
const importsByProgram = new Map();
|
|
1605
|
+
for (const ref of ctx.externalStructRefs.values()) {
|
|
1606
|
+
const info = externalStructInfo(ref, ctx);
|
|
1607
|
+
if (!info)
|
|
1608
|
+
continue;
|
|
1609
|
+
const imports = importsByProgram.get(info.programId) ?? new Set();
|
|
1610
|
+
imports.add(`type ${info.baseName} as ${info.typeName}`);
|
|
1611
|
+
imports.add(`serialize${info.baseName} as ${info.serializerName}`);
|
|
1612
|
+
imports.add(`deserialize${info.baseName} as ${info.deserializerName}`);
|
|
1613
|
+
importsByProgram.set(info.programId, imports);
|
|
1614
|
+
}
|
|
1615
|
+
// External record types: alias the imported type under a private `_`-prefixed
|
|
1616
|
+
// name so we can re-export the public name as both a type alias and a value
|
|
1617
|
+
// binding (carrying `.output`).
|
|
1618
|
+
const externalRecords = [];
|
|
1619
|
+
for (const ref of ctx.externalRecordRefs.values()) {
|
|
1620
|
+
const info = externalRecordInfo(ref, ctx);
|
|
1621
|
+
if (!info)
|
|
1622
|
+
continue;
|
|
1623
|
+
externalRecords.push(info);
|
|
1624
|
+
const imports = importsByProgram.get(info.programId) ?? new Set();
|
|
1625
|
+
imports.add(`type ${info.baseName} as _${info.typeName}`);
|
|
1626
|
+
imports.add(`serialize${info.baseName} as ${info.serializerName}`);
|
|
1627
|
+
imports.add(`deserialize${info.baseName} as ${info.deserializerName}`);
|
|
1628
|
+
importsByProgram.set(info.programId, imports);
|
|
1629
|
+
}
|
|
1630
|
+
const importLines = [...importsByProgram.entries()]
|
|
1631
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
1632
|
+
.map(([programId, imports]) => `import { ${[...imports].sort().join(", ")} } from "./${programIdToClassName(programId)}.js";`);
|
|
1633
|
+
// Re-export each external record's type alias publicly, and emit a same-named
|
|
1634
|
+
// value binding carrying the `.output` matcher. The merged type + value
|
|
1635
|
+
// pair lets callers write both `IdOnlyExternalRecordHandle<GoldToken_Token>`
|
|
1636
|
+
// (type position) and `GoldToken_Token.output` (value position).
|
|
1637
|
+
const valueLines = [];
|
|
1638
|
+
for (const info of externalRecords.sort((a, b) => a.typeName.localeCompare(b.typeName))) {
|
|
1639
|
+
valueLines.push(`export type ${info.typeName} = _${info.typeName};`);
|
|
1640
|
+
valueLines.push(`export const ${info.typeName} = {`);
|
|
1641
|
+
valueLines.push(` output: createRecordOutputMatcher<_${info.typeName}>({`);
|
|
1642
|
+
valueLines.push(` program: "${info.programId}",`);
|
|
1643
|
+
valueLines.push(` recordName: "${info.baseName}",`);
|
|
1644
|
+
valueLines.push(` deserialize: ${info.deserializerName},`);
|
|
1645
|
+
valueLines.push(` }),`);
|
|
1646
|
+
valueLines.push("};");
|
|
1647
|
+
}
|
|
1648
|
+
// Widened input aliases for external struct/record refs. Local types get
|
|
1649
|
+
// explicit `${Name}Input` interfaces; external refs reuse the imported branded
|
|
1650
|
+
// type through `WidenInput<…>` so no cross-program `Input` import is needed.
|
|
1651
|
+
// Emitted for both struct and record refs (so struct-only programs still get
|
|
1652
|
+
// them — hence no early return before this block).
|
|
1653
|
+
const aliases = [];
|
|
1654
|
+
for (const ref of ctx.externalStructRefs.values()) {
|
|
1655
|
+
const info = externalStructInfo(ref, ctx);
|
|
1656
|
+
if (info)
|
|
1657
|
+
aliases.push({ alias: structInputName(ref, ctx), typeName: info.typeName });
|
|
1658
|
+
}
|
|
1659
|
+
for (const ref of ctx.externalRecordRefs.values()) {
|
|
1660
|
+
const info = externalRecordInfo(ref, ctx);
|
|
1661
|
+
if (info)
|
|
1662
|
+
aliases.push({ alias: recordInputName(ref, ctx), typeName: info.typeName });
|
|
1663
|
+
}
|
|
1664
|
+
const aliasLines = aliases
|
|
1665
|
+
.sort((a, b) => a.alias.localeCompare(b.alias))
|
|
1666
|
+
.map(({ alias, typeName }) => `export type ${alias} = ${ctx.widenInputAlias}<${typeName}>;`);
|
|
1667
|
+
const tail = [];
|
|
1668
|
+
if (valueLines.length > 0)
|
|
1669
|
+
tail.push("", ...valueLines);
|
|
1670
|
+
if (aliasLines.length > 0)
|
|
1671
|
+
tail.push("", ...aliasLines);
|
|
1672
|
+
return [...importLines, ...tail];
|
|
1673
|
+
}
|
|
1674
|
+
function isLocalStructRef(ref, ctx) {
|
|
1675
|
+
if (ref.program !== null && ref.program !== ctx.programId)
|
|
1676
|
+
return false;
|
|
1677
|
+
return ctx.structsByKey.has(pathKey(ref.path));
|
|
1678
|
+
}
|
|
1679
|
+
function isLocalRecordRef(ref, ctx) {
|
|
1680
|
+
if (ref.program !== null && ref.program !== ctx.programId)
|
|
1681
|
+
return false;
|
|
1682
|
+
return ctx.recordsByKey.has(pathKey(ref.path));
|
|
1683
|
+
}
|
|
1684
|
+
function externalStructInfo(ref, ctx) {
|
|
1685
|
+
const programId = ref.program;
|
|
1686
|
+
if (!programId || programId === ctx.programId)
|
|
1687
|
+
return null;
|
|
1688
|
+
return ctx.externalInfoByKey.get(externalRefKey(ref)) ?? null;
|
|
1689
|
+
}
|
|
1690
|
+
function externalRecordInfo(ref, ctx) {
|
|
1691
|
+
const programId = ref.program;
|
|
1692
|
+
if (!programId || programId === ctx.programId)
|
|
1693
|
+
return null;
|
|
1694
|
+
return ctx.externalInfoByKey.get(externalRefKey(ref)) ?? null;
|
|
1695
|
+
}
|
|
1696
|
+
function pathKey(path) {
|
|
1697
|
+
return path.join("::");
|
|
1698
|
+
}
|
|
1699
|
+
function externalRefKey(ref) {
|
|
1700
|
+
return `${ref.program ?? ""}:${pathKey(ref.path)}`;
|
|
1701
|
+
}
|
|
1702
|
+
/**
|
|
1703
|
+
* Reserved words that an ABI input name must not become a generated **function
|
|
1704
|
+
* parameter**. Object keys tolerate anything; identifiers do not. Two groups:
|
|
1705
|
+
*
|
|
1706
|
+
* - Method-scope locals the generated body declares (`options`, `_args`,
|
|
1707
|
+
* `_result`, `_decoded`) — a param sharing one of these names redeclares the
|
|
1708
|
+
* local (TS2451) or shadows the trailing `options` param.
|
|
1709
|
+
* - The ECMAScript reserved-word set (keywords, strict-mode reserved words,
|
|
1710
|
+
* and the strict-mode restricted binding names `eval`/`arguments`) — illegal
|
|
1711
|
+
* or unsafe as a binding name in the strict-by-default ESM output.
|
|
1712
|
+
*
|
|
1713
|
+
* Names that hit this set (or are not valid identifiers) fall back to the
|
|
1714
|
+
* always-safe `arg${index}`; see {@link safeParamName}.
|
|
1715
|
+
*/
|
|
1716
|
+
const RESERVED_PARAM_WORDS = new Set([
|
|
1717
|
+
// method-scope locals the generated body declares
|
|
1718
|
+
"options",
|
|
1719
|
+
"_args",
|
|
1720
|
+
"_result",
|
|
1721
|
+
"_decoded",
|
|
1722
|
+
// ECMAScript keywords
|
|
1723
|
+
"break",
|
|
1724
|
+
"case",
|
|
1725
|
+
"catch",
|
|
1726
|
+
"class",
|
|
1727
|
+
"const",
|
|
1728
|
+
"continue",
|
|
1729
|
+
"debugger",
|
|
1730
|
+
"default",
|
|
1731
|
+
"delete",
|
|
1732
|
+
"do",
|
|
1733
|
+
"else",
|
|
1734
|
+
"enum",
|
|
1735
|
+
"export",
|
|
1736
|
+
"extends",
|
|
1737
|
+
"false",
|
|
1738
|
+
"finally",
|
|
1739
|
+
"for",
|
|
1740
|
+
"function",
|
|
1741
|
+
"if",
|
|
1742
|
+
"import",
|
|
1743
|
+
"in",
|
|
1744
|
+
"instanceof",
|
|
1745
|
+
"new",
|
|
1746
|
+
"null",
|
|
1747
|
+
"return",
|
|
1748
|
+
"super",
|
|
1749
|
+
"switch",
|
|
1750
|
+
"this",
|
|
1751
|
+
"throw",
|
|
1752
|
+
"true",
|
|
1753
|
+
"try",
|
|
1754
|
+
"typeof",
|
|
1755
|
+
"var",
|
|
1756
|
+
"void",
|
|
1757
|
+
"while",
|
|
1758
|
+
"with",
|
|
1759
|
+
// strict-mode future reserved words
|
|
1760
|
+
"implements",
|
|
1761
|
+
"interface",
|
|
1762
|
+
"let",
|
|
1763
|
+
"package",
|
|
1764
|
+
"private",
|
|
1765
|
+
"protected",
|
|
1766
|
+
"public",
|
|
1767
|
+
"static",
|
|
1768
|
+
"yield",
|
|
1769
|
+
// async/await context
|
|
1770
|
+
"async",
|
|
1771
|
+
"await",
|
|
1772
|
+
// strict-mode restricted binding names
|
|
1773
|
+
"eval",
|
|
1774
|
+
"arguments",
|
|
1775
|
+
]);
|
|
1776
|
+
/** True when `name` is a syntactically valid (ASCII) JS identifier. */
|
|
1777
|
+
function isValidJsIdentifier(name) {
|
|
1778
|
+
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
|
|
1779
|
+
}
|
|
1780
|
+
/**
|
|
1781
|
+
* Map an ABI input name to a legal, unique TypeScript parameter identifier.
|
|
1782
|
+
*
|
|
1783
|
+
* A real (non-synthesized) Leo name can land in the parameter position
|
|
1784
|
+
* (`parseAbi` preserves 4.1/internal names verbatim), so an invalid identifier
|
|
1785
|
+
* or reserved word must be remapped rather than emitted literally. Synthesized
|
|
1786
|
+
* `arg{i}` names (the 4.2 default) pass straight through. `reserved` is the
|
|
1787
|
+
* per-transition set of already-claimed identifiers; mutated to record the
|
|
1788
|
+
* returned name so the param list stays collision-free.
|
|
1789
|
+
*/
|
|
1790
|
+
function safeParamName(index, name, reserved) {
|
|
1791
|
+
let candidate = isValidJsIdentifier(name) && !RESERVED_PARAM_WORDS.has(name) ? name : `arg${index}`;
|
|
1792
|
+
while (reserved.has(candidate))
|
|
1793
|
+
candidate += "_";
|
|
1794
|
+
reserved.add(candidate);
|
|
1795
|
+
return candidate;
|
|
1796
|
+
}
|
|
1797
|
+
/**
|
|
1798
|
+
* Per-transition map from each input's original ABI name to the safe identifier
|
|
1799
|
+
* used for its generated parameter and in-body read expression. The original
|
|
1800
|
+
* name is still used verbatim for `inputContext(...)` labels.
|
|
1801
|
+
*/
|
|
1802
|
+
function buildSafeParamNames(inputs) {
|
|
1803
|
+
const reserved = new Set();
|
|
1804
|
+
const safeNames = new Map();
|
|
1805
|
+
inputs.forEach((input, index) => {
|
|
1806
|
+
safeNames.set(input.name, safeParamName(index, input.name, reserved));
|
|
1807
|
+
});
|
|
1808
|
+
return safeNames;
|
|
1809
|
+
}
|
|
1810
|
+
function formatTransitionMethodParams(inputs, ctx, safeNames, optionsType) {
|
|
1811
|
+
const params = inputs.map((input) => `${safeNames.get(input.name)}: ${aleoTypeToInputBindingTs(input.ty, ctx)}`);
|
|
1812
|
+
params.push(`options?: ${optionsType}`);
|
|
1813
|
+
return params.join(", ");
|
|
1814
|
+
}
|
|
1815
|
+
function formatReturnType(outputs, ctx) {
|
|
1816
|
+
if (outputs.length === 0)
|
|
1817
|
+
return "void";
|
|
1818
|
+
if (outputs.length === 1)
|
|
1819
|
+
return aleoTypeToOutputBindingTs(outputs[0].ty, ctx);
|
|
1820
|
+
return `[${outputs.map((o) => aleoTypeToOutputBindingTs(o.ty, ctx)).join(", ")}]`;
|
|
1821
|
+
}
|
|
1822
|
+
/**
|
|
1823
|
+
* Typed `outputs` field shape for on-chain results. Mirrors `formatReturnType`'s
|
|
1824
|
+
* arity rule, with two substitutions:
|
|
1825
|
+
* - Record types (local + imported) and DynamicRecord → `EncryptedRecord<T>`.
|
|
1826
|
+
* - Private / default-private plaintext outputs (Aleo emits these as value
|
|
1827
|
+
* ciphertexts on chain) → `EncryptedValue<T>`.
|
|
1828
|
+
* Public plaintext outputs keep their decoded type.
|
|
1829
|
+
* Future entries are dropped from the result shape (they still occupy
|
|
1830
|
+
* positions in rawOutputs).
|
|
1831
|
+
*/
|
|
1832
|
+
function formatTypedOutputType(outputs, ctx) {
|
|
1833
|
+
const visible = outputs.filter((o) => !isFutureOutput(o.ty));
|
|
1834
|
+
if (visible.length === 0)
|
|
1835
|
+
return "void";
|
|
1836
|
+
if (visible.length === 1)
|
|
1837
|
+
return typedOutputElementType(visible[0], ctx);
|
|
1838
|
+
return `[${visible.map((o) => typedOutputElementType(o, ctx)).join(", ")}]`;
|
|
1839
|
+
}
|
|
1840
|
+
function isFutureOutput(ty) {
|
|
1841
|
+
return typeof ty === "object" && ty !== null && "Future" in ty;
|
|
1842
|
+
}
|
|
1843
|
+
/**
|
|
1844
|
+
* A plaintext output appears as a value ciphertext on chain when its
|
|
1845
|
+
* visibility is not explicitly `Public`. When no visibility modifier was
|
|
1846
|
+
* written, the parser canonicalizes the mode to `Private` (older Leo ABIs
|
|
1847
|
+
* emitted `mode: "None"`, which collapsed to the same default). `Private` and
|
|
1848
|
+
* `Constant` both produce `ciphertext1...` on chain; only `Public` does not.
|
|
1849
|
+
*/
|
|
1850
|
+
function isPrivatePlaintextOutput(output) {
|
|
1851
|
+
const ty = output.ty;
|
|
1852
|
+
if (typeof ty !== "object" || ty === null || !("Plaintext" in ty))
|
|
1853
|
+
return false;
|
|
1854
|
+
return output.mode !== "Public";
|
|
1855
|
+
}
|
|
1856
|
+
function typedOutputElementType(output, ctx) {
|
|
1857
|
+
const ty = output.ty;
|
|
1858
|
+
if (ty === "DynamicRecord")
|
|
1859
|
+
return "IdOnlyDynamicRecordHandle";
|
|
1860
|
+
if (typeof ty === "object" && ty !== null && "Record" in ty) {
|
|
1861
|
+
if (isLocalRecordRef(ty.Record, ctx)) {
|
|
1862
|
+
return `EncryptedRecord<${recordRefName(ty.Record)}>`;
|
|
1863
|
+
}
|
|
1864
|
+
const external = externalRecordInfo(ty.Record, ctx);
|
|
1865
|
+
return external
|
|
1866
|
+
? `IdOnlyExternalRecordHandle<${external.typeName}>`
|
|
1867
|
+
: "IdOnlyExternalRecordHandle<LeoDynamicRecord>";
|
|
1868
|
+
}
|
|
1869
|
+
if (typeof ty === "object" && ty !== null && "Plaintext" in ty) {
|
|
1870
|
+
const decoded = plaintextToOutputBindingTs(ty.Plaintext, ctx);
|
|
1871
|
+
return isPrivatePlaintextOutput(output) ? `EncryptedValue<${decoded}>` : decoded;
|
|
1872
|
+
}
|
|
1873
|
+
return "unknown";
|
|
1874
|
+
}
|
|
1875
|
+
/**
|
|
1876
|
+
* Emit the projector function literal passed to settleTyped / expectAcceptedTyped.
|
|
1877
|
+
* Indexes rawOutputs by ORIGINAL ABI position (Future entries reserve their slot
|
|
1878
|
+
* in rawOutputs but contribute nothing to the typed result shape).
|
|
1879
|
+
*
|
|
1880
|
+
* Signature is `(rawOutputs, tpk) => TOutputs` regardless of whether `tpk` is
|
|
1881
|
+
* consumed. When the transition has at least one private plaintext output
|
|
1882
|
+
* (decoded as `EncryptedValue<T>` and requiring `tpk`), the parameter name is
|
|
1883
|
+
* `tpk`. Otherwise it's `_tpk` to keep `noUnusedParameters`-style checks quiet.
|
|
1884
|
+
*/
|
|
1885
|
+
function formatProjectorExpr(transition, programId, sourceProgramExpr, runtimeProgramExpr, ctx) {
|
|
1886
|
+
const visibleIndices = [];
|
|
1887
|
+
transition.outputs.forEach((output, idx) => {
|
|
1888
|
+
if (!isFutureOutput(output.ty))
|
|
1889
|
+
visibleIndices.push(idx);
|
|
1890
|
+
});
|
|
1891
|
+
const transitionName = transition.name;
|
|
1892
|
+
const hasPrivatePlaintext = transition.outputs.some(isPrivatePlaintextOutput);
|
|
1893
|
+
const tpkParam = hasPrivatePlaintext ? "tpk" : "_tpk";
|
|
1894
|
+
const usesTransitions = transition.outputs.some((o) => projectorElementUsesTransitions(o, ctx));
|
|
1895
|
+
const transitionsParam = usesTransitions ? "transitions" : "_transitions";
|
|
1896
|
+
const inputCount = transition.inputs.length;
|
|
1897
|
+
if (visibleIndices.length === 0) {
|
|
1898
|
+
return `(_rawOutputs: readonly RawTransitionOutput[], ${tpkParam}: string, ${transitionsParam}: readonly ConfirmedTransitionRecord[]) => undefined as void`;
|
|
1899
|
+
}
|
|
1900
|
+
const rawAccess = (abiIndex) => `BaseContract.rawOutputAt(rawOutputs, ${runtimeProgramExpr}, "${transitionName}", ${abiIndex})`;
|
|
1901
|
+
const decodeForIndex = (abiIndex) => {
|
|
1902
|
+
const output = transition.outputs[abiIndex];
|
|
1903
|
+
const access = rawAccess(abiIndex);
|
|
1904
|
+
return projectorElementExpr(access, output, sourceProgramExpr, runtimeProgramExpr, transitionName, abiIndex, inputCount, ctx);
|
|
1905
|
+
};
|
|
1906
|
+
if (visibleIndices.length === 1) {
|
|
1907
|
+
const abiIndex = visibleIndices[0];
|
|
1908
|
+
return `(rawOutputs: readonly RawTransitionOutput[], ${tpkParam}: string, ${transitionsParam}: readonly ConfirmedTransitionRecord[]) => ${decodeForIndex(abiIndex)}`;
|
|
1909
|
+
}
|
|
1910
|
+
const tupleType = formatTypedOutputType(transition.outputs, ctx);
|
|
1911
|
+
const elems = visibleIndices.map(decodeForIndex);
|
|
1912
|
+
return `(rawOutputs: readonly RawTransitionOutput[], ${tpkParam}: string, ${transitionsParam}: readonly ConfirmedTransitionRecord[]) => ([${elems.join(", ")}] as ${tupleType})`;
|
|
1913
|
+
}
|
|
1914
|
+
/**
|
|
1915
|
+
* Whether the projector element for this output references the `transitions`
|
|
1916
|
+
* parameter — true for `dyn record` and any external `Record` (both id-only
|
|
1917
|
+
* constructors close over `transitions`). Local concrete records and
|
|
1918
|
+
* plaintext outputs don't reference `transitions`.
|
|
1919
|
+
*/
|
|
1920
|
+
function projectorElementUsesTransitions(output, ctx) {
|
|
1921
|
+
const ty = output.ty;
|
|
1922
|
+
if (ty === "DynamicRecord")
|
|
1923
|
+
return true;
|
|
1924
|
+
if (typeof ty === "object" && ty !== null && "Record" in ty) {
|
|
1925
|
+
return !isLocalRecordRef(ty.Record, ctx);
|
|
1926
|
+
}
|
|
1927
|
+
return false;
|
|
1928
|
+
}
|
|
1929
|
+
function projectorElementExpr(rawExpr, output, sourceProgramExpr, runtimeProgramExpr, transitionName, abiIndex, inputCount, ctx) {
|
|
1930
|
+
const ty = output.ty;
|
|
1931
|
+
const idOnlyAccess = `BaseContract.idOnlyRecordOutputAt(rawOutputs, ${runtimeProgramExpr}, "${transitionName}", ${abiIndex})`;
|
|
1932
|
+
if (ty === "DynamicRecord") {
|
|
1933
|
+
return `BaseContract.makeIdOnlyDynamicRecordHandle(${idOnlyAccess}, transitions, ${sourceProgramExpr}, ${runtimeProgramExpr})`;
|
|
1934
|
+
}
|
|
1935
|
+
if (typeof ty === "object" && ty !== null && "Record" in ty) {
|
|
1936
|
+
if (isLocalRecordRef(ty.Record, ctx)) {
|
|
1937
|
+
return `BaseContract.makeEncryptedRecord(${runtimeProgramExpr}, "${recordRefName(ty.Record)}", ${rawExpr}, deserialize${recordRefName(ty.Record)}, ${sourceProgramExpr})`;
|
|
1938
|
+
}
|
|
1939
|
+
const external = externalRecordInfo(ty.Record, ctx);
|
|
1940
|
+
const typeArg = external?.typeName ?? "LeoDynamicRecord";
|
|
1941
|
+
return `BaseContract.makeIdOnlyExternalRecordHandle<${typeArg}>(${idOnlyAccess}, transitions, ${sourceProgramExpr}, ${runtimeProgramExpr})`;
|
|
1942
|
+
}
|
|
1943
|
+
if (typeof ty === "object" && ty !== null && "Plaintext" in ty) {
|
|
1944
|
+
if (isPrivatePlaintextOutput(output)) {
|
|
1945
|
+
// Global index = inputs.length + outputAbiIndex. Aleo's domain
|
|
1946
|
+
// separation places inputs first; verified by Step 0 devnode decrypt.
|
|
1947
|
+
const globalIndex = inputCount + abiIndex;
|
|
1948
|
+
const deserializer = plaintextDeserializerFn(ty.Plaintext, ctx);
|
|
1949
|
+
return `BaseContract.makeEncryptedValue(${rawExpr}, tpk, ${runtimeProgramExpr}, "${transitionName}", ${globalIndex}, ${deserializer})`;
|
|
1950
|
+
}
|
|
1951
|
+
return deserializePlaintextExpr(rawExpr, ty.Plaintext, ctx);
|
|
1952
|
+
}
|
|
1953
|
+
return rawExpr;
|
|
1954
|
+
}
|
|
1955
|
+
export function programIdToClassName(programId) {
|
|
1956
|
+
const name = programId.replace(/\.aleo$/, "");
|
|
1957
|
+
return name
|
|
1958
|
+
.split(/[_\-.]/)
|
|
1959
|
+
.map(capitalize)
|
|
1960
|
+
.join("");
|
|
1961
|
+
}
|
|
1962
|
+
/**
|
|
1963
|
+
* Typechain file stems the emitter always writes besides per-program modules.
|
|
1964
|
+
* A program whose class name equals one of these would overwrite that file.
|
|
1965
|
+
*/
|
|
1966
|
+
const RESERVED_TYPECHAIN_FILE_STEMS = ["BaseContract"];
|
|
1967
|
+
/**
|
|
1968
|
+
* Assert that every program id maps to a distinct typechain module file
|
|
1969
|
+
* (`${programIdToClassName(id)}.ts`) and that none collides with a reserved
|
|
1970
|
+
* emitter file (`BaseContract.ts`).
|
|
1971
|
+
*
|
|
1972
|
+
* `programIdToClassName` is non-injective — it splits on `[_\-.]` and
|
|
1973
|
+
* CamelCases — so e.g. `foo_bar.aleo` and `foo__bar.aleo` both yield `FooBar`,
|
|
1974
|
+
* and `base_contract.aleo` yields `BaseContract`. The per-program emit loop
|
|
1975
|
+
* writes `${stem}.ts` with no cross-program dedup, so a collision silently
|
|
1976
|
+
* overwrites another program's bindings (or the runtime `BaseContract.ts`),
|
|
1977
|
+
* leaving the generated module set internally inconsistent.
|
|
1978
|
+
*
|
|
1979
|
+
* Comparison is case-insensitive: the common dev filesystems (macOS APFS,
|
|
1980
|
+
* Windows NTFS) are case-insensitive, so two programs whose class names differ
|
|
1981
|
+
* only by case (e.g. `ab.aleo` → `Ab`, `a_b.aleo` → `AB`) would share one
|
|
1982
|
+
* file. This guard turns any such collision into a clear build-time
|
|
1983
|
+
* `CodegenError` instead.
|
|
1984
|
+
*/
|
|
1985
|
+
export function assertTypechainModuleNamesUnique(programIds) {
|
|
1986
|
+
// Keyed by lower-cased stem (case-insensitive FS); value preserves the
|
|
1987
|
+
// original casing for the error message.
|
|
1988
|
+
const reserved = new Map(RESERVED_TYPECHAIN_FILE_STEMS.map((stem) => [stem.toLowerCase(), stem]));
|
|
1989
|
+
const seen = new Map(); // lower stem -> first program id claiming it
|
|
1990
|
+
for (const programId of programIds) {
|
|
1991
|
+
const stem = programIdToClassName(programId);
|
|
1992
|
+
const key = stem.toLowerCase();
|
|
1993
|
+
const reservedStem = reserved.get(key);
|
|
1994
|
+
if (reservedStem !== undefined) {
|
|
1995
|
+
throw new CodegenError(`Program '${programId}' generates typechain/${stem}.ts, which collides with the reserved generated file '${reservedStem}.ts' (file names are compared case-insensitively). Rename the program (its id maps to the class name '${stem}').`, { programId, fileStem: stem, reservedFile: reservedStem, phase: "generate" });
|
|
1996
|
+
}
|
|
1997
|
+
const existing = seen.get(key);
|
|
1998
|
+
if (existing !== undefined) {
|
|
1999
|
+
throw new CodegenError(`Programs '${existing}' and '${programId}' both generate typechain/${stem}.ts (file names are compared case-insensitively): their program ids map to the same module file. Rename one of them so each program maps to a distinct typechain module.`, { programId, conflictsWith: existing, fileStem: stem, phase: "generate" });
|
|
2000
|
+
}
|
|
2001
|
+
seen.set(key, programId);
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
/**
|
|
2005
|
+
* Derive a class name that does not collide with struct/record interface names
|
|
2006
|
+
* or the BaseContract imports emitted for this module. The latter also keeps
|
|
2007
|
+
* the `create${class}` factory clear of the imported `createRecordOutputMatcher`
|
|
2008
|
+
* (e.g. `record_output_matcher.aleo` → `RecordOutputMatcherContract`).
|
|
2009
|
+
*/
|
|
2010
|
+
export function resolveContractClassName(abi, options = {}) {
|
|
2011
|
+
const base = programIdToClassName(abi.program);
|
|
2012
|
+
const typeNames = new Set([
|
|
2013
|
+
...reservedBaseContractImportNames(options.includeLeoValueImport ?? false),
|
|
2014
|
+
...abi.structs.map((s) => pathToTsName(s.path)),
|
|
2015
|
+
...abi.records.map((r) => pathToTsName(r.path)),
|
|
2016
|
+
]);
|
|
2017
|
+
let candidate = base;
|
|
2018
|
+
while (typeNames.has(candidate)) {
|
|
2019
|
+
candidate += "Contract";
|
|
2020
|
+
}
|
|
2021
|
+
return candidate;
|
|
2022
|
+
}
|
|
2023
|
+
function capitalize(s) {
|
|
2024
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
2025
|
+
}
|
|
2026
|
+
function isValidIdentifier(name) {
|
|
2027
|
+
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
|
|
2028
|
+
}
|
|
2029
|
+
/**
|
|
2030
|
+
* snake_case -> camelCase for generated state property names. Leading underscores are
|
|
2031
|
+
* preserved (`_internal` -> `_internal`); only internal `_x` boundaries are camelCased.
|
|
2032
|
+
*/
|
|
2033
|
+
function toCamelCase(name) {
|
|
2034
|
+
const lead = /^_+/.exec(name)?.[0] ?? "";
|
|
2035
|
+
const rest = name.slice(lead.length);
|
|
2036
|
+
const camel = rest.replace(/_+([a-zA-Z0-9])/g, (_, c) => c.toUpperCase());
|
|
2037
|
+
return lead + camel;
|
|
2038
|
+
}
|
|
2039
|
+
/**
|
|
2040
|
+
* Maps each mapping's original (Leo) name to the property key to emit on the
|
|
2041
|
+
* generated `mappings` object. Collision-safe: if two mappings camelCase to the
|
|
2042
|
+
* same key, every member of that collision group is emitted under its original
|
|
2043
|
+
* Leo name (quoted) so no two mappings produce a duplicate object key.
|
|
2044
|
+
*/
|
|
2045
|
+
function buildStatePropKeys(entries) {
|
|
2046
|
+
const groups = new Map(); // camelName -> original names
|
|
2047
|
+
for (const entry of entries) {
|
|
2048
|
+
const camel = toCamelCase(entry.name);
|
|
2049
|
+
const originals = groups.get(camel) ?? [];
|
|
2050
|
+
originals.push(entry.name);
|
|
2051
|
+
groups.set(camel, originals);
|
|
2052
|
+
}
|
|
2053
|
+
const propKeys = new Map(); // original name -> emitted key token
|
|
2054
|
+
for (const [camel, originals] of groups) {
|
|
2055
|
+
if (originals.length > 1) {
|
|
2056
|
+
for (const original of originals) {
|
|
2057
|
+
propKeys.set(original, JSON.stringify(original));
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
else {
|
|
2061
|
+
const original = originals[0];
|
|
2062
|
+
propKeys.set(original, isValidIdentifier(camel) ? camel : JSON.stringify(camel));
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
return propKeys;
|
|
2066
|
+
}
|
|
2067
|
+
function buildMappingPropKeys(mappings) {
|
|
2068
|
+
return buildStatePropKeys(mappings);
|
|
2069
|
+
}
|
|
2070
|
+
function buildStoragePropKeys(storageVariables) {
|
|
2071
|
+
return buildStatePropKeys(storageVariables);
|
|
2072
|
+
}
|
|
2073
|
+
function indentLines(lines, indent) {
|
|
2074
|
+
return lines.map((line) => (line === "" ? "" : `${indent}${line}`));
|
|
2075
|
+
}
|
|
2076
|
+
//# sourceMappingURL=typescript-generator.js.map
|