@givelotus/compiler 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +331 -2
  2. package/artifact-v2.schema.json +58 -0
  3. package/artifact.schema.json +19 -0
  4. package/dist/ast.d.ts +292 -0
  5. package/dist/ast.js +150 -0
  6. package/dist/bindings.d.ts +6 -0
  7. package/dist/bindings.js +134 -0
  8. package/dist/call-runtime.d.ts +84 -0
  9. package/dist/call-runtime.js +249 -0
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.js +22 -0
  12. package/dist/compiler.d.ts +79 -0
  13. package/dist/compiler.js +125 -0
  14. package/dist/diagnostics.d.ts +163 -0
  15. package/dist/diagnostics.js +498 -0
  16. package/dist/ecash.d.ts +41 -0
  17. package/dist/ecash.js +190 -0
  18. package/dist/fees.d.ts +164 -0
  19. package/dist/fees.js +208 -0
  20. package/dist/fixture-cli.d.ts +2 -0
  21. package/dist/fixture-cli.js +41 -0
  22. package/dist/fixtures.d.ts +68 -0
  23. package/dist/fixtures.js +46 -0
  24. package/dist/forth-ir.d.ts +73 -0
  25. package/dist/forth-ir.js +147 -0
  26. package/dist/generic-cli.d.ts +2 -0
  27. package/dist/generic-cli.js +140 -0
  28. package/dist/generic.d.ts +48 -0
  29. package/dist/generic.js +2566 -0
  30. package/dist/lints.d.ts +8 -0
  31. package/dist/lints.js +204 -0
  32. package/dist/names.d.ts +1 -0
  33. package/dist/names.js +7 -0
  34. package/dist/opcodes.d.ts +154 -0
  35. package/dist/opcodes.js +162 -0
  36. package/dist/optimizer.d.ts +58 -0
  37. package/dist/optimizer.js +786 -0
  38. package/dist/package-fetch-cli.d.ts +2 -0
  39. package/dist/package-fetch-cli.js +17 -0
  40. package/dist/package-lock-cli.d.ts +2 -0
  41. package/dist/package-lock-cli.js +28 -0
  42. package/dist/package-sources.d.ts +82 -0
  43. package/dist/package-sources.js +785 -0
  44. package/dist/package-update-cli.d.ts +2 -0
  45. package/dist/package-update-cli.js +20 -0
  46. package/dist/packages.d.ts +231 -0
  47. package/dist/packages.js +1307 -0
  48. package/dist/parser.d.ts +32 -0
  49. package/dist/parser.js +575 -0
  50. package/dist/policy.d.ts +83 -0
  51. package/dist/policy.js +207 -0
  52. package/dist/runtime.d.ts +58 -0
  53. package/dist/runtime.js +126 -0
  54. package/dist/scheduler.d.ts +38 -0
  55. package/dist/scheduler.js +76 -0
  56. package/dist/semantic-ir.d.ts +76 -0
  57. package/dist/semantic-ir.js +231 -0
  58. package/dist/std.d.ts +27 -0
  59. package/dist/std.js +225 -0
  60. package/dist/target-compiler.d.ts +9 -0
  61. package/dist/target-compiler.js +139 -0
  62. package/dist/targets.d.ts +53 -0
  63. package/dist/targets.js +67 -0
  64. package/dist/toml-subset.d.ts +19 -0
  65. package/dist/toml-subset.js +81 -0
  66. package/dist/transaction-runtime.d.ts +182 -0
  67. package/dist/transaction-runtime.js +646 -0
  68. package/dist/version.d.ts +3 -0
  69. package/dist/version.js +3 -0
  70. package/dist/vm-cost.d.ts +11 -0
  71. package/dist/vm-cost.js +541 -0
  72. package/package.json +71 -4
  73. package/policy-artifact.schema.json +20 -0
  74. package/std/custody/arbiter-escrow.lotus +20 -0
  75. package/std/custody/htlc.lotus +15 -0
  76. package/std/custody/multisig-2of3.lotus +13 -0
  77. package/std/custody/single-owner-wallet.lotus +9 -0
  78. package/std/custody/vault-with-recovery.lotus +14 -0
  79. package/std/defi/amm-pool-v2.lotus +97 -0
  80. package/std/defi/indexed-limit-order.lotus +37 -0
  81. package/std/nft/nft-collection.lotus +51 -0
  82. package/std/nft/royalty-transfer-rules.lotus +38 -0
  83. package/std/nft/unique-nft.lotus +30 -0
  84. package/std/tokens/capped-supply-token.lotus +76 -0
  85. package/std/tokens/fixed-supply-token.lotus +29 -0
  86. package/std/tokens/standard-transfer-rules.lotus +15 -0
  87. package/std/tokens/voucher-mint-token.lotus +31 -0
@@ -0,0 +1,2566 @@
1
+ /** Bounded, typed P03 contract frontend. No VM or consensus-validation code. */
2
+ import { artifactSpan, hex } from './compiler.js';
3
+ import { DiagnosticBag, SourceManager, suggest } from './diagnostics.js';
4
+ import { lintProgram } from './lints.js';
5
+ import { COMPILER_NAME, COMPILER_VERSION } from './version.js';
6
+ import { resolveTarget } from './targets.js';
7
+ import { SUPPORTED_COMPILER_EDITIONS, SUPPORTED_OPTIMIZER_VERSIONS, isSupportedCompilerEdition, isSupportedOptimizerVersion, resolveCompilerEdition, resolveOptimizerVersion, } from './optimizer.js';
8
+ import { PromiseScheduler } from './scheduler.js';
9
+ import { INT_MAX, INT_MIN, INT_RANGE, MAX_DEPENDENCY_VISITS, MAX_EXPANSIONS, MAX_INFERENCE_VISITS, comparable, conjuncts, decodedInt, helperReturn, isBranchRootType, isTaggedHashType, leafHash, literal, sourceBindings, tree, } from './ast.js';
10
+ import { lex, Parser } from './parser.js';
11
+ import { ForthEmitter } from './forth-ir.js';
12
+ export { DEFAULT_COMPILER_EDITION, DEFAULT_OPTIMIZER_VERSION, OPTIMIZER_PASSES_BY_VERSION, SUPPORTED_COMPILER_EDITIONS, SUPPORTED_OPTIMIZER_VERSIONS, isSupportedCompilerEdition, isSupportedOptimizerVersion, resolveCompilerEdition, resolveOptimizerVersion, } from './optimizer.js';
13
+ export { TAGGED_HASH_TYPES, isBranchRootType, isTaggedHashType, linkedProgramSource, sourceBindings, } from './ast.js';
14
+ /** Notes for an inlined helper chain. The expansion stack itself is capped at 16. */
15
+ const MAX_INLINE_NOTES = 16;
16
+ const isRawBytes = (t) => t === 'PublicKey' || t === 'Signature' || t === 'Bytes32' || t.startsWith('Bytes(');
17
+ const isBytesLike = (t) => isRawBytes(t) || isTaggedHashType(t);
18
+ const isNumeric = (t) => t === 'Int' || t === 'Amount';
19
+ const typeMatches = (actual, expected) => actual === expected || (isBranchRootType(actual) && isBranchRootType(expected));
20
+ const TAGGED_HASH_CONSTRUCTORS = new Set([
21
+ 'TxId', 'StateRoot', 'ChainId', 'SigHash', 'TokenId', 'BranchRoot',
22
+ ]);
23
+ function constructorFor(t) {
24
+ if (t === 'ContractRootHash')
25
+ return 'BranchRoot';
26
+ return TAGGED_HASH_CONSTRUCTORS.has(t) ? t : undefined;
27
+ }
28
+ function taggedHashHelp(actual, expected) {
29
+ if (expected === 'bytes' || expected === 'Bytes32') {
30
+ if (isTaggedHashType(actual)) {
31
+ return { help: `convert ${actual} to raw bytes with bytes32(...)` };
32
+ }
33
+ return {};
34
+ }
35
+ const ctor = constructorFor(expected);
36
+ if (actual === 'Bytes32' && isTaggedHashType(expected)) {
37
+ return ctor ? { help: `wrap Bytes32 with ${ctor}(...)` } : {};
38
+ }
39
+ if (isTaggedHashType(actual) && isTaggedHashType(expected) && !typeMatches(actual, expected)) {
40
+ return ctor
41
+ ? { help: `cannot mix ${actual} and ${expected}; convert explicitly via ${ctor}(bytes32(...)) if intended` }
42
+ : { help: `cannot mix ${actual} and ${expected}; use bytes32(...) for raw bytes` };
43
+ }
44
+ return {};
45
+ }
46
+ function taggedHashCompareHelp(a, b) {
47
+ if (isTaggedHashType(a) && isTaggedHashType(b)) {
48
+ return { help: `cannot compare ${a} with ${b}; use bytes32(...) on both sides if you intentionally want raw byte equality` };
49
+ }
50
+ if (a === 'Bytes32' && isTaggedHashType(b)) {
51
+ const ctor = constructorFor(b);
52
+ return { help: ctor ? `convert with bytes32(...) or ${ctor}(...) so both sides have the same type` : `convert ${b} with bytes32(...) to compare raw bytes` };
53
+ }
54
+ if (isTaggedHashType(a) && b === 'Bytes32') {
55
+ const ctor = constructorFor(a);
56
+ return { help: ctor ? `convert with bytes32(...) or ${ctor}(...) so both sides have the same type` : `convert ${a} with bytes32(...) to compare raw bytes` };
57
+ }
58
+ return {};
59
+ }
60
+ class Compiler {
61
+ program;
62
+ options;
63
+ diag;
64
+ scheduledJob;
65
+ enforceScheduledJobs = false;
66
+ dependencyVisits = 0;
67
+ helperDependencies = new Map();
68
+ methodMemo = new Map();
69
+ methodActive = new Set();
70
+ rootMemo = new Map();
71
+ rootActive = new Set();
72
+ bindingMemo = new Map();
73
+ resolvedEdition;
74
+ resolvedOptimizerVersion;
75
+ constructor(program, options, diag) {
76
+ this.program = program;
77
+ this.options = options;
78
+ this.diag = diag;
79
+ if ((program.languageVersion ?? 0) !== (options.languageVersion ?? 0))
80
+ this.fatal('E0131', 'linked program languageVersion differs from compile options');
81
+ if (program.edition !== undefined && options.edition !== undefined && program.edition !== options.edition) {
82
+ this.fatal('E0133', `compile option edition "${options.edition}" conflicts with source pragma edition "${program.edition}"`);
83
+ }
84
+ if (program.optimizerVersion !== undefined) {
85
+ if (options.optimizerVersion !== undefined && program.optimizerVersion !== options.optimizerVersion) {
86
+ this.fatal('E0134', `compile option optimizerVersion "${options.optimizerVersion}" conflicts with source pragma optimizer "${program.optimizerVersion}"`);
87
+ }
88
+ if (options.optimize === false && program.optimizerVersion !== 'none') {
89
+ this.fatal('E0134', `compile option optimize: false conflicts with source pragma optimizer "${program.optimizerVersion}"`);
90
+ }
91
+ if (options.optimize === true && program.optimizerVersion === 'none') {
92
+ this.fatal('E0134', 'compile option optimize: true conflicts with source pragma optimizer "none"');
93
+ }
94
+ }
95
+ this.resolvedEdition = resolveCompilerEdition(options.edition ?? program.edition);
96
+ this.resolvedOptimizerVersion = resolveOptimizerVersion({
97
+ optimize: options.optimize,
98
+ optimizerVersion: options.optimizerVersion ?? program.optimizerVersion,
99
+ });
100
+ if (options.languageVersion === 1)
101
+ for (const contract of program.contracts.values())
102
+ for (const method of contract.methods) {
103
+ if (method.invocation !== (contract.kind === 'token' ? 'mint' : 'spend'))
104
+ this.fatal('E0130', 'LC-1 entry requires its declared invocation kind', method.span);
105
+ }
106
+ }
107
+ /** Record a diagnostic, including the inline-expansion chain, and keep going until the cap. */
108
+ problem(code, message, span, frames = [], extra = {}) {
109
+ const related = frames.slice(-MAX_INLINE_NOTES).reverse().map(frame => ({
110
+ file: frame.at.file ?? this.diag.fallbackFile, span: frame.at, message: `in expansion of helper ${frame.name} called here`,
111
+ }));
112
+ this.diag.report(code, message, span, { ...extra, related: [...(extra.related ?? []), ...related] });
113
+ return 'Error';
114
+ }
115
+ fatal(code, message, span, frames = [], extra = {}) {
116
+ this.problem(code, message, span, frames, extra);
117
+ this.diag.finish();
118
+ }
119
+ hint(name, scope) {
120
+ const best = suggest(name, [
121
+ ...(scope ? scope.keys() : []), ...this.program.helpers.keys(), ...this.program.contracts.keys(),
122
+ 'checksig', 'checkdatasig', 'sighash', 'sha256', 'hash256', 'blake3',
123
+ 'leaf_hash', 'leaf_hash_bytes', 'node_hash', 'contract_root', 'merkle_root',
124
+ 'num_bytes', 'check_lock', 'check_sequence',
125
+ 'abs', 'sqrt', 'log', 'min', 'max', 'mulpow2', 'within',
126
+ 'cat', 'size', 'num2bin', 'bin2num',
127
+ 'bit_not', 'bit_and', 'bit_or', 'bit_xor', 'bit_shl',
128
+ 'merkle_root_sorted', 'merkle_root_indexed',
129
+ 'state_hash', 'state_verify', 'enforce_output', 'tx_token_in', 'tx_token_out',
130
+ 'bytes32', 'TxId', 'StateRoot', 'ChainId', 'SigHash', 'TokenId', 'BranchRoot',
131
+ ]);
132
+ return best ? { help: `did you mean '${best}'?` } : {};
133
+ }
134
+ contract(name, span) { const c = this.program.contracts.get(name); if (!c)
135
+ this.fatal(span ? 'E0303' : 'E0605', `unknown contract ${name}`, span ?? this.program.contracts.values().next().value?.span); return c; }
136
+ bound(name) {
137
+ const old = this.bindingMemo.get(name);
138
+ if (old)
139
+ return old;
140
+ const c = this.contract(name);
141
+ const input = this.options.bindings[name] ?? {};
142
+ if (typeof input !== 'object' || Array.isArray(input))
143
+ this.fatal('E0602', `constructor bindings for ${name} must be an object`, c.span);
144
+ const out = new Map();
145
+ for (const p of c.params) {
146
+ if (!Object.hasOwn(input, p.name))
147
+ this.fatal('E0603', `missing constructor binding ${name}.${p.name}`, p.span);
148
+ try {
149
+ out.set(p.name, literal(input[p.name], p.type));
150
+ }
151
+ catch (error) {
152
+ this.fatal('E0604', `invalid constructor binding ${name}.${p.name} (${p.type}): ${error.message}`, p.span);
153
+ }
154
+ }
155
+ const extra = Object.keys(input).find(key => !out.has(key));
156
+ if (extra !== undefined)
157
+ this.fatal('E0602', `unexpected constructor binding ${name}.${extra}`, c.span);
158
+ this.bindingMemo.set(name, out);
159
+ return out;
160
+ }
161
+ findMethod(contract, method, span) {
162
+ const m = this.contract(contract, span).methods.find(x => x.name === method);
163
+ if (!m)
164
+ this.fatal('E0304', `unknown method ${contract}.${method}`, span);
165
+ return m;
166
+ }
167
+ dependencies(method) {
168
+ const found = new Set();
169
+ const scanHelper = (body, target, helpers) => {
170
+ for (const stmt of body) {
171
+ if (stmt.kind === 'if') {
172
+ scan(stmt.expr, target, helpers);
173
+ scanHelper(stmt.then, target, helpers);
174
+ scanHelper(stmt.otherwise, target, helpers);
175
+ }
176
+ else
177
+ scan(stmt.expr, target, helpers);
178
+ }
179
+ };
180
+ const scan = (expr, target, helpers) => {
181
+ if (++this.dependencyVisits > MAX_DEPENDENCY_VISITS)
182
+ this.fatal('E0705', 'dependency scan visit budget exceeded', expr.span);
183
+ if (expr.kind === 'call') {
184
+ const args = expr.args ?? [];
185
+ if (expr.value === 'leaf_hash' && args.length === 1 && args[0]?.kind === 'name') {
186
+ const path = args[0].value.split('.');
187
+ if (path.length === 2) {
188
+ target.add(`leaf:${path[0]}.${path[1]}`);
189
+ }
190
+ }
191
+ else if ((expr.value === 'contract_root' || expr.value === 'merkle_root') && args.length === 1 && args[0]?.kind === 'name' && !args[0].value.includes('.')) {
192
+ target.add(`root:${args[0].value}`);
193
+ }
194
+ else {
195
+ for (const arg of args)
196
+ scan(arg, target, helpers);
197
+ const helper = this.program.helpers.get(expr.value);
198
+ if (helper && !helpers.includes(helper.name)) {
199
+ let dependencies = this.helperDependencies.get(helper.name);
200
+ if (!dependencies) {
201
+ if (helpers.length >= 16)
202
+ this.fatal('E0706', 'helper dependency depth exceeded', expr.span);
203
+ const inner = new Set();
204
+ scanHelper(helper.body, inner, [...helpers, helper.name]);
205
+ dependencies = [...inner];
206
+ this.helperDependencies.set(helper.name, dependencies);
207
+ }
208
+ for (const dependency of dependencies)
209
+ target.add(dependency);
210
+ }
211
+ }
212
+ }
213
+ else {
214
+ if (expr.left)
215
+ scan(expr.left, target, helpers);
216
+ if (expr.right)
217
+ scan(expr.right, target, helpers);
218
+ if (expr.args)
219
+ for (const arg of expr.args)
220
+ scan(arg, target, helpers);
221
+ }
222
+ };
223
+ const statements = (body) => {
224
+ for (const stmt of body) {
225
+ if (stmt.expr)
226
+ scan(stmt.expr, found, []);
227
+ if (stmt.then)
228
+ statements(stmt.then);
229
+ if (stmt.otherwise)
230
+ statements(stmt.otherwise);
231
+ }
232
+ };
233
+ statements(method.body);
234
+ return [...found];
235
+ }
236
+ async compileAsync(onEvent) {
237
+ this.contract(this.options.contract);
238
+ const scheduler = new PromiseScheduler(onEvent);
239
+ this.enforceScheduledJobs = true;
240
+ const execute = (name, job) => {
241
+ this.scheduledJob = name;
242
+ try {
243
+ job();
244
+ }
245
+ finally {
246
+ this.scheduledJob = undefined;
247
+ }
248
+ };
249
+ // Register all declarations from the single parsed program. Jobs compile
250
+ // only after their leaf/root dependencies have completed successfully.
251
+ for (const contract of this.program.contracts.values()) {
252
+ for (const method of contract.methods) {
253
+ const name = `leaf:${contract.name}.${method.name}`;
254
+ scheduler.register(name, () => this.dependencies(method), () => execute(name, () => { this.method(contract.name, method.name); }), artifactSpan(method.span));
255
+ }
256
+ const name = `root:${contract.name}`;
257
+ scheduler.register(name, contract.methods.map(method => `leaf:${contract.name}.${method.name}`), () => execute(name, () => { this.root(contract.name); }), artifactSpan(contract.span));
258
+ }
259
+ await scheduler.run(`root:${this.options.contract}`);
260
+ this.enforceScheduledJobs = false;
261
+ return this.compile();
262
+ }
263
+ root(name) {
264
+ const old = this.rootMemo.get(name);
265
+ if (old)
266
+ return old;
267
+ if (this.enforceScheduledJobs && this.scheduledJob !== `root:${name}`)
268
+ this.fatal('E9001', `unscheduled root dependency ${name}`, this.contract(name).span);
269
+ if (this.rootActive.has(name))
270
+ this.fatal('E0801', `contract-root dependency cycle at ${name}`, this.contract(name).span);
271
+ this.rootActive.add(name);
272
+ try {
273
+ this.bound(name);
274
+ const leaves = this.contract(name).methods.map(m => ({ name: m.name, hash: this.method(name, m.name).leaf }));
275
+ let result;
276
+ try {
277
+ result = tree(leaves);
278
+ }
279
+ catch (error) {
280
+ const message = error.message;
281
+ this.fatal(message === 'duplicate method leaf' ? 'E0207' : 'E0119', message, this.contract(name).span);
282
+ }
283
+ this.rootMemo.set(name, result);
284
+ return result;
285
+ }
286
+ finally {
287
+ this.rootActive.delete(name);
288
+ }
289
+ }
290
+ method(contractName, methodName) {
291
+ const key = `${contractName}.${methodName}`;
292
+ const old = this.methodMemo.get(key);
293
+ if (old)
294
+ return old;
295
+ if (this.enforceScheduledJobs && this.scheduledJob !== `leaf:${key}`)
296
+ this.fatal('E9001', `unscheduled leaf dependency ${key}`, this.findMethod(contractName, methodName).span);
297
+ if (this.methodActive.has(key))
298
+ this.fatal('E0801', `method-leaf dependency cycle at ${key}`, this.findMethod(contractName, methodName).span);
299
+ this.methodActive.add(key);
300
+ try {
301
+ const method = this.findMethod(contractName, methodName);
302
+ const c = this.contract(contractName);
303
+ const bindings = this.bound(contractName);
304
+ const env = new Map();
305
+ for (const p of c.params)
306
+ env.set(p.name, { kind: 'constant', type: p.type, data: bindings.get(p.name).bytes });
307
+ const stackParams = c.kind === 'token' ? [...method.params.slice(1), method.params[0]] : method.params;
308
+ for (const [index, p] of stackParams.entries()) {
309
+ if (env.has(p.name))
310
+ this.fatal('E0205', `method parameter ${p.name} shadows constructor`, p.span);
311
+ env.set(p.name, { kind: 'argument', type: p.type, index });
312
+ }
313
+ const emitter = new ForthEmitter(stackParams.length, (code, message, span, frames, extra) => this.fatal(code, message, span, frames, extra));
314
+ if (this.options.languageVersion === 1) {
315
+ emitter.op('INVOCATIONKIND', method.span, undefined, 1);
316
+ emitter.number(method.invocation === 'mint' ? 3n : 1n, method.span);
317
+ emitter.op('NUMEQUAL', method.span, undefined, -1);
318
+ emitter.op('VERIFY', method.span, undefined, -1);
319
+ }
320
+ const helperStack = [];
321
+ let inferenceVisits = 0;
322
+ const strictHashes = this.resolvedEdition === '2026.2';
323
+ const acceptsBytes = (t) => strictHashes ? isRawBytes(t) : isBytesLike(t);
324
+ const acceptsBranchRoot = (t) => isBranchRootType(t) || (!strictHashes && t === 'Bytes32');
325
+ const acceptsTokenId = (t) => t === 'TokenId' || (!strictHashes && t === 'Bytes32');
326
+ const acceptsStateRoot = (t) => t === 'StateRoot' || (!strictHashes && comparable(t, 'Bytes32', this.resolvedEdition));
327
+ const txIdType = strictHashes ? 'TxId' : 'Bytes32';
328
+ const stateRootType = strictHashes ? 'StateRoot' : 'Bytes32';
329
+ const chainIdType = strictHashes ? 'ChainId' : 'Bytes32';
330
+ const sigHashType = strictHashes ? 'SigHash' : 'Bytes32';
331
+ const inferTupleCall = (expr, scope, active, frames) => {
332
+ if (expr.kind !== 'call') {
333
+ this.problem('E0125', 'tuple destructuring requires a multi-return builtin call (mul128_wide, add_carry, sub_carry, split, less_swap, tx_token_balance)', expr.span, frames);
334
+ return 'Error';
335
+ }
336
+ const name = expr.value, args = expr.args ?? [];
337
+ if (name === 'mul128_wide') {
338
+ if (args.length !== 2) {
339
+ this.problem('E0502', 'mul128_wide expects two numeric/byte operands', expr.span, frames);
340
+ return 'Error';
341
+ }
342
+ const a = infer(args[0], scope, active, frames), b = infer(args[1], scope, active, frames);
343
+ if (a === 'Error' || b === 'Error')
344
+ return 'Error';
345
+ if ((!isNumeric(a) && !acceptsBytes(a)) || (!isNumeric(b) && !acceptsBytes(b))) {
346
+ const bad = (!isNumeric(a) && !acceptsBytes(a)) ? a : b;
347
+ this.problem('E0405', 'mul128_wide expects Int/Amount or bytes operands', expr.span, frames, taggedHashHelp(bad, 'bytes'));
348
+ return 'Error';
349
+ }
350
+ return ['Bytes(8192)', 'Bytes(8192)'];
351
+ }
352
+ if (name === 'add_carry' || name === 'sub_carry') {
353
+ if (args.length !== 3) {
354
+ this.problem('E0502', `${name} expects a, b, and carry/borrow Int`, expr.span, frames);
355
+ return 'Error';
356
+ }
357
+ const a = infer(args[0], scope, active, frames), b = infer(args[1], scope, active, frames), cIn = infer(args[2], scope, active, frames);
358
+ if (a === 'Error' || b === 'Error' || cIn === 'Error')
359
+ return 'Error';
360
+ if ((!isNumeric(a) && !acceptsBytes(a)) || (!isNumeric(b) && !acceptsBytes(b)) || cIn !== 'Int') {
361
+ const bad = (!isNumeric(a) && !acceptsBytes(a)) ? a : (!isNumeric(b) && !acceptsBytes(b)) ? b : cIn;
362
+ this.problem('E0405', `${name} expects Int/Amount/bytes operands and Int carry`, expr.span, frames, taggedHashHelp(bad, 'bytes'));
363
+ return 'Error';
364
+ }
365
+ return ['Bytes(8192)', 'Int'];
366
+ }
367
+ if (name === 'split') {
368
+ if (args.length !== 2) {
369
+ this.problem('E0502', 'split expects bytes value and Int offset', expr.span, frames);
370
+ return 'Error';
371
+ }
372
+ const a = infer(args[0], scope, active, frames), b = infer(args[1], scope, active, frames);
373
+ if (a === 'Error' || b === 'Error')
374
+ return 'Error';
375
+ if (!acceptsBytes(a) || b !== 'Int') {
376
+ this.problem('E0405', 'split expects bytes and Int offset', expr.span, frames, !acceptsBytes(a) ? taggedHashHelp(a, 'bytes') : {});
377
+ return 'Error';
378
+ }
379
+ return ['Bytes(8192)', 'Bytes(8192)'];
380
+ }
381
+ if (name === 'less_swap') {
382
+ if (args.length !== 2) {
383
+ this.problem('E0502', 'less_swap expects two byte values', expr.span, frames);
384
+ return 'Error';
385
+ }
386
+ const a = infer(args[0], scope, active, frames), b = infer(args[1], scope, active, frames);
387
+ if (a === 'Error' || b === 'Error')
388
+ return 'Error';
389
+ if (!acceptsBytes(a) || !acceptsBytes(b)) {
390
+ this.problem('E0405', 'less_swap expects byte values', expr.span, frames, taggedHashHelp(!acceptsBytes(a) ? a : b, 'bytes'));
391
+ return 'Error';
392
+ }
393
+ return [a === b ? a : 'Bytes(8192)', a === b ? b : 'Bytes(8192)'];
394
+ }
395
+ if (name === 'tx_token_balance') {
396
+ if (args.length !== 1) {
397
+ this.problem('E0502', strictHashes ? 'tx_token_balance expects TokenId' : 'tx_token_balance expects TokenId or Bytes32', expr.span, frames);
398
+ return 'Error';
399
+ }
400
+ const a = infer(args[0], scope, active, frames);
401
+ if (a === 'Error')
402
+ return 'Error';
403
+ if (!acceptsTokenId(a)) {
404
+ this.problem('E0405', strictHashes ? `tx_token_balance expects TokenId, got ${a}` : `tx_token_balance expects TokenId or Bytes32, got ${a}`, args[0].span, frames, taggedHashHelp(a, 'TokenId'));
405
+ return 'Error';
406
+ }
407
+ return ['Amount', 'Amount'];
408
+ }
409
+ this.problem('E0125', `function ${name} does not return a 2-tuple`, expr.span, frames);
410
+ return 'Error';
411
+ };
412
+ const inferBlock = (body, scope, active, frames, returning) => {
413
+ const introduced = [];
414
+ try {
415
+ for (const stmt of body) {
416
+ if (stmt.kind === 'let') {
417
+ if (scope.has(stmt.name))
418
+ return this.problem('E0208', `let ${stmt.name} shadows a binding`, stmt.nameSpan, frames);
419
+ const t = infer(stmt.expr, scope, active, frames);
420
+ if (t === 'Error')
421
+ return 'Error';
422
+ if (!typeMatches(t, stmt.type))
423
+ return this.problem('E0414', `let ${stmt.name} expects ${stmt.type}, got ${t}`, stmt.expr.span, frames, taggedHashHelp(t, stmt.type));
424
+ scope.set(stmt.name, { kind: 'local', type: stmt.type, index: -1 });
425
+ introduced.push(stmt.name);
426
+ }
427
+ else if (stmt.kind === 'let_tuple') {
428
+ const [va, vb] = stmt.variables;
429
+ if (scope.has(va.name))
430
+ return this.problem('E0208', `let ${va.name} shadows a binding`, va.span, frames);
431
+ if (scope.has(vb.name))
432
+ return this.problem('E0208', `let ${vb.name} shadows a binding`, vb.span, frames);
433
+ const pair = inferTupleCall(stmt.expr, scope, active, frames);
434
+ if (pair === 'Error')
435
+ return 'Error';
436
+ scope.set(va.name, { kind: 'local', type: pair[0], index: -1 });
437
+ scope.set(vb.name, { kind: 'local', type: pair[1], index: -1 });
438
+ introduced.push(va.name, vb.name);
439
+ }
440
+ else if (stmt.kind === 'require') {
441
+ for (const part of conjuncts(stmt.expr)) {
442
+ const t = infer(part, scope, active, frames);
443
+ if (t === 'Error')
444
+ return 'Error';
445
+ if (t !== 'Bool')
446
+ return this.problem('E0404', `require requires Bool, got ${t}`, part.span, frames);
447
+ }
448
+ }
449
+ else if (stmt.kind === 'if') {
450
+ const t = infer(stmt.expr, scope, active, frames);
451
+ if (t === 'Error')
452
+ return 'Error';
453
+ if (t !== 'Bool')
454
+ return this.problem('E0404', `if requires Bool, got ${t}`, stmt.expr.span, frames);
455
+ if (inferBlock(stmt.then, scope, active, frames, false) === 'Error')
456
+ return 'Error';
457
+ if (inferBlock(stmt.otherwise, scope, active, frames, false) === 'Error')
458
+ return 'Error';
459
+ }
460
+ else {
461
+ if (!returning)
462
+ return this.problem('E0123', 'return must be the final statement of the helper', stmt.span, frames);
463
+ return infer(stmt.expr, scope, active, frames);
464
+ }
465
+ }
466
+ if (returning)
467
+ return this.problem('E0123', 'helper must end with return', body.at(-1)?.span, frames);
468
+ return 'Bool';
469
+ }
470
+ finally {
471
+ for (const name of introduced)
472
+ scope.delete(name);
473
+ }
474
+ };
475
+ const infer = (expr, scope, active = [], frames = []) => {
476
+ if (++inferenceVisits > MAX_INFERENCE_VISITS)
477
+ this.fatal('E0704', 'type inference visit budget exceeded', expr.span, frames);
478
+ if (expr.kind === 'number') {
479
+ const n = BigInt(expr.value);
480
+ if (n < INT_MIN || n >= INT_MAX)
481
+ return this.problem('E0413', INT_RANGE, expr.span, frames);
482
+ return 'Int';
483
+ }
484
+ if (expr.kind === 'bool')
485
+ return 'Bool';
486
+ if (expr.kind === 'name') {
487
+ if (expr.value === 'this.root')
488
+ return c.kind === 'token' ? 'TokenId' : 'ContractRootHash';
489
+ if (expr.value === 'this.input_index')
490
+ return 'Int';
491
+ if (expr.value === 'this.active_branch_index')
492
+ return 'Int';
493
+ if (expr.value === 'tx.id')
494
+ return txIdType;
495
+ if (expr.value === 'tx.chain_id')
496
+ return chainIdType;
497
+ if (expr.value === 'tx.mint_count')
498
+ return 'Int';
499
+ if (expr.value === 'this.coin.token_id') {
500
+ if (c.kind === 'token')
501
+ return this.problem('E0411', 'mint method has no coin', expr.span, frames);
502
+ return 'TokenId';
503
+ }
504
+ if (expr.value === 'this.coin.value') {
505
+ if (c.kind === 'token')
506
+ return this.problem('E0411', 'mint method has no coin', expr.span, frames);
507
+ return 'Amount';
508
+ }
509
+ if (expr.value === 'this.coin.txid') {
510
+ if (c.kind === 'token')
511
+ return this.problem('E0411', 'mint method has no coin', expr.span, frames);
512
+ return txIdType;
513
+ }
514
+ if (expr.value === 'this.coin.vout') {
515
+ if (c.kind === 'token')
516
+ return this.problem('E0411', 'mint method has no coin', expr.span, frames);
517
+ return 'Int';
518
+ }
519
+ if (expr.value === 'this.coin.path_index') {
520
+ if (c.kind === 'token')
521
+ return this.problem('E0411', 'mint method has no coin', expr.span, frames);
522
+ return 'Int';
523
+ }
524
+ if (expr.value === 'this.coin.flags') {
525
+ if (c.kind === 'token')
526
+ return this.problem('E0411', 'mint method has no coin', expr.span, frames);
527
+ return 'Int';
528
+ }
529
+ if (expr.value === 'this.coin.state_root') {
530
+ if (c.kind === 'token')
531
+ return this.problem('E0411', 'mint method has no coin', expr.span, frames);
532
+ return stateRootType;
533
+ }
534
+ const dot = expr.value.split('.');
535
+ const recordFields = ['token_id', 'value', 'is_spend', 'txid', 'vout', 'path_index', 'flags', 'state_root'];
536
+ const coinFields = ['token_id', 'value', 'txid', 'vout', 'path_index', 'flags', 'state_root'];
537
+ if ((dot.length === 2 && recordFields.includes(dot[1])) || (dot.length === 3 && dot[1] === 'coin' && coinFields.includes(dot[2]))) {
538
+ const v = scope.get(dot[0]);
539
+ if (!v || v.kind !== 'local' || (v.type !== 'InputIndex' && v.type !== 'OutputIndex'))
540
+ return this.problem('E0305', `unbound record ${dot[0]}`, expr.span, frames, this.hint(dot[0], scope));
541
+ if (dot.length === 3 && v.type !== 'InputIndex')
542
+ return this.problem('E0412', 'coin field requires input', expr.span, frames);
543
+ const field = dot.at(-1);
544
+ if (field === 'is_spend') {
545
+ if (v.type !== 'InputIndex')
546
+ return this.problem('E0412', 'is_spend requires input', expr.span, frames);
547
+ return 'Bool';
548
+ }
549
+ if (field === 'txid' || field === 'vout' || field === 'path_index') {
550
+ if (v.type !== 'InputIndex')
551
+ return this.problem('E0412', `${field} requires input`, expr.span, frames);
552
+ return field === 'txid' ? txIdType : 'Int';
553
+ }
554
+ if (field === 'flags')
555
+ return 'Int';
556
+ if (field === 'state_root')
557
+ return stateRootType;
558
+ return field === 'token_id' ? 'TokenId' : 'Amount';
559
+ }
560
+ const v = scope.get(expr.value);
561
+ if (!v)
562
+ return this.problem('E0301', `unbound name ${expr.value}`, expr.span, frames, this.hint(expr.value, scope));
563
+ return v.kind === 'substitute' ? infer(v.expr, v.env, active, v.frames) : v.type;
564
+ }
565
+ if (expr.kind === 'unary') {
566
+ if (expr.value === '-' && expr.right?.kind === 'number') {
567
+ const n = -BigInt(expr.right.value);
568
+ if (n < INT_MIN || n >= INT_MAX)
569
+ return this.problem('E0413', INT_RANGE, expr.span, frames);
570
+ return 'Int';
571
+ }
572
+ const t = infer(expr.right, scope, active, frames);
573
+ if (t === 'Error')
574
+ return 'Error';
575
+ if ((expr.value === '!' && t === 'Bool') || (expr.value === '-' && t === 'Int'))
576
+ return t;
577
+ return this.problem('E0402', `invalid unary ${expr.value} on ${t}`, expr.span, frames);
578
+ }
579
+ if (expr.kind === 'index') {
580
+ const target = expr.left;
581
+ if (target.kind !== 'name' || (target.value !== 'tx.inputs' && target.value !== 'tx.outputs')) {
582
+ return this.problem('E0412', 'indexing is only supported on tx.inputs[...] and tx.outputs[...]', target.span, frames, {
583
+ labels: [{ span: target.span, message: 'expected tx.inputs or tx.outputs here', primary: true }],
584
+ });
585
+ }
586
+ const idx = infer(expr.right, scope, active, frames);
587
+ if (idx === 'Error')
588
+ return 'Error';
589
+ if (idx !== 'Int') {
590
+ return this.problem('E0405', `index must be Int, got ${idx}`, expr.right.span, frames, {
591
+ labels: [{ span: expr.right.span, message: `expected Int index, found ${idx}`, primary: true }],
592
+ });
593
+ }
594
+ return target.value === 'tx.inputs' ? 'InputIndex' : 'OutputIndex';
595
+ }
596
+ if (expr.kind === 'member') {
597
+ const base = infer(expr.left, scope, active, frames);
598
+ if (base === 'Error')
599
+ return 'Error';
600
+ if (base !== 'InputIndex' && base !== 'OutputIndex') {
601
+ return this.problem('E0412', `cannot access .${expr.value} on ${base}`, expr.span, frames, {
602
+ labels: [{ span: expr.left.span, message: `expression has type ${base}`, primary: true }],
603
+ });
604
+ }
605
+ const field = expr.value;
606
+ const onCoin = expr.left.kind === 'member' && expr.left.value === 'coin';
607
+ if (field === 'coin') {
608
+ if (base !== 'InputIndex' || onCoin)
609
+ return this.problem('E0412', 'coin field requires an input', expr.span, frames);
610
+ return 'InputIndex';
611
+ }
612
+ if (field === 'is_spend') {
613
+ if (base !== 'InputIndex' || onCoin)
614
+ return this.problem('E0412', 'is_spend requires an input', expr.span, frames);
615
+ return 'Bool';
616
+ }
617
+ if (field === 'txid' || field === 'vout' || field === 'path_index') {
618
+ if (base !== 'InputIndex')
619
+ return this.problem('E0412', `${field} requires an input`, expr.span, frames);
620
+ return field === 'txid' ? txIdType : 'Int';
621
+ }
622
+ if (field === 'flags')
623
+ return 'Int';
624
+ if (field === 'state_root')
625
+ return stateRootType;
626
+ if (field === 'token_id')
627
+ return 'TokenId';
628
+ if (field === 'value')
629
+ return 'Amount';
630
+ return this.problem('E0412', `unknown field .${field} on ${base}`, expr.span, frames);
631
+ }
632
+ if (expr.kind === 'member_call') {
633
+ const base = infer(expr.left, scope, active, frames);
634
+ if (base === 'Error')
635
+ return 'Error';
636
+ if (base !== 'InputIndex' && base !== 'OutputIndex') {
637
+ return this.problem('E0412', `cannot call .${expr.value}(...) on ${base}`, expr.span, frames, {
638
+ labels: [{ span: expr.left.span, message: `expression has type ${base}`, primary: true }],
639
+ });
640
+ }
641
+ const mname = expr.value, margs = expr.args ?? [];
642
+ if (['branch', 'branch_count', 'path', 'path_count'].includes(mname)) {
643
+ const indexed = mname === 'branch' || mname === 'path';
644
+ const pathRead = mname === 'path' || mname === 'path_count';
645
+ if (margs.length !== (indexed ? 1 : 0) || (indexed && infer(margs[0], scope, active, frames) !== 'Int')) {
646
+ return this.problem('E0405', `${mname} expects ${indexed ? 'one Int index' : 'no arguments'}`, expr.span, frames);
647
+ }
648
+ return indexed ? (pathRead ? 'Bytes(8192)' : 'Bytes32') : 'Int';
649
+ }
650
+ if (['requires_branch', 'exclusive_branch', 'continues_branch'].includes(mname)) {
651
+ if (mname !== 'requires_branch' && base !== 'OutputIndex') {
652
+ return this.problem('E0412', `${mname} requires an output`, expr.span, frames);
653
+ }
654
+ if (margs.length !== 1)
655
+ return this.problem('E0412', `${mname} expects one root argument`, expr.span, frames);
656
+ const arg = infer(margs[0], scope, active, frames);
657
+ if (arg === 'Error')
658
+ return 'Error';
659
+ if (!acceptsBranchRoot(arg)) {
660
+ return this.problem('E0412', strictHashes
661
+ ? `${mname} expects a BranchRoot or ContractRootHash, got ${arg}`
662
+ : `${mname} expects a BranchRoot, ContractRootHash, or Bytes32 root, got ${arg}`, margs[0].span, frames, taggedHashHelp(arg, 'BranchRoot'));
663
+ }
664
+ return 'Bool';
665
+ }
666
+ return this.problem('E0412', `unknown method .${mname}(...) on ${base}`, expr.span, frames);
667
+ }
668
+ if (expr.kind === 'binary') {
669
+ const a = infer(expr.left, scope, active, frames), b = infer(expr.right, scope, active, frames);
670
+ if (a === 'Error' || b === 'Error')
671
+ return 'Error';
672
+ if ((expr.value === '==' || expr.value === '!=') && comparable(a, b, this.resolvedEdition))
673
+ return 'Bool';
674
+ if (a !== b && !(isNumeric(a) && isNumeric(b))) {
675
+ return this.problem('E0401', `binary type mismatch ${a}, ${b}`, expr.span, frames, {
676
+ ...((expr.value === '==' || expr.value === '!=') ? taggedHashCompareHelp(a, b) : {}),
677
+ labels: [
678
+ { span: expr.left.span, message: `left operand has type ${a}` },
679
+ { span: expr.right.span, message: `right operand has type ${b}`, primary: true },
680
+ ],
681
+ });
682
+ }
683
+ if (expr.value === '==' || expr.value === '!=')
684
+ return 'Bool';
685
+ if (['+', '-', '*', '/', '%'].includes(expr.value) && isNumeric(a) && isNumeric(b))
686
+ return a === 'Amount' || b === 'Amount' ? 'Amount' : 'Int';
687
+ if (['<', '>', '<=', '>='].includes(expr.value) && isNumeric(a) && isNumeric(b))
688
+ return 'Bool';
689
+ if (['&&', '||'].includes(expr.value) && a === 'Bool')
690
+ return 'Bool';
691
+ return this.problem('E0403', `invalid binary ${expr.value} on ${a}`, expr.span, frames, {
692
+ labels: [
693
+ { span: expr.left.span, message: `left operand has type ${a}` },
694
+ { span: expr.right.span, message: `right operand has type ${b}`, primary: true },
695
+ ],
696
+ });
697
+ }
698
+ if (expr.kind !== 'call')
699
+ return this.problem('E9001', 'unknown expression', expr.span, frames);
700
+ const name = expr.value, args = expr.args ?? [];
701
+ if (name === 'bytes32') {
702
+ if (args.length !== 1)
703
+ return this.problem('E0502', 'bytes32 expects one 32-byte hash argument', expr.span, frames);
704
+ const t = infer(args[0], scope, active, frames);
705
+ if (t === 'Error')
706
+ return 'Error';
707
+ if (t !== 'Bytes32' && !isTaggedHashType(t)) {
708
+ return this.problem('E0405', `bytes32 expects Bytes32 or a 32-byte tagged hash, got ${t}`, args[0].span, frames);
709
+ }
710
+ return 'Bytes32';
711
+ }
712
+ if (TAGGED_HASH_CONSTRUCTORS.has(name)) {
713
+ const target = name;
714
+ if (args.length !== 1)
715
+ return this.problem('E0502', `${target} expects one Bytes32 argument`, expr.span, frames);
716
+ const t = infer(args[0], scope, active, frames);
717
+ if (t === 'Error')
718
+ return 'Error';
719
+ if (t !== 'Bytes32' && !typeMatches(t, target)) {
720
+ return this.problem('E0405', `${target}(...) expects Bytes32${target === 'BranchRoot' ? ', BranchRoot, or ContractRootHash' : ` or ${target}`}, got ${t}`, args[0].span, frames, taggedHashHelp(t, target));
721
+ }
722
+ return target;
723
+ }
724
+ if (name === 'num_bytes') {
725
+ if (args.length !== 1 || infer(args[0], scope, active, frames) !== 'Int')
726
+ return this.problem('E0405', 'num_bytes expects Int', expr.span, frames);
727
+ return 'Bytes(16)';
728
+ }
729
+ if (name === 'check_lock' || name === 'check_sequence') {
730
+ if (args.length !== 2 || args.some(arg => infer(arg, scope, active, frames) !== 'Int'))
731
+ return this.problem('E0405', `${name} expects Int kind and bound`, expr.span, frames);
732
+ return 'Bool';
733
+ }
734
+ if (['.branch', '.branch_count', '.path', '.path_count'].some(suffix => name.endsWith(suffix))) {
735
+ const path = name.split('.'), current = path.slice(0, -1).join('.') === 'this.coin', receiver = scope.get(path[0]);
736
+ if (current ? c.kind === 'token' : !(receiver?.kind === 'local' && ['InputIndex', 'OutputIndex'].includes(receiver.type) && (path.length === 2 || path.length === 3 && path[1] === 'coin' && receiver.type === 'InputIndex')))
737
+ return this.problem('E0412', 'branch/path read requires a spend coin or enumerated input/output', expr.span, frames);
738
+ const branch = name.endsWith('.branch') || name.endsWith('.path'), pathRead = name.endsWith('.path') || name.endsWith('.path_count');
739
+ if (args.length !== (branch ? 1 : 0) || branch && infer(args[0], scope, active, frames) !== 'Int')
740
+ return this.problem('E0405', 'branch/path index must be Int; count takes no arguments', expr.span, frames);
741
+ return branch ? (pathRead ? 'Bytes(8192)' : 'Bytes32') : 'Int';
742
+ }
743
+ if (name === 'leaf_hash') {
744
+ if (args.length !== 1 || args[0].kind !== 'name' || args[0].value.split('.').length !== 2)
745
+ return this.problem('E0502', 'leaf_hash requires Contract.method', expr.span, frames);
746
+ return 'MethodLeafHash';
747
+ }
748
+ if (name === 'contract_root' || name === 'merkle_root') {
749
+ if (args.length !== 1 || args[0].kind !== 'name' || args[0].value.includes('.'))
750
+ return this.problem('E0502', `${name} requires tree name`, expr.span, frames);
751
+ return this.contract(args[0].value, args[0].span).kind === 'token' ? 'TokenId' : 'ContractRootHash';
752
+ }
753
+ if (name.endsWith('.requires_branch') || name.endsWith('.exclusive_branch') || name.endsWith('.continues_branch')) {
754
+ const parts = name.split('.'), receiver = scope.get(parts[0]);
755
+ const inputPredicate = name.endsWith('.requires_branch') && receiver?.type === 'InputIndex';
756
+ if (inputPredicate ? !(parts.length === 2 || parts.length === 3 && parts[1] === 'coin') : parts.length !== 2 || receiver?.type !== 'OutputIndex')
757
+ return this.problem('E0412', 'branch predicate requires an enumerated input/output receiver', expr.span, frames);
758
+ if (args.length !== 1)
759
+ return this.problem('E0412', 'requires_branch expects output and contract root', expr.span, frames);
760
+ const arg = infer(args[0], scope, active, frames);
761
+ if (arg === 'Error')
762
+ return 'Error';
763
+ if (!acceptsBranchRoot(arg))
764
+ return this.problem('E0412', strictHashes
765
+ ? `requires_branch expects a BranchRoot or ContractRootHash, got ${arg}`
766
+ : `requires_branch expects a BranchRoot, ContractRootHash, or Bytes32 root, got ${arg}`, args[0].span, frames, taggedHashHelp(arg, 'BranchRoot'));
767
+ return 'Bool';
768
+ }
769
+ if (name === 'checksig') {
770
+ if (args.length !== 2)
771
+ return this.problem('E0502', 'checksig expects Signature, PublicKey', expr.span, frames);
772
+ const a = infer(args[0], scope, active, frames), b = infer(args[1], scope, active, frames);
773
+ if (a === 'Error' || b === 'Error')
774
+ return 'Error';
775
+ if (a !== 'Signature' || b !== 'PublicKey')
776
+ return this.problem('E0405', 'checksig expects Signature, PublicKey', expr.span, frames);
777
+ return 'Bool';
778
+ }
779
+ if (['sha256', 'hash256', 'blake3'].includes(name)) {
780
+ if (args.length !== 1)
781
+ return this.problem('E0502', `${name} expects one byte value`, expr.span, frames);
782
+ const t = infer(args[0], scope, active, frames);
783
+ if (t === 'Error')
784
+ return 'Error';
785
+ if (!acceptsBytes(t))
786
+ return this.problem('E0405', `${name} expects bytes, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'bytes'));
787
+ return 'Bytes32';
788
+ }
789
+ if (name === 'abs' || name === 'sqrt' || name === 'log') {
790
+ if (args.length !== 1)
791
+ return this.problem('E0502', `${name} expects one numeric argument`, expr.span, frames);
792
+ const t = infer(args[0], scope, active, frames);
793
+ if (t === 'Error')
794
+ return 'Error';
795
+ if (!isNumeric(t))
796
+ return this.problem('E0405', `${name} expects Int or Amount`, expr.span, frames);
797
+ return name === 'abs' ? t : 'Int';
798
+ }
799
+ if (name === 'min' || name === 'max') {
800
+ if (args.length !== 2)
801
+ return this.problem('E0502', `${name} expects two numeric arguments`, expr.span, frames);
802
+ const a = infer(args[0], scope, active, frames), b = infer(args[1], scope, active, frames);
803
+ if (a === 'Error' || b === 'Error')
804
+ return 'Error';
805
+ if (!isNumeric(a) || !isNumeric(b))
806
+ return this.problem('E0405', `${name} expects Int or Amount`, expr.span, frames);
807
+ return a === 'Amount' || b === 'Amount' ? 'Amount' : 'Int';
808
+ }
809
+ if (name === 'mulpow2') {
810
+ if (args.length !== 2)
811
+ return this.problem('E0502', 'mulpow2 expects numeric value and Int exponent', expr.span, frames);
812
+ const a = infer(args[0], scope, active, frames), b = infer(args[1], scope, active, frames);
813
+ if (a === 'Error' || b === 'Error')
814
+ return 'Error';
815
+ if (!isNumeric(a) || b !== 'Int')
816
+ return this.problem('E0405', 'mulpow2 expects Int/Amount and Int', expr.span, frames);
817
+ return a;
818
+ }
819
+ if (name === 'within') {
820
+ if (args.length !== 3)
821
+ return this.problem('E0502', 'within expects value, low, high', expr.span, frames);
822
+ for (const arg of args) {
823
+ const t = infer(arg, scope, active, frames);
824
+ if (t === 'Error')
825
+ return 'Error';
826
+ if (!isNumeric(t))
827
+ return this.problem('E0405', 'within expects numeric arguments', arg.span, frames);
828
+ }
829
+ return 'Bool';
830
+ }
831
+ if (name === 'cat') {
832
+ if (args.length !== 2)
833
+ return this.problem('E0502', 'cat expects two byte values', expr.span, frames);
834
+ const a = infer(args[0], scope, active, frames), b = infer(args[1], scope, active, frames);
835
+ if (a === 'Error' || b === 'Error')
836
+ return 'Error';
837
+ if (!acceptsBytes(a) || !acceptsBytes(b)) {
838
+ const bad = !acceptsBytes(a) ? a : b;
839
+ const badSpan = !acceptsBytes(a) ? args[0].span : args[1].span;
840
+ return this.problem('E0405', `cat expects byte values, got ${bad}`, badSpan, frames, taggedHashHelp(bad, 'bytes'));
841
+ }
842
+ return 'Bytes(8192)';
843
+ }
844
+ if (name === 'size' || name === 'bin2num') {
845
+ if (args.length !== 1)
846
+ return this.problem('E0502', `${name} expects one byte value`, expr.span, frames);
847
+ const t = infer(args[0], scope, active, frames);
848
+ if (t === 'Error')
849
+ return 'Error';
850
+ if (!acceptsBytes(t))
851
+ return this.problem('E0405', `${name} expects bytes, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'bytes'));
852
+ return 'Int';
853
+ }
854
+ if (name === 'num2bin') {
855
+ if (args.length !== 2)
856
+ return this.problem('E0502', 'num2bin expects numeric value and Int width', expr.span, frames);
857
+ const a = infer(args[0], scope, active, frames), b = infer(args[1], scope, active, frames);
858
+ if (a === 'Error' || b === 'Error')
859
+ return 'Error';
860
+ if (!isNumeric(a) || b !== 'Int')
861
+ return this.problem('E0405', 'num2bin expects Int/Amount and Int', expr.span, frames);
862
+ return 'Bytes(8192)';
863
+ }
864
+ if (name === 'leaf_hash_bytes') {
865
+ if (args.length !== 1)
866
+ return this.problem('E0502', 'leaf_hash_bytes expects one byte value', expr.span, frames);
867
+ const t = infer(args[0], scope, active, frames);
868
+ if (t === 'Error')
869
+ return 'Error';
870
+ if (!acceptsBytes(t))
871
+ return this.problem('E0405', `leaf_hash_bytes expects bytes, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'bytes'));
872
+ return 'Bytes32';
873
+ }
874
+ if (name === 'node_hash') {
875
+ if (args.length !== 2)
876
+ return this.problem('E0502', 'node_hash expects two Bytes32 values', expr.span, frames);
877
+ const a = infer(args[0], scope, active, frames), b = infer(args[1], scope, active, frames);
878
+ if (a === 'Error' || b === 'Error')
879
+ return 'Error';
880
+ if (!comparable(a, 'Bytes32', this.resolvedEdition) || !comparable(b, 'Bytes32', this.resolvedEdition)) {
881
+ const bad = !comparable(a, 'Bytes32', this.resolvedEdition) ? a : b;
882
+ const badSpan = !comparable(a, 'Bytes32', this.resolvedEdition) ? args[0].span : args[1].span;
883
+ return this.problem('E0405', `node_hash expects 32-byte hashes, got ${bad}`, badSpan, frames, taggedHashHelp(bad, 'Bytes32'));
884
+ }
885
+ return 'Bytes32';
886
+ }
887
+ if (name === 'checkdatasig') {
888
+ if (args.length !== 4)
889
+ return this.problem('E0502', 'checkdatasig expects signature, message, key, algorithm', expr.span, frames);
890
+ const s = infer(args[0], scope, active, frames), m = infer(args[1], scope, active, frames), k = infer(args[2], scope, active, frames), alg = infer(args[3], scope, active, frames);
891
+ if (s === 'Error' || m === 'Error' || k === 'Error' || alg === 'Error')
892
+ return 'Error';
893
+ if (!acceptsBytes(s) || !acceptsBytes(m) || !acceptsBytes(k) || alg !== 'Int') {
894
+ const bad = !acceptsBytes(s) ? s : !acceptsBytes(m) ? m : !acceptsBytes(k) ? k : alg;
895
+ return this.problem('E0405', 'checkdatasig expects bytes signature, bytes message, bytes key, Int algorithm', expr.span, frames, taggedHashHelp(bad, 'bytes'));
896
+ }
897
+ return 'Bool';
898
+ }
899
+ if (name === 'sighash') {
900
+ if (args.length !== 1)
901
+ return this.problem('E0502', 'sighash expects Int mode', expr.span, frames);
902
+ const t = infer(args[0], scope, active, frames);
903
+ if (t === 'Error')
904
+ return 'Error';
905
+ if (t !== 'Int')
906
+ return this.problem('E0405', 'sighash expects Int mode', expr.span, frames);
907
+ return sigHashType;
908
+ }
909
+ if (name === 'state_hash') {
910
+ if (args.length > 64)
911
+ return this.problem('E0502', 'state_hash accepts at most 64 items', expr.span, frames);
912
+ for (const arg of args) {
913
+ const t = infer(arg, scope, active, frames);
914
+ if (t === 'Error')
915
+ return 'Error';
916
+ if (!acceptsBytes(t))
917
+ return this.problem('E0405', `state_hash items must be bytes, got ${t}`, arg.span, frames, taggedHashHelp(t, 'bytes'));
918
+ }
919
+ return stateRootType;
920
+ }
921
+ if (name === 'state_verify') {
922
+ if (c.kind === 'token')
923
+ return this.problem('E0411', 'state_verify requires a spend method', expr.span, frames);
924
+ if (args.length !== 1)
925
+ return this.problem('E0502', strictHashes ? 'state_verify expects StateRoot' : 'state_verify expects Bytes32 root', expr.span, frames);
926
+ const t = infer(args[0], scope, active, frames);
927
+ if (t === 'Error')
928
+ return 'Error';
929
+ if (!acceptsStateRoot(t)) {
930
+ return this.problem('E0405', strictHashes ? `state_verify expects StateRoot, got ${t}` : `state_verify expects Bytes32, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'StateRoot'));
931
+ }
932
+ return 'Bool';
933
+ }
934
+ if (name === 'enforce_output') {
935
+ if (args.length !== 2)
936
+ return this.problem('E0502', 'enforce_output expects template bytes and Int claim', expr.span, frames);
937
+ const a = infer(args[0], scope, active, frames), b = infer(args[1], scope, active, frames);
938
+ if (a === 'Error' || b === 'Error')
939
+ return 'Error';
940
+ if (!acceptsBytes(a) || b !== 'Int')
941
+ return this.problem('E0405', 'enforce_output expects bytes template and Int claim', expr.span, frames, !acceptsBytes(a) ? taggedHashHelp(a, 'bytes') : {});
942
+ return 'Bool';
943
+ }
944
+ if (name === 'tx_token_in' || name === 'tx_token_out') {
945
+ if (args.length !== 1)
946
+ return this.problem('E0502', strictHashes ? `${name} expects TokenId` : `${name} expects TokenId or Bytes32`, expr.span, frames);
947
+ const t = infer(args[0], scope, active, frames);
948
+ if (t === 'Error')
949
+ return 'Error';
950
+ if (!acceptsTokenId(t)) {
951
+ return this.problem('E0405', strictHashes ? `${name} expects TokenId, got ${t}` : `${name} expects TokenId or Bytes32, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'TokenId'));
952
+ }
953
+ return 'Amount';
954
+ }
955
+ if (name === 'bit_not') {
956
+ if (args.length !== 1)
957
+ return this.problem('E0502', 'bit_not expects one byte value', expr.span, frames);
958
+ const t = infer(args[0], scope, active, frames);
959
+ if (t === 'Error')
960
+ return 'Error';
961
+ if (!acceptsBytes(t))
962
+ return this.problem('E0405', `bit_not expects bytes, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'bytes'));
963
+ return 'Bytes(8192)';
964
+ }
965
+ if (name === 'bit_and' || name === 'bit_or' || name === 'bit_xor') {
966
+ if (args.length !== 2)
967
+ return this.problem('E0502', `${name} expects two byte values`, expr.span, frames);
968
+ const a = infer(args[0], scope, active, frames), b = infer(args[1], scope, active, frames);
969
+ if (a === 'Error' || b === 'Error')
970
+ return 'Error';
971
+ if (!acceptsBytes(a) || !acceptsBytes(b)) {
972
+ const bad = !acceptsBytes(a) ? a : b;
973
+ return this.problem('E0405', `${name} expects byte values, got ${bad}`, !acceptsBytes(a) ? args[0].span : args[1].span, frames, taggedHashHelp(bad, 'bytes'));
974
+ }
975
+ return 'Bytes(8192)';
976
+ }
977
+ if (name === 'bit_shl') {
978
+ if (args.length !== 2)
979
+ return this.problem('E0502', 'bit_shl expects bytes value and Int shift', expr.span, frames);
980
+ const a = infer(args[0], scope, active, frames), b = infer(args[1], scope, active, frames);
981
+ if (a === 'Error' || b === 'Error')
982
+ return 'Error';
983
+ if (!acceptsBytes(a) || b !== 'Int')
984
+ return this.problem('E0405', 'bit_shl expects bytes and Int shift', expr.span, frames, !acceptsBytes(a) ? taggedHashHelp(a, 'bytes') : {});
985
+ return 'Bytes(8192)';
986
+ }
987
+ if (name === 'merkle_root_sorted') {
988
+ if (args.length !== 3)
989
+ return this.problem('E0502', 'merkle_root_sorted expects leaf, proof, selector', expr.span, frames);
990
+ const leaf = infer(args[0], scope, active, frames), proof = infer(args[1], scope, active, frames), sel = infer(args[2], scope, active, frames);
991
+ if (leaf === 'Error' || proof === 'Error' || sel === 'Error')
992
+ return 'Error';
993
+ if (!comparable(leaf, 'Bytes32', this.resolvedEdition) || !acceptsBytes(proof) || sel !== 'Int') {
994
+ const bad = !comparable(leaf, 'Bytes32', this.resolvedEdition) ? leaf : !acceptsBytes(proof) ? proof : sel;
995
+ return this.problem('E0405', 'merkle_root_sorted expects Bytes32 leaf, bytes proof, Int selector', expr.span, frames, taggedHashHelp(bad, 'Bytes32'));
996
+ }
997
+ return 'Bytes32';
998
+ }
999
+ if (name === 'merkle_root_indexed') {
1000
+ if (args.length !== 4)
1001
+ return this.problem('E0502', 'merkle_root_indexed expects leaf, key, proof, selector', expr.span, frames);
1002
+ const leaf = infer(args[0], scope, active, frames), key = infer(args[1], scope, active, frames), proof = infer(args[2], scope, active, frames), sel = infer(args[3], scope, active, frames);
1003
+ if (leaf === 'Error' || key === 'Error' || proof === 'Error' || sel === 'Error')
1004
+ return 'Error';
1005
+ if (!comparable(leaf, 'Bytes32', this.resolvedEdition) || !acceptsBytes(key) || !acceptsBytes(proof) || sel !== 'Int') {
1006
+ const bad = !comparable(leaf, 'Bytes32', this.resolvedEdition) ? leaf : !acceptsBytes(key) ? key : !acceptsBytes(proof) ? proof : sel;
1007
+ return this.problem('E0405', 'merkle_root_indexed expects Bytes32 leaf, bytes key, bytes proof, Int selector', expr.span, frames, taggedHashHelp(bad, 'Bytes32'));
1008
+ }
1009
+ return 'Bytes32';
1010
+ }
1011
+ if (name.includes('.')) {
1012
+ const dotParts = name.split('.');
1013
+ const stateDecl = dotParts.length === 2 ? this.program.states?.get(dotParts[0]) : undefined;
1014
+ if (stateDecl) {
1015
+ const sm = dotParts[1];
1016
+ if (sm !== 'hash' && sm !== 'verify' && sm !== 'matches') {
1017
+ return this.problem('E0302', `unknown state method ${name}; expected hash, verify, or matches`, expr.span, frames);
1018
+ }
1019
+ if (sm === 'verify' && c.kind === 'token')
1020
+ return this.problem('E0411', `${name} requires a spend method`, expr.span, frames);
1021
+ const offset = sm === 'matches' ? 1 : 0;
1022
+ if (args.length !== stateDecl.fields.length + offset) {
1023
+ return this.problem('E0502', `${name} expects ${stateDecl.fields.length + offset} argument(s), got ${args.length}`, expr.span, frames);
1024
+ }
1025
+ if (sm === 'matches') {
1026
+ const ioType = infer(args[0], scope, active, frames);
1027
+ if (ioType === 'Error')
1028
+ return 'Error';
1029
+ if (ioType !== 'OutputIndex' && ioType !== 'InputIndex') {
1030
+ return this.problem('E0405', `${name} first argument must be an input or output, got ${ioType}`, args[0].span, frames, {
1031
+ labels: [{ span: args[0].span, message: `expected InputIndex or OutputIndex, found ${ioType}`, primary: true }],
1032
+ });
1033
+ }
1034
+ }
1035
+ for (let fi = 0; fi < stateDecl.fields.length; fi++) {
1036
+ const field = stateDecl.fields[fi];
1037
+ const argExpr = args[fi + offset];
1038
+ const actual = infer(argExpr, scope, active, frames);
1039
+ if (actual === 'Error')
1040
+ return 'Error';
1041
+ const ok = typeMatches(actual, field.type) || (isNumeric(actual) && isNumeric(field.type)) || comparable(actual, field.type, this.resolvedEdition);
1042
+ if (!ok) {
1043
+ return this.problem('E0405', `${stateDecl.name}.${field.name} expects ${field.type}, got ${actual}`, argExpr.span, frames, {
1044
+ ...taggedHashHelp(actual, field.type),
1045
+ labels: [{ span: argExpr.span, message: `expected ${field.type} for field '${field.name}', found ${actual}`, primary: true }],
1046
+ });
1047
+ }
1048
+ }
1049
+ return sm === 'hash' ? stateRootType : 'Bool';
1050
+ }
1051
+ }
1052
+ if (['mul128_wide', 'add_carry', 'sub_carry', 'split', 'less_swap', 'tx_token_balance'].includes(name)) {
1053
+ return this.problem('E0125', `${name} returns a 2-tuple; bind it with \`let (a, b) = ${name}(...);\``, expr.span, frames);
1054
+ }
1055
+ const helper = this.program.helpers.get(name);
1056
+ if (!helper)
1057
+ return this.problem('E0302', `unknown function ${name}`, expr.span, frames, this.hint(name, scope));
1058
+ if (helper.params.length !== args.length)
1059
+ return this.problem('E0501', `helper ${name} arity mismatch`, expr.span, frames);
1060
+ if (active.includes(name) || active.length >= 16)
1061
+ this.fatal('E0503', `recursive helper ${name}`, expr.span, frames);
1062
+ const inner = new Map();
1063
+ const next = [...frames, { name: helper.name, at: expr.span }];
1064
+ for (let i = 0; i < args.length; i++) {
1065
+ const p = helper.params[i], actual = infer(args[i], scope, active, frames);
1066
+ if (actual === 'Error')
1067
+ return 'Error';
1068
+ if (!typeMatches(actual, p.type))
1069
+ return this.problem('E0406', `helper ${name}.${p.name} expects ${p.type}, got ${actual}`, args[i].span, frames, taggedHashHelp(actual, p.type));
1070
+ inner.set(p.name, { kind: 'substitute', type: p.type, expr: args[i], env: scope, origin: expr.span, frames });
1071
+ }
1072
+ const result = inferBlock(helper.body, inner, [...active, name], next, true);
1073
+ if (result === 'Error')
1074
+ return 'Error';
1075
+ if (!typeMatches(result, helper.result))
1076
+ return this.problem('E0407', `helper ${name} returns ${result}, declared ${helper.result}`, helperReturn(helper.body)?.expr.span ?? helper.span, next, taggedHashHelp(result, helper.result));
1077
+ return helper.result;
1078
+ };
1079
+ // Compile-time value of an Int expression built from literals, bound
1080
+ // constructor values and helper arguments, or undefined if it depends on
1081
+ // the witness or the transaction.
1082
+ const constInt = (expr, scope, depth = 0) => {
1083
+ if (depth > 64)
1084
+ return undefined;
1085
+ if (expr.kind === 'number')
1086
+ return BigInt(expr.value);
1087
+ if (expr.kind === 'unary' && expr.value === '-') {
1088
+ const v = constInt(expr.right, scope, depth + 1);
1089
+ return v === undefined ? undefined : -v;
1090
+ }
1091
+ if (expr.kind === 'name') {
1092
+ const v = scope.get(expr.value);
1093
+ if (v?.kind === 'constant' && (v.type === 'Int' || v.type === 'Amount'))
1094
+ return decodedInt(v.data);
1095
+ if (v?.kind === 'substitute')
1096
+ return constInt(v.expr, v.env, depth + 1);
1097
+ return undefined;
1098
+ }
1099
+ if (expr.kind === 'binary' && ['+', '-', '*'].includes(expr.value)) {
1100
+ const a = constInt(expr.left, scope, depth + 1), b = constInt(expr.right, scope, depth + 1);
1101
+ if (a === undefined || b === undefined)
1102
+ return undefined;
1103
+ return expr.value === '+' ? a + b : expr.value === '-' ? a - b : a * b;
1104
+ }
1105
+ return undefined;
1106
+ };
1107
+ // P01/P03 lock rules. A refund path whose lock can never be met would
1108
+ // strand the coin, so constant kinds and bounds are checked here.
1109
+ const lockProblem = (name, args, scope, span, frames) => {
1110
+ if (name === 'check_sequence' && c.kind === 'token') {
1111
+ this.problem('E0418', 'check_sequence needs a consuming input; a mint has none (P03)', span, frames);
1112
+ return true;
1113
+ }
1114
+ const kind = constInt(args[0], scope);
1115
+ if (kind === undefined) {
1116
+ this.problem('E0415', `${name} kind must be a compile-time constant: 1 (block height) or 2 (${name === 'check_lock' ? 'median time past' : '512-second units'})`, args[0].span, frames, { notes: ['a kind chosen by the witness would let the spender pick the clock'] });
1117
+ return true;
1118
+ }
1119
+ if (kind !== 1n && kind !== 2n) {
1120
+ this.problem('E0416', `${name} kind ${kind} is not a P01 lock kind; use 1 (block height) or 2 (${name === 'check_lock' ? 'median time past' : '512-second units'})`, args[0].span, frames, { notes: ['the method could never be spent'] });
1121
+ return true;
1122
+ }
1123
+ const bound = constInt(args[1], scope);
1124
+ if (bound === undefined)
1125
+ return false;
1126
+ let message;
1127
+ if (name === 'check_sequence') {
1128
+ if (bound < 0n || bound > 65535n)
1129
+ message = `check_sequence bound ${bound} is outside 0..65535, the relative delay a sequence can encode (P01)`;
1130
+ }
1131
+ else if (bound < 0n)
1132
+ message = `check_lock bound ${bound} is negative`;
1133
+ else if (bound > (1n << 56n) - 1n)
1134
+ message = `check_lock bound ${bound} exceeds the 56-bit lock_value (P01)`;
1135
+ else if (kind === 1n && bound > 0xffffffffn)
1136
+ message = `check_lock height ${bound} exceeds the largest u32 block height (P01)`;
1137
+ if (!message)
1138
+ return false;
1139
+ this.problem('E0417', message, args[1].span, frames, { notes: ['the method could never be spent'] });
1140
+ return true;
1141
+ };
1142
+ let emitBlock;
1143
+ const expression = (expr, scope, origin, frames = []) => {
1144
+ emitter.frames = frames;
1145
+ if (expr.kind === 'number') {
1146
+ const n = BigInt(expr.value);
1147
+ if (n < INT_MIN || n >= INT_MAX)
1148
+ return this.problem('E0413', INT_RANGE, expr.span, frames);
1149
+ emitter.number(n, expr.span, origin);
1150
+ return 'Int';
1151
+ }
1152
+ if (expr.kind === 'bool') {
1153
+ emitter.number(expr.value === 'true' ? 1n : 0n, expr.span, origin);
1154
+ return 'Bool';
1155
+ }
1156
+ if (expr.kind === 'name') {
1157
+ if (expr.value === 'this.root') {
1158
+ emitter.op('BRANCHROOT', expr.span, origin, 1);
1159
+ return c.kind === 'token' ? 'TokenId' : 'ContractRootHash';
1160
+ }
1161
+ if (expr.value === 'this.input_index') {
1162
+ emitter.op('INPUTINDEX', expr.span, origin, 1);
1163
+ return 'Int';
1164
+ }
1165
+ if (expr.value === 'this.active_branch_index') {
1166
+ emitter.op('ACTIVEBRANCHINDEX', expr.span, origin, 1);
1167
+ return 'Int';
1168
+ }
1169
+ if (expr.value === 'tx.id') {
1170
+ emitter.op('TXID', expr.span, origin, 1);
1171
+ return txIdType;
1172
+ }
1173
+ if (expr.value === 'tx.chain_id') {
1174
+ emitter.op('CHAINID', expr.span, origin, 1);
1175
+ return chainIdType;
1176
+ }
1177
+ if (expr.value === 'tx.mint_count') {
1178
+ emitter.op('TXMINTCOUNT', expr.span, origin, 1);
1179
+ return 'Int';
1180
+ }
1181
+ if (expr.value === 'this.coin.token_id' || expr.value === 'this.coin.value' || expr.value === 'this.coin.txid' || expr.value === 'this.coin.vout' || expr.value === 'this.coin.path_index' || expr.value === 'this.coin.flags' || expr.value === 'this.coin.state_root') {
1182
+ if (c.kind === 'token')
1183
+ return this.problem('E0411', 'mint method has no coin', expr.span, frames);
1184
+ emitter.op('INPUTINDEX', expr.span, origin, 1);
1185
+ const field = expr.value.slice('this.coin.'.length);
1186
+ const opMap = {
1187
+ token_id: ['UTXOTOKENID', 'TokenId'],
1188
+ value: ['UTXOVALUE', 'Amount'],
1189
+ txid: ['OUTPOINTTXID', txIdType],
1190
+ vout: ['OUTPOINTINDEX', 'Int'],
1191
+ path_index: ['INPUTPATHINDEX', 'Int'],
1192
+ flags: ['UTXOFLAGS', 'Int'],
1193
+ state_root: ['UTXOSTATEROOT', stateRootType],
1194
+ };
1195
+ const [opName, resultType] = opMap[field];
1196
+ emitter.op(opName, expr.span, origin);
1197
+ return resultType;
1198
+ }
1199
+ const dot = expr.value.split('.');
1200
+ const recordFields = ['token_id', 'value', 'is_spend', 'txid', 'vout', 'path_index', 'flags', 'state_root'];
1201
+ const coinFields = ['token_id', 'value', 'txid', 'vout', 'path_index', 'flags', 'state_root'];
1202
+ if ((dot.length === 2 && recordFields.includes(dot[1])) || (dot.length === 3 && dot[1] === 'coin' && coinFields.includes(dot[2]))) {
1203
+ const v = scope.get(dot[0]);
1204
+ if (!v || v.kind !== 'local' || (v.type !== 'InputIndex' && v.type !== 'OutputIndex'))
1205
+ return this.problem('E0305', `unbound record ${dot[0]}`, expr.span, frames, this.hint(dot[0], scope));
1206
+ if (dot.length === 3 && v.type !== 'InputIndex')
1207
+ return this.problem('E0412', 'coin field requires input', expr.span, frames);
1208
+ const field = dot.at(-1);
1209
+ if ((field === 'is_spend' || field === 'txid' || field === 'vout' || field === 'path_index') && v.type !== 'InputIndex') {
1210
+ return this.problem('E0412', `${field} requires input`, expr.span, frames);
1211
+ }
1212
+ emitter.number(BigInt(emitter.height - 1 - v.index), expr.span, origin);
1213
+ emitter.op('PICK', expr.span, origin);
1214
+ if (field === 'is_spend') {
1215
+ emitter.op('INPUTFLAGS', expr.span, origin);
1216
+ emitter.number(1n, expr.span, origin);
1217
+ emitter.op('NUMEQUAL', expr.span, origin, -1);
1218
+ return 'Bool';
1219
+ }
1220
+ if (field === 'txid') {
1221
+ emitter.op('OUTPOINTTXID', expr.span, origin);
1222
+ return txIdType;
1223
+ }
1224
+ if (field === 'vout') {
1225
+ emitter.op('OUTPOINTINDEX', expr.span, origin);
1226
+ return 'Int';
1227
+ }
1228
+ if (field === 'path_index') {
1229
+ emitter.op('INPUTPATHINDEX', expr.span, origin);
1230
+ return 'Int';
1231
+ }
1232
+ if (field === 'flags') {
1233
+ emitter.op(v.type === 'OutputIndex' ? 'OUTPUTFLAGS' : 'UTXOFLAGS', expr.span, origin);
1234
+ return 'Int';
1235
+ }
1236
+ if (field === 'state_root') {
1237
+ emitter.op(v.type === 'OutputIndex' ? 'OUTPUTSTATEROOT' : 'UTXOSTATEROOT', expr.span, origin);
1238
+ return stateRootType;
1239
+ }
1240
+ const op = v.type === 'OutputIndex' ? (field === 'token_id' ? 'OUTPUTTOKENID' : 'OUTPUTVALUE') : (field === 'token_id' ? 'UTXOTOKENID' : 'UTXOVALUE');
1241
+ emitter.op(op, expr.span, origin);
1242
+ return field === 'token_id' ? 'TokenId' : 'Amount';
1243
+ }
1244
+ const v = scope.get(expr.value);
1245
+ if (!v)
1246
+ return this.problem('E0301', `unbound name ${expr.value}`, expr.span, frames, this.hint(expr.value, scope));
1247
+ if (v.kind === 'constant')
1248
+ emitter.push(v.data, expr.span, origin);
1249
+ else if (v.kind === 'argument' || v.kind === 'local') {
1250
+ emitter.number(BigInt(emitter.height - 1 - v.index), expr.span, origin);
1251
+ emitter.op('PICK', expr.span, origin);
1252
+ }
1253
+ else {
1254
+ const actual = expression(v.expr, v.env, v.origin, v.frames);
1255
+ if (actual === 'Error')
1256
+ return 'Error';
1257
+ if (!typeMatches(actual, v.type))
1258
+ return this.problem('E0406', `helper substitution expected ${v.type}, got ${actual}`, expr.span, frames, taggedHashHelp(actual, v.type));
1259
+ return v.type;
1260
+ }
1261
+ return v.type;
1262
+ }
1263
+ if (expr.kind === 'unary') {
1264
+ if (expr.value === '-' && expr.right?.kind === 'number') {
1265
+ const n = -BigInt(expr.right.value);
1266
+ if (n < INT_MIN || n >= INT_MAX)
1267
+ return this.problem('E0413', INT_RANGE, expr.span, frames);
1268
+ emitter.number(n, expr.span, origin);
1269
+ return 'Int';
1270
+ }
1271
+ const t = expression(expr.right, scope, origin, frames);
1272
+ if (t === 'Error')
1273
+ return 'Error';
1274
+ if (expr.value === '!' && t === 'Bool') {
1275
+ emitter.op('NOT', expr.span, origin);
1276
+ return 'Bool';
1277
+ }
1278
+ if (expr.value === '-' && t === 'Int') {
1279
+ emitter.op('NEGATE', expr.span, origin);
1280
+ return 'Int';
1281
+ }
1282
+ return this.problem('E0402', `invalid unary ${expr.value} on ${t}`, expr.span, frames);
1283
+ }
1284
+ if (expr.kind === 'index') {
1285
+ const target = expr.left;
1286
+ if (target.kind !== 'name' || (target.value !== 'tx.inputs' && target.value !== 'tx.outputs')) {
1287
+ return this.problem('E0412', 'indexing is only supported on tx.inputs[...] and tx.outputs[...]', target.span, frames, {
1288
+ labels: [{ span: target.span, message: 'expected tx.inputs or tx.outputs here', primary: true }],
1289
+ });
1290
+ }
1291
+ const idx = expression(expr.right, scope, origin, frames);
1292
+ if (idx === 'Error')
1293
+ return 'Error';
1294
+ if (idx !== 'Int') {
1295
+ return this.problem('E0405', `index must be Int, got ${idx}`, expr.right.span, frames, {
1296
+ labels: [{ span: expr.right.span, message: `expected Int index, found ${idx}`, primary: true }],
1297
+ });
1298
+ }
1299
+ return target.value === 'tx.inputs' ? 'InputIndex' : 'OutputIndex';
1300
+ }
1301
+ if (expr.kind === 'member') {
1302
+ const base = expression(expr.left, scope, origin, frames);
1303
+ if (base === 'Error')
1304
+ return 'Error';
1305
+ if (base !== 'InputIndex' && base !== 'OutputIndex') {
1306
+ return this.problem('E0412', `cannot access .${expr.value} on ${base}`, expr.span, frames, {
1307
+ labels: [{ span: expr.left.span, message: `expression has type ${base}`, primary: true }],
1308
+ });
1309
+ }
1310
+ const field = expr.value;
1311
+ if (field === 'coin') {
1312
+ if (base !== 'InputIndex')
1313
+ return this.problem('E0412', 'coin field requires an input', expr.span, frames);
1314
+ return 'InputIndex';
1315
+ }
1316
+ if (field === 'is_spend') {
1317
+ if (base !== 'InputIndex')
1318
+ return this.problem('E0412', 'is_spend requires an input', expr.span, frames);
1319
+ emitter.op('INPUTFLAGS', expr.span, origin);
1320
+ emitter.number(1n, expr.span, origin);
1321
+ emitter.op('NUMEQUAL', expr.span, origin, -1);
1322
+ return 'Bool';
1323
+ }
1324
+ if (field === 'txid' || field === 'vout' || field === 'path_index') {
1325
+ if (base !== 'InputIndex')
1326
+ return this.problem('E0412', `${field} requires an input`, expr.span, frames);
1327
+ emitter.op(field === 'txid' ? 'OUTPOINTTXID' : field === 'vout' ? 'OUTPOINTINDEX' : 'INPUTPATHINDEX', expr.span, origin);
1328
+ return field === 'txid' ? txIdType : 'Int';
1329
+ }
1330
+ if (field === 'flags') {
1331
+ emitter.op(base === 'OutputIndex' ? 'OUTPUTFLAGS' : 'UTXOFLAGS', expr.span, origin);
1332
+ return 'Int';
1333
+ }
1334
+ if (field === 'state_root') {
1335
+ emitter.op(base === 'OutputIndex' ? 'OUTPUTSTATEROOT' : 'UTXOSTATEROOT', expr.span, origin);
1336
+ return stateRootType;
1337
+ }
1338
+ if (field === 'token_id' || field === 'value') {
1339
+ const op = base === 'OutputIndex'
1340
+ ? (field === 'token_id' ? 'OUTPUTTOKENID' : 'OUTPUTVALUE')
1341
+ : (field === 'token_id' ? 'UTXOTOKENID' : 'UTXOVALUE');
1342
+ emitter.op(op, expr.span, origin);
1343
+ return field === 'token_id' ? 'TokenId' : 'Amount';
1344
+ }
1345
+ return this.problem('E0412', `unknown field .${field} on ${base}`, expr.span, frames);
1346
+ }
1347
+ if (expr.kind === 'member_call') {
1348
+ const base = expression(expr.left, scope, origin, frames);
1349
+ if (base === 'Error')
1350
+ return 'Error';
1351
+ if (base !== 'InputIndex' && base !== 'OutputIndex') {
1352
+ return this.problem('E0412', `cannot call .${expr.value}(...) on ${base}`, expr.span, frames, {
1353
+ labels: [{ span: expr.left.span, message: `expression has type ${base}`, primary: true }],
1354
+ });
1355
+ }
1356
+ const mname = expr.value, margs = expr.args ?? [];
1357
+ if (['branch', 'branch_count', 'path', 'path_count'].includes(mname)) {
1358
+ const indexed = mname === 'branch' || mname === 'path';
1359
+ const pathRead = mname === 'path' || mname === 'path_count';
1360
+ if (margs.length !== (indexed ? 1 : 0)) {
1361
+ return this.problem('E0405', `${mname} expects ${indexed ? 'one Int index' : 'no arguments'}`, expr.span, frames);
1362
+ }
1363
+ if (indexed) {
1364
+ const idx = expression(margs[0], scope, origin, frames);
1365
+ if (idx === 'Error')
1366
+ return 'Error';
1367
+ if (idx !== 'Int')
1368
+ return this.problem('E0405', `${mname} index must be Int, got ${idx}`, margs[0].span, frames);
1369
+ }
1370
+ const output = base === 'OutputIndex';
1371
+ const op = pathRead
1372
+ ? (output ? (indexed ? 'OUTPUTPATH' : 'OUTPUTPATHCOUNT') : (indexed ? 'UTXOPATH' : 'UTXOPATHCOUNT'))
1373
+ : (output ? (indexed ? 'OUTPUTBRANCH' : 'OUTPUTBRANCHCOUNT') : (indexed ? 'UTXOBRANCH' : 'UTXOBRANCHCOUNT'));
1374
+ emitter.op(op, expr.span, origin, indexed ? -1 : 0);
1375
+ return indexed ? (pathRead ? 'Bytes(8192)' : 'Bytes32') : 'Int';
1376
+ }
1377
+ if (['requires_branch', 'exclusive_branch', 'continues_branch'].includes(mname)) {
1378
+ if (mname !== 'requires_branch' && base !== 'OutputIndex') {
1379
+ return this.problem('E0412', `${mname} requires an output`, expr.span, frames);
1380
+ }
1381
+ if (margs.length !== 1)
1382
+ return this.problem('E0412', `${mname} expects one root argument`, expr.span, frames);
1383
+ const t = expression(margs[0], scope, origin, frames);
1384
+ if (t === 'Error')
1385
+ return 'Error';
1386
+ if (!acceptsBranchRoot(t)) {
1387
+ return this.problem('E0412', strictHashes
1388
+ ? `${mname} expects a BranchRoot or ContractRootHash, got ${t}`
1389
+ : `${mname} expects a BranchRoot, ContractRootHash, or Bytes32 root, got ${t}`, margs[0].span, frames, taggedHashHelp(t, 'BranchRoot'));
1390
+ }
1391
+ const op = base === 'InputIndex'
1392
+ ? 'UTXOREQUIRESBRANCH'
1393
+ : mname === 'exclusive_branch' ? 'OUTPUTEXCLUSIVEBRANCH'
1394
+ : mname === 'continues_branch' ? 'OUTPUTCONTINUESBRANCH'
1395
+ : 'OUTPUTREQUIRESBRANCH';
1396
+ emitter.op(op, expr.span, origin, -1);
1397
+ return 'Bool';
1398
+ }
1399
+ return this.problem('E0412', `unknown method .${mname}(...) on ${base}`, expr.span, frames);
1400
+ }
1401
+ if (expr.kind === 'binary') {
1402
+ if (expr.value === '&&' || expr.value === '||') {
1403
+ const a = expression(expr.left, scope, origin, frames);
1404
+ if (a === 'Error')
1405
+ return 'Error';
1406
+ if (a !== 'Bool')
1407
+ return this.problem('E0404', `${expr.value} requires Bool`, expr.left?.span ?? expr.span, frames);
1408
+ if (expr.value === '||')
1409
+ emitter.op('NOT', expr.span, origin);
1410
+ emitter.control('IF', expr.span);
1411
+ const before = emitter.height;
1412
+ const b = expression(expr.right, scope, origin, frames);
1413
+ if (b === 'Error')
1414
+ return 'Error';
1415
+ if (b !== 'Bool')
1416
+ return this.problem('E0404', `${expr.value} requires Bool`, expr.right?.span ?? expr.span, frames);
1417
+ if (emitter.height !== before + 1)
1418
+ this.fatal('E9001', 'logical branch stack mismatch', expr.span, frames);
1419
+ emitter.control('ELSE', expr.span);
1420
+ emitter.height = before;
1421
+ emitter.number(expr.value === '&&' ? 0n : 1n, expr.span, origin);
1422
+ emitter.control('ENDIF', expr.span);
1423
+ return 'Bool';
1424
+ }
1425
+ const a = expression(expr.left, scope, origin, frames);
1426
+ if (a === 'Error')
1427
+ return 'Error';
1428
+ const b = expression(expr.right, scope, origin, frames);
1429
+ if (b === 'Error') {
1430
+ emitter.op('DROP', expr.span, origin, -1);
1431
+ return 'Error';
1432
+ }
1433
+ if (expr.value === '==' || expr.value === '!=') {
1434
+ if (!comparable(a, b, this.resolvedEdition)) {
1435
+ return this.problem('E0401', `equality type mismatch ${a} and ${b}`, expr.span, frames, {
1436
+ ...taggedHashCompareHelp(a, b),
1437
+ labels: [
1438
+ { span: expr.left.span, message: `left operand has type ${a}` },
1439
+ { span: expr.right.span, message: `right operand has type ${b}`, primary: true },
1440
+ ],
1441
+ });
1442
+ }
1443
+ emitter.op('EQUAL', expr.span, origin, -1);
1444
+ if (expr.value === '!=')
1445
+ emitter.op('NOT', expr.span, origin);
1446
+ return 'Bool';
1447
+ }
1448
+ const cases = {
1449
+ '+': ['ADD', a], '-': ['SUB', a], '*': ['MUL', a], '/': ['DIV', a], '%': ['MOD', a],
1450
+ '<': ['LESSTHAN', 'Bool'], '>': ['GREATERTHAN', 'Bool'], '<=': ['LESSTHANOREQUAL', 'Bool'], '>=': ['GREATERTHANOREQUAL', 'Bool'],
1451
+ };
1452
+ const rule = cases[expr.value];
1453
+ if (!rule || !isNumeric(a) || !isNumeric(b)) {
1454
+ return this.problem('E0403', `invalid ${expr.value} operands ${a}, ${b}`, expr.span, frames, {
1455
+ labels: [
1456
+ { span: expr.left.span, message: `left operand has type ${a}` },
1457
+ { span: expr.right.span, message: `right operand has type ${b}`, primary: true },
1458
+ ],
1459
+ });
1460
+ }
1461
+ emitter.op(rule[0], expr.span, origin, -1);
1462
+ return ['+', '-', '*', '/', '%'].includes(expr.value) && (a === 'Amount' || b === 'Amount') ? 'Amount' : rule[1];
1463
+ }
1464
+ if (expr.kind !== 'call')
1465
+ return this.problem('E9001', 'unknown expression', expr.span, frames);
1466
+ const args = expr.args ?? [];
1467
+ const name = expr.value;
1468
+ if (name === 'bytes32') {
1469
+ if (args.length !== 1)
1470
+ return this.problem('E0502', 'bytes32 expects one 32-byte hash argument', expr.span, frames);
1471
+ const t = expression(args[0], scope, origin, frames);
1472
+ if (t === 'Error')
1473
+ return 'Error';
1474
+ if (t !== 'Bytes32' && !isTaggedHashType(t)) {
1475
+ emitter.op('DROP', expr.span, origin, -1);
1476
+ return this.problem('E0405', `bytes32 expects Bytes32 or a 32-byte tagged hash, got ${t}`, args[0].span, frames);
1477
+ }
1478
+ // Zero-cost explicit retyping: 0 VM instructions emitted.
1479
+ return 'Bytes32';
1480
+ }
1481
+ if (TAGGED_HASH_CONSTRUCTORS.has(name)) {
1482
+ const target = name;
1483
+ if (args.length !== 1)
1484
+ return this.problem('E0502', `${target} expects one Bytes32 argument`, expr.span, frames);
1485
+ const t = expression(args[0], scope, origin, frames);
1486
+ if (t === 'Error')
1487
+ return 'Error';
1488
+ if (t !== 'Bytes32' && !typeMatches(t, target)) {
1489
+ emitter.op('DROP', expr.span, origin, -1);
1490
+ return this.problem('E0405', `${target}(...) expects Bytes32${target === 'BranchRoot' ? ', BranchRoot, or ContractRootHash' : ` or ${target}`}, got ${t}`, args[0].span, frames, taggedHashHelp(t, target));
1491
+ }
1492
+ // Zero-cost explicit retyping: 0 VM instructions emitted.
1493
+ return target;
1494
+ }
1495
+ if (name === 'num_bytes') {
1496
+ if (args.length !== 1)
1497
+ return this.problem('E0405', 'num_bytes expects Int', expr.span, frames);
1498
+ if (expression(args[0], scope, origin, frames) !== 'Int')
1499
+ return this.problem('E0405', 'num_bytes expects Int', expr.span, frames);
1500
+ // Numeric ADD validates an adversarial witness as canonical P03 N.
1501
+ emitter.number(0n, expr.span, origin);
1502
+ emitter.op('ADD', expr.span, origin, -1);
1503
+ return 'Bytes(16)';
1504
+ }
1505
+ if (name === 'check_lock' || name === 'check_sequence') {
1506
+ if (args.length !== 2)
1507
+ return this.problem('E0405', `${name} expects Int kind and bound`, expr.span, frames);
1508
+ if (lockProblem(name, args, scope, expr.span, frames))
1509
+ return 'Error';
1510
+ const kind = expression(args[0], scope, origin, frames), bound = expression(args[1], scope, origin, frames);
1511
+ if (kind !== 'Int' || bound !== 'Int')
1512
+ return this.problem('E0405', `${name} expects Int kind and bound`, expr.span, frames);
1513
+ emitter.op(name === 'check_lock' ? 'CHECKLOCKTIMEVERIFY' : 'CHECKSEQUENCEVERIFY', expr.span, origin, -2);
1514
+ emitter.number(1n, expr.span, origin);
1515
+ return 'Bool';
1516
+ }
1517
+ if (['.branch', '.branch_count', '.path', '.path_count'].some(suffix => name.endsWith(suffix))) {
1518
+ const path = name.split('.'), current = path.slice(0, -1).join('.') === 'this.coin', receiver = scope.get(path[0]);
1519
+ if (current ? c.kind === 'token' : !(receiver?.kind === 'local' && ['InputIndex', 'OutputIndex'].includes(receiver.type) && (path.length === 2 || path.length === 3 && path[1] === 'coin' && receiver.type === 'InputIndex')))
1520
+ return this.problem('E0412', 'branch/path read requires a spend coin or enumerated input/output', expr.span, frames);
1521
+ const branch = name.endsWith('.branch') || name.endsWith('.path'), pathRead = name.endsWith('.path') || name.endsWith('.path_count');
1522
+ if (args.length !== (branch ? 1 : 0))
1523
+ return this.problem('E0405', 'branch/path expects one Int index; count takes no arguments', expr.span, frames);
1524
+ if (current)
1525
+ emitter.op('INPUTINDEX', expr.span, origin, 1);
1526
+ else {
1527
+ const v = receiver;
1528
+ if (v.kind !== 'local')
1529
+ return this.problem('E0412', 'branch/path read requires a local index', expr.span, frames);
1530
+ emitter.number(BigInt(emitter.height - 1 - v.index), expr.span, origin);
1531
+ emitter.op('PICK', expr.span, origin);
1532
+ }
1533
+ if (branch && expression(args[0], scope, origin, frames) !== 'Int')
1534
+ return this.problem('E0405', 'branch/path index must be Int', expr.span, frames);
1535
+ const output = !current && receiver.type === 'OutputIndex';
1536
+ const op = pathRead ? (output ? (branch ? 'OUTPUTPATH' : 'OUTPUTPATHCOUNT') : (branch ? 'UTXOPATH' : 'UTXOPATHCOUNT')) : (output ? (branch ? 'OUTPUTBRANCH' : 'OUTPUTBRANCHCOUNT') : (branch ? 'UTXOBRANCH' : 'UTXOBRANCHCOUNT'));
1537
+ emitter.op(op, expr.span, origin, branch ? -1 : 0);
1538
+ return branch ? (pathRead ? 'Bytes(8192)' : 'Bytes32') : 'Int';
1539
+ }
1540
+ if (name === 'leaf_hash') {
1541
+ if (args.length !== 1 || args[0].kind !== 'name')
1542
+ return this.problem('E0502', 'leaf_hash requires Contract.method name', expr.span, frames);
1543
+ const path = args[0].value.split('.');
1544
+ if (path.length !== 2)
1545
+ return this.problem('E0502', 'leaf_hash requires Contract.method name', expr.span, frames);
1546
+ emitter.push(this.method(path[0], path[1]).leaf, expr.span, origin);
1547
+ return 'MethodLeafHash';
1548
+ }
1549
+ if (name === 'contract_root' || name === 'merkle_root') {
1550
+ if (args.length !== 1 || args[0].kind !== 'name' || args[0].value.includes('.'))
1551
+ return this.problem('E0502', 'contract_root requires Contract name', expr.span, frames);
1552
+ const other = this.contract(args[0].value, args[0].span);
1553
+ emitter.push(this.root(other.name).root, expr.span, origin);
1554
+ return other.kind === 'token' ? 'TokenId' : 'ContractRootHash';
1555
+ }
1556
+ if (name.endsWith('.requires_branch') || name.endsWith('.exclusive_branch') || name.endsWith('.continues_branch')) {
1557
+ const parts = name.split('.'), v = scope.get(parts[0]);
1558
+ const inputPredicate = name.endsWith('.requires_branch') && v?.type === 'InputIndex';
1559
+ if (inputPredicate ? !(parts.length === 2 || parts.length === 3 && parts[1] === 'coin') : parts.length !== 2 || v?.type !== 'OutputIndex')
1560
+ return this.problem('E0412', 'branch predicate requires an enumerated input/output receiver', expr.span, frames);
1561
+ if (!v || v.kind !== 'local' || args.length !== 1)
1562
+ return this.problem('E0412', 'requires_branch requires output index and one root', expr.span, frames);
1563
+ emitter.number(BigInt(emitter.height - 1 - v.index), expr.span, origin);
1564
+ emitter.op('PICK', expr.span, origin);
1565
+ const t = expression(args[0], scope, origin, frames);
1566
+ if (t === 'Error')
1567
+ return 'Error';
1568
+ if (!acceptsBranchRoot(t))
1569
+ return this.problem('E0412', strictHashes
1570
+ ? `requires_branch expects a BranchRoot or ContractRootHash, got ${t}`
1571
+ : `requires_branch expects a BranchRoot, ContractRootHash, or Bytes32 root, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'BranchRoot'));
1572
+ emitter.op(inputPredicate ? 'UTXOREQUIRESBRANCH' : name.endsWith('.exclusive_branch') ? 'OUTPUTEXCLUSIVEBRANCH' : name.endsWith('.continues_branch') ? 'OUTPUTCONTINUESBRANCH' : 'OUTPUTREQUIRESBRANCH', expr.span, origin, -1);
1573
+ return 'Bool';
1574
+ }
1575
+ if (name === 'checksig') {
1576
+ if (args.length !== 2)
1577
+ return this.problem('E0502', 'checksig needs signature and PublicKey', expr.span, frames);
1578
+ const a = expression(args[0], scope, origin, frames), b = expression(args[1], scope, origin, frames);
1579
+ if (a === 'Error' || b === 'Error')
1580
+ return 'Error';
1581
+ if (a !== 'Signature' || b !== 'PublicKey')
1582
+ return this.problem('E0405', 'checksig expects Signature, PublicKey', expr.span, frames);
1583
+ emitter.op('CHECKSIG', expr.span, origin, -1);
1584
+ return 'Bool';
1585
+ }
1586
+ const hashes = { sha256: 'SHA256', hash256: 'HASH256', blake3: 'BLAKE3' };
1587
+ if (hashes[name]) {
1588
+ if (args.length !== 1)
1589
+ return this.problem('E0502', `${name} expects one byte value`, expr.span, frames);
1590
+ const t = expression(args[0], scope, origin, frames);
1591
+ if (t === 'Error')
1592
+ return 'Error';
1593
+ if (!acceptsBytes(t))
1594
+ return this.problem('E0405', `${name} expects byte value, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'bytes'));
1595
+ emitter.op(hashes[name], expr.span, origin);
1596
+ return 'Bytes32';
1597
+ }
1598
+ if (name === 'abs' || name === 'sqrt' || name === 'log') {
1599
+ if (args.length !== 1)
1600
+ return this.problem('E0502', `${name} expects one numeric argument`, expr.span, frames);
1601
+ const t = expression(args[0], scope, origin, frames);
1602
+ if (t === 'Error')
1603
+ return 'Error';
1604
+ if (!isNumeric(t))
1605
+ return this.problem('E0405', `${name} expects Int or Amount`, expr.span, frames);
1606
+ emitter.op(name === 'abs' ? 'ABS' : name === 'sqrt' ? 'SQRT' : 'LOG', expr.span, origin);
1607
+ return name === 'abs' ? t : 'Int';
1608
+ }
1609
+ if (name === 'min' || name === 'max') {
1610
+ if (args.length !== 2)
1611
+ return this.problem('E0502', `${name} expects two numeric arguments`, expr.span, frames);
1612
+ const a = expression(args[0], scope, origin, frames), b = expression(args[1], scope, origin, frames);
1613
+ if (a === 'Error' || b === 'Error')
1614
+ return 'Error';
1615
+ if (!isNumeric(a) || !isNumeric(b))
1616
+ return this.problem('E0405', `${name} expects Int or Amount`, expr.span, frames);
1617
+ emitter.op(name === 'min' ? 'MIN' : 'MAX', expr.span, origin, -1);
1618
+ return a === 'Amount' || b === 'Amount' ? 'Amount' : 'Int';
1619
+ }
1620
+ if (name === 'mulpow2') {
1621
+ if (args.length !== 2)
1622
+ return this.problem('E0502', 'mulpow2 expects numeric value and Int exponent', expr.span, frames);
1623
+ const a = expression(args[0], scope, origin, frames), b = expression(args[1], scope, origin, frames);
1624
+ if (a === 'Error' || b === 'Error')
1625
+ return 'Error';
1626
+ if (!isNumeric(a) || b !== 'Int')
1627
+ return this.problem('E0405', 'mulpow2 expects Int/Amount and Int', expr.span, frames);
1628
+ emitter.op('MULPOW2', expr.span, origin, -1);
1629
+ return a;
1630
+ }
1631
+ if (name === 'within') {
1632
+ if (args.length !== 3)
1633
+ return this.problem('E0502', 'within expects value, low, high', expr.span, frames);
1634
+ for (const arg of args) {
1635
+ const t = expression(arg, scope, origin, frames);
1636
+ if (t === 'Error')
1637
+ return 'Error';
1638
+ if (!isNumeric(t))
1639
+ return this.problem('E0405', 'within expects numeric arguments', arg.span, frames);
1640
+ }
1641
+ emitter.op('WITHIN', expr.span, origin, -2);
1642
+ return 'Bool';
1643
+ }
1644
+ if (name === 'cat') {
1645
+ if (args.length !== 2)
1646
+ return this.problem('E0502', 'cat expects two byte values', expr.span, frames);
1647
+ const a = expression(args[0], scope, origin, frames), b = expression(args[1], scope, origin, frames);
1648
+ if (a === 'Error' || b === 'Error')
1649
+ return 'Error';
1650
+ if (!acceptsBytes(a) || !acceptsBytes(b)) {
1651
+ const bad = !acceptsBytes(a) ? a : b;
1652
+ const badSpan = !acceptsBytes(a) ? args[0].span : args[1].span;
1653
+ return this.problem('E0405', `cat expects byte values, got ${bad}`, badSpan, frames, taggedHashHelp(bad, 'bytes'));
1654
+ }
1655
+ emitter.op('CAT', expr.span, origin, -1);
1656
+ return 'Bytes(8192)';
1657
+ }
1658
+ if (name === 'size') {
1659
+ if (args.length !== 1)
1660
+ return this.problem('E0502', 'size expects one byte value', expr.span, frames);
1661
+ const t = expression(args[0], scope, origin, frames);
1662
+ if (t === 'Error')
1663
+ return 'Error';
1664
+ if (!acceptsBytes(t))
1665
+ return this.problem('E0405', `size expects bytes, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'bytes'));
1666
+ // P03 SIZE peeks TOS and pushes length; NIP drops the original item.
1667
+ emitter.op('SIZE', expr.span, origin, 1);
1668
+ emitter.op('NIP', expr.span, origin, -1);
1669
+ return 'Int';
1670
+ }
1671
+ if (name === 'bin2num') {
1672
+ if (args.length !== 1)
1673
+ return this.problem('E0502', 'bin2num expects one byte value', expr.span, frames);
1674
+ const t = expression(args[0], scope, origin, frames);
1675
+ if (t === 'Error')
1676
+ return 'Error';
1677
+ if (!acceptsBytes(t))
1678
+ return this.problem('E0405', `bin2num expects bytes, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'bytes'));
1679
+ emitter.op('BIN2NUM', expr.span, origin);
1680
+ return 'Int';
1681
+ }
1682
+ if (name === 'num2bin') {
1683
+ if (args.length !== 2)
1684
+ return this.problem('E0502', 'num2bin expects numeric value and Int width', expr.span, frames);
1685
+ const a = expression(args[0], scope, origin, frames), b = expression(args[1], scope, origin, frames);
1686
+ if (a === 'Error' || b === 'Error')
1687
+ return 'Error';
1688
+ if (!isNumeric(a) || b !== 'Int')
1689
+ return this.problem('E0405', 'num2bin expects Int/Amount and Int', expr.span, frames);
1690
+ emitter.op('NUM2BIN', expr.span, origin, -1);
1691
+ return 'Bytes(8192)';
1692
+ }
1693
+ if (name === 'leaf_hash_bytes') {
1694
+ if (args.length !== 1)
1695
+ return this.problem('E0502', 'leaf_hash_bytes expects one byte value', expr.span, frames);
1696
+ const t = expression(args[0], scope, origin, frames);
1697
+ if (t === 'Error')
1698
+ return 'Error';
1699
+ if (!acceptsBytes(t))
1700
+ return this.problem('E0405', `leaf_hash_bytes expects bytes, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'bytes'));
1701
+ emitter.op('LEAFHASH', expr.span, origin);
1702
+ return 'Bytes32';
1703
+ }
1704
+ if (name === 'node_hash') {
1705
+ if (args.length !== 2)
1706
+ return this.problem('E0502', 'node_hash expects two Bytes32 values', expr.span, frames);
1707
+ const a = expression(args[0], scope, origin, frames), b = expression(args[1], scope, origin, frames);
1708
+ if (a === 'Error' || b === 'Error')
1709
+ return 'Error';
1710
+ if (!comparable(a, 'Bytes32', this.resolvedEdition) || !comparable(b, 'Bytes32', this.resolvedEdition)) {
1711
+ const bad = !comparable(a, 'Bytes32', this.resolvedEdition) ? a : b;
1712
+ const badSpan = !comparable(a, 'Bytes32', this.resolvedEdition) ? args[0].span : args[1].span;
1713
+ return this.problem('E0405', `node_hash expects 32-byte hashes, got ${bad}`, badSpan, frames, taggedHashHelp(bad, 'Bytes32'));
1714
+ }
1715
+ emitter.op('NODEHASH', expr.span, origin, -1);
1716
+ return 'Bytes32';
1717
+ }
1718
+ if (name === 'checkdatasig') {
1719
+ if (args.length !== 4)
1720
+ return this.problem('E0502', 'checkdatasig expects signature, message, key, algorithm', expr.span, frames);
1721
+ const s = expression(args[0], scope, origin, frames), m = expression(args[1], scope, origin, frames), k = expression(args[2], scope, origin, frames), alg = expression(args[3], scope, origin, frames);
1722
+ if (s === 'Error' || m === 'Error' || k === 'Error' || alg === 'Error')
1723
+ return 'Error';
1724
+ if (!acceptsBytes(s) || !acceptsBytes(m) || !acceptsBytes(k) || alg !== 'Int') {
1725
+ const bad = !acceptsBytes(s) ? s : !acceptsBytes(m) ? m : !acceptsBytes(k) ? k : alg;
1726
+ return this.problem('E0405', 'checkdatasig expects bytes signature, bytes message, bytes key, Int algorithm', expr.span, frames, taggedHashHelp(bad, 'bytes'));
1727
+ }
1728
+ emitter.op('CHECKDATASIG', expr.span, origin, -3);
1729
+ return 'Bool';
1730
+ }
1731
+ if (name === 'sighash') {
1732
+ if (args.length !== 1)
1733
+ return this.problem('E0502', 'sighash expects Int mode', expr.span, frames);
1734
+ const t = expression(args[0], scope, origin, frames);
1735
+ if (t === 'Error')
1736
+ return 'Error';
1737
+ if (t !== 'Int')
1738
+ return this.problem('E0405', 'sighash expects Int mode', expr.span, frames);
1739
+ emitter.op('SIGHASH', expr.span, origin);
1740
+ return sigHashType;
1741
+ }
1742
+ if (name === 'state_hash') {
1743
+ if (args.length > 64)
1744
+ return this.problem('E0502', 'state_hash accepts at most 64 items', expr.span, frames);
1745
+ for (const arg of args) {
1746
+ const t = expression(arg, scope, origin, frames);
1747
+ if (t === 'Error')
1748
+ return 'Error';
1749
+ if (!acceptsBytes(t))
1750
+ return this.problem('E0405', `state_hash items must be bytes, got ${t}`, arg.span, frames, taggedHashHelp(t, 'bytes'));
1751
+ }
1752
+ emitter.number(BigInt(args.length), expr.span, origin);
1753
+ emitter.op('STATEHASH', expr.span, origin, -args.length);
1754
+ return stateRootType;
1755
+ }
1756
+ if (name === 'state_verify') {
1757
+ if (c.kind === 'token')
1758
+ return this.problem('E0411', 'state_verify requires a spend method', expr.span, frames);
1759
+ if (args.length !== 1)
1760
+ return this.problem('E0502', strictHashes ? 'state_verify expects StateRoot' : 'state_verify expects Bytes32 root', expr.span, frames);
1761
+ const t = expression(args[0], scope, origin, frames);
1762
+ if (t === 'Error')
1763
+ return 'Error';
1764
+ if (!acceptsStateRoot(t)) {
1765
+ return this.problem('E0405', strictHashes ? `state_verify expects StateRoot, got ${t}` : `state_verify expects Bytes32, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'StateRoot'));
1766
+ }
1767
+ emitter.op('STATEVERIFY', expr.span, origin, -1);
1768
+ emitter.number(1n, expr.span, origin);
1769
+ return 'Bool';
1770
+ }
1771
+ if (name === 'enforce_output') {
1772
+ if (args.length !== 2)
1773
+ return this.problem('E0502', 'enforce_output expects template bytes and Int claim', expr.span, frames);
1774
+ const a = expression(args[0], scope, origin, frames), b = expression(args[1], scope, origin, frames);
1775
+ if (a === 'Error' || b === 'Error')
1776
+ return 'Error';
1777
+ if (!acceptsBytes(a) || b !== 'Int')
1778
+ return this.problem('E0405', 'enforce_output expects bytes template and Int claim', expr.span, frames, !acceptsBytes(a) ? taggedHashHelp(a, 'bytes') : {});
1779
+ emitter.op('ENFORCEOUTPUT', expr.span, origin, -2);
1780
+ emitter.number(1n, expr.span, origin);
1781
+ return 'Bool';
1782
+ }
1783
+ if (name === 'tx_token_in' || name === 'tx_token_out') {
1784
+ if (args.length !== 1)
1785
+ return this.problem('E0502', strictHashes ? `${name} expects TokenId` : `${name} expects TokenId or Bytes32`, expr.span, frames);
1786
+ const t = expression(args[0], scope, origin, frames);
1787
+ if (t === 'Error')
1788
+ return 'Error';
1789
+ if (!acceptsTokenId(t)) {
1790
+ return this.problem('E0405', strictHashes ? `${name} expects TokenId, got ${t}` : `${name} expects TokenId or Bytes32, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'TokenId'));
1791
+ }
1792
+ // TXTOKENBALANCE pops asset, pushes N(in) then N(out) (delta +1).
1793
+ emitter.op('TXTOKENBALANCE', expr.span, origin, 1);
1794
+ emitter.op(name === 'tx_token_in' ? 'DROP' : 'NIP', expr.span, origin, -1);
1795
+ return 'Amount';
1796
+ }
1797
+ if (name === 'bit_not') {
1798
+ if (args.length !== 1)
1799
+ return this.problem('E0502', 'bit_not expects one byte value', expr.span, frames);
1800
+ const t = expression(args[0], scope, origin, frames);
1801
+ if (t === 'Error')
1802
+ return 'Error';
1803
+ if (!acceptsBytes(t))
1804
+ return this.problem('E0405', `bit_not expects bytes, got ${t}`, args[0].span, frames, taggedHashHelp(t, 'bytes'));
1805
+ emitter.op('INVERT', expr.span, origin);
1806
+ return 'Bytes(8192)';
1807
+ }
1808
+ if (name === 'bit_and' || name === 'bit_or' || name === 'bit_xor') {
1809
+ if (args.length !== 2)
1810
+ return this.problem('E0502', `${name} expects two byte values`, expr.span, frames);
1811
+ const a = expression(args[0], scope, origin, frames), b = expression(args[1], scope, origin, frames);
1812
+ if (a === 'Error' || b === 'Error')
1813
+ return 'Error';
1814
+ if (!acceptsBytes(a) || !acceptsBytes(b)) {
1815
+ const bad = !acceptsBytes(a) ? a : b;
1816
+ return this.problem('E0405', `${name} expects byte values, got ${bad}`, !acceptsBytes(a) ? args[0].span : args[1].span, frames, taggedHashHelp(bad, 'bytes'));
1817
+ }
1818
+ emitter.op(name === 'bit_and' ? 'AND' : name === 'bit_or' ? 'OR' : 'XOR', expr.span, origin, -1);
1819
+ return 'Bytes(8192)';
1820
+ }
1821
+ if (name === 'bit_shl') {
1822
+ if (args.length !== 2)
1823
+ return this.problem('E0502', 'bit_shl expects bytes value and Int shift', expr.span, frames);
1824
+ const a = expression(args[0], scope, origin, frames), b = expression(args[1], scope, origin, frames);
1825
+ if (a === 'Error' || b === 'Error')
1826
+ return 'Error';
1827
+ if (!acceptsBytes(a) || b !== 'Int')
1828
+ return this.problem('E0405', 'bit_shl expects bytes and Int shift', expr.span, frames, !acceptsBytes(a) ? taggedHashHelp(a, 'bytes') : {});
1829
+ emitter.op('RAWLEFTBITSHIFT', expr.span, origin, -1);
1830
+ return 'Bytes(8192)';
1831
+ }
1832
+ if (name === 'merkle_root_sorted') {
1833
+ if (args.length !== 3)
1834
+ return this.problem('E0502', 'merkle_root_sorted expects leaf, proof, selector', expr.span, frames);
1835
+ const leaf = expression(args[0], scope, origin, frames), proof = expression(args[1], scope, origin, frames), sel = expression(args[2], scope, origin, frames);
1836
+ if (leaf === 'Error' || proof === 'Error' || sel === 'Error')
1837
+ return 'Error';
1838
+ if (!comparable(leaf, 'Bytes32', this.resolvedEdition) || !acceptsBytes(proof) || sel !== 'Int') {
1839
+ const bad = !comparable(leaf, 'Bytes32', this.resolvedEdition) ? leaf : !acceptsBytes(proof) ? proof : sel;
1840
+ return this.problem('E0405', 'merkle_root_sorted expects Bytes32 leaf, bytes proof, Int selector', expr.span, frames, taggedHashHelp(bad, 'Bytes32'));
1841
+ }
1842
+ emitter.op('MERKLEROOT_SORTED', expr.span, origin, -2);
1843
+ return 'Bytes32';
1844
+ }
1845
+ if (name === 'merkle_root_indexed') {
1846
+ if (args.length !== 4)
1847
+ return this.problem('E0502', 'merkle_root_indexed expects leaf, key, proof, selector', expr.span, frames);
1848
+ const leaf = expression(args[0], scope, origin, frames), key = expression(args[1], scope, origin, frames), proof = expression(args[2], scope, origin, frames), sel = expression(args[3], scope, origin, frames);
1849
+ if (leaf === 'Error' || key === 'Error' || proof === 'Error' || sel === 'Error')
1850
+ return 'Error';
1851
+ if (!comparable(leaf, 'Bytes32', this.resolvedEdition) || !acceptsBytes(key) || !acceptsBytes(proof) || sel !== 'Int') {
1852
+ const bad = !comparable(leaf, 'Bytes32', this.resolvedEdition) ? leaf : !acceptsBytes(key) ? key : !acceptsBytes(proof) ? proof : sel;
1853
+ return this.problem('E0405', 'merkle_root_indexed expects Bytes32 leaf, bytes key, bytes proof, Int selector', expr.span, frames, taggedHashHelp(bad, 'Bytes32'));
1854
+ }
1855
+ emitter.op('MERKLEROOT_INDEXED', expr.span, origin, -3);
1856
+ return 'Bytes32';
1857
+ }
1858
+ if (name.includes('.')) {
1859
+ const dotParts = name.split('.');
1860
+ const stateDecl = dotParts.length === 2 ? this.program.states?.get(dotParts[0]) : undefined;
1861
+ if (stateDecl) {
1862
+ const sm = dotParts[1];
1863
+ if (sm !== 'hash' && sm !== 'verify' && sm !== 'matches') {
1864
+ return this.problem('E0302', `unknown state method ${name}; expected hash, verify, or matches`, expr.span, frames);
1865
+ }
1866
+ if (sm === 'verify' && c.kind === 'token')
1867
+ return this.problem('E0411', `${name} requires a spend method`, expr.span, frames);
1868
+ const offset = sm === 'matches' ? 1 : 0;
1869
+ if (args.length !== stateDecl.fields.length + offset) {
1870
+ return this.problem('E0502', `${name} expects ${stateDecl.fields.length + offset} argument(s), got ${args.length}`, expr.span, frames);
1871
+ }
1872
+ const emitStateHash = () => {
1873
+ const startH = emitter.height;
1874
+ for (let fi = 0; fi < stateDecl.fields.length; fi++) {
1875
+ const field = stateDecl.fields[fi];
1876
+ const argExpr = args[fi + offset];
1877
+ const actual = expression(argExpr, scope, origin, frames);
1878
+ if (actual === 'Error') {
1879
+ while (emitter.height > startH)
1880
+ emitter.op('DROP', expr.span, origin, -1);
1881
+ return false;
1882
+ }
1883
+ const ok = typeMatches(actual, field.type) || (isNumeric(actual) && isNumeric(field.type)) || comparable(actual, field.type, this.resolvedEdition);
1884
+ if (!ok) {
1885
+ this.problem('E0405', `${stateDecl.name}.${field.name} expects ${field.type}, got ${actual}`, argExpr.span, frames, {
1886
+ ...taggedHashHelp(actual, field.type),
1887
+ labels: [{ span: argExpr.span, message: `expected ${field.type} for field '${field.name}', found ${actual}`, primary: true }],
1888
+ });
1889
+ while (emitter.height > startH)
1890
+ emitter.op('DROP', expr.span, origin, -1);
1891
+ return false;
1892
+ }
1893
+ if (isNumeric(field.type) || field.type === 'Bool') {
1894
+ emitter.number(16n, argExpr.span, origin);
1895
+ emitter.op('NUM2BIN', argExpr.span, origin, -1);
1896
+ }
1897
+ }
1898
+ emitter.number(BigInt(stateDecl.fields.length), expr.span, origin);
1899
+ emitter.op('STATEHASH', expr.span, origin, -stateDecl.fields.length);
1900
+ return true;
1901
+ };
1902
+ if (sm === 'hash') {
1903
+ return emitStateHash() ? stateRootType : 'Error';
1904
+ }
1905
+ if (sm === 'verify') {
1906
+ if (stateDecl.mode === 'inline') {
1907
+ if (!emitStateHash())
1908
+ return 'Error';
1909
+ emitter.op('STATEVERIFY', expr.span, origin, -1);
1910
+ emitter.number(1n, expr.span, origin);
1911
+ return 'Bool';
1912
+ }
1913
+ emitter.op('INPUTINDEX', expr.span, origin, 1);
1914
+ emitter.op('UTXOBRANCHCOUNT', expr.span, origin);
1915
+ emitter.number(2n, expr.span, origin);
1916
+ emitter.op('NUMEQUAL', expr.span, origin, -1);
1917
+ emitter.control('IF', expr.span, origin);
1918
+ const before = emitter.height;
1919
+ emitter.op('INPUTINDEX', expr.span, origin, 1);
1920
+ emitter.number(1n, expr.span, origin);
1921
+ emitter.op('UTXOBRANCH', expr.span, origin, -1);
1922
+ if (!emitStateHash()) {
1923
+ emitter.op('DROP', expr.span, origin, -1);
1924
+ emitter.number(0n, expr.span, origin);
1925
+ emitter.control('ELSE', expr.span, origin);
1926
+ emitter.height = before;
1927
+ emitter.number(0n, expr.span, origin);
1928
+ emitter.control('ENDIF', expr.span, origin);
1929
+ emitter.op('DROP', expr.span, origin, -1);
1930
+ return 'Error';
1931
+ }
1932
+ emitter.op('EQUAL', expr.span, origin, -1);
1933
+ emitter.control('ELSE', expr.span, origin);
1934
+ emitter.height = before;
1935
+ emitter.number(0n, expr.span, origin);
1936
+ emitter.control('ENDIF', expr.span, origin);
1937
+ return 'Bool';
1938
+ }
1939
+ const ioType = expression(args[0], scope, origin, frames);
1940
+ if (ioType === 'Error')
1941
+ return 'Error';
1942
+ if (ioType !== 'OutputIndex' && ioType !== 'InputIndex') {
1943
+ emitter.op('DROP', expr.span, origin, -1);
1944
+ return this.problem('E0405', `${name} first argument must be an input or output, got ${ioType}`, args[0].span, frames, {
1945
+ labels: [{ span: args[0].span, message: `expected InputIndex or OutputIndex, found ${ioType}`, primary: true }],
1946
+ });
1947
+ }
1948
+ const isOut = ioType === 'OutputIndex';
1949
+ if (stateDecl.mode === 'inline') {
1950
+ emitter.op(isOut ? 'OUTPUTSTATEROOT' : 'UTXOSTATEROOT', expr.span, origin);
1951
+ if (!emitStateHash()) {
1952
+ emitter.op('DROP', expr.span, origin, -1);
1953
+ return 'Error';
1954
+ }
1955
+ emitter.op('EQUAL', expr.span, origin, -1);
1956
+ return 'Bool';
1957
+ }
1958
+ emitter.op('DUP', expr.span, origin, 1);
1959
+ emitter.op(isOut ? 'OUTPUTBRANCHCOUNT' : 'UTXOBRANCHCOUNT', expr.span, origin);
1960
+ emitter.number(2n, expr.span, origin);
1961
+ emitter.op('NUMEQUAL', expr.span, origin, -1);
1962
+ emitter.control('IF', expr.span, origin);
1963
+ const before = emitter.height;
1964
+ emitter.number(1n, expr.span, origin);
1965
+ emitter.op(isOut ? 'OUTPUTBRANCH' : 'UTXOBRANCH', expr.span, origin, -1);
1966
+ if (!emitStateHash()) {
1967
+ emitter.op('DROP', expr.span, origin, -1);
1968
+ emitter.number(0n, expr.span, origin);
1969
+ emitter.control('ELSE', expr.span, origin);
1970
+ emitter.height = before;
1971
+ emitter.op('DROP', expr.span, origin, -1);
1972
+ emitter.number(0n, expr.span, origin);
1973
+ emitter.control('ENDIF', expr.span, origin);
1974
+ emitter.op('DROP', expr.span, origin, -1);
1975
+ return 'Error';
1976
+ }
1977
+ emitter.op('EQUAL', expr.span, origin, -1);
1978
+ emitter.control('ELSE', expr.span, origin);
1979
+ emitter.height = before;
1980
+ emitter.op('DROP', expr.span, origin, -1);
1981
+ emitter.number(0n, expr.span, origin);
1982
+ emitter.control('ENDIF', expr.span, origin);
1983
+ return 'Bool';
1984
+ }
1985
+ }
1986
+ if (['mul128_wide', 'add_carry', 'sub_carry', 'split', 'less_swap', 'tx_token_balance'].includes(name)) {
1987
+ return this.problem('E0125', `${name} returns a 2-tuple; bind it with \`let (a, b) = ${name}(...);\``, expr.span, frames);
1988
+ }
1989
+ const helper = this.program.helpers.get(name);
1990
+ if (!helper)
1991
+ return this.problem('E0302', `unknown function ${name}`, expr.span, frames, this.hint(name, scope));
1992
+ if (helper.params.length !== args.length)
1993
+ return this.problem('E0501', `helper ${name} arity mismatch`, expr.span, frames);
1994
+ if (helperStack.includes(name))
1995
+ this.fatal('E0503', `recursive helper ${name}`, expr.span, frames);
1996
+ if (++emitter.expansions > MAX_EXPANSIONS || helperStack.length >= 16)
1997
+ this.fatal('E0703', 'helper expansion budget exceeded', expr.span, frames);
1998
+ const inner = new Map();
1999
+ // Each helper parameter is a hygienically scoped expression thunk. The
2000
+ // source argument is checked against the declared parameter type once.
2001
+ // `frames` stays the caller's chain; the body is checked under `next`.
2002
+ for (let i = 0; i < args.length; i++) {
2003
+ const p = helper.params[i];
2004
+ const actual = infer(args[i], scope, helperStack, frames);
2005
+ if (actual === 'Error')
2006
+ return 'Error';
2007
+ if (!typeMatches(actual, p.type))
2008
+ return this.problem('E0406', `helper ${name}.${p.name} expects ${p.type}, got ${actual}`, args[i].span, frames, taggedHashHelp(actual, p.type));
2009
+ inner.set(p.name, { kind: 'substitute', type: p.type, expr: args[i], env: scope, origin: expr.span, frames });
2010
+ }
2011
+ const next = [...frames, { name: helper.name, at: expr.span }];
2012
+ helperStack.push(name);
2013
+ try {
2014
+ const result = emitBlock(helper.body, inner, expr.span, next, true);
2015
+ if (result === 'Error')
2016
+ return 'Error';
2017
+ if (!typeMatches(result, helper.result))
2018
+ return this.problem('E0407', `helper ${name} returns ${result}, declared ${helper.result}`, helperReturn(helper.body)?.expr.span ?? helper.span, next, taggedHashHelp(result, helper.result));
2019
+ return helper.result;
2020
+ }
2021
+ finally {
2022
+ helperStack.pop();
2023
+ }
2024
+ };
2025
+ // Split only a require operand. Each conjunct is verified immediately, so
2026
+ // CHECKSIG/EQUAL sit next to VERIFY. `||` is left as a short-circuit.
2027
+ const emitRequire = (expr, scope, origin, frames, span) => {
2028
+ for (const part of conjuncts(expr)) {
2029
+ const t = expression(part, scope, origin, frames);
2030
+ if (t === 'Error')
2031
+ continue;
2032
+ if (t !== 'Bool') {
2033
+ this.problem('E0404', `require requires Bool, got ${t}`, part.span, frames);
2034
+ emitter.op('DROP', part.span, origin, -1);
2035
+ continue;
2036
+ }
2037
+ emitter.op('VERIFY', span, origin, -1);
2038
+ }
2039
+ };
2040
+ const emitTupleCall = (expr, scope, origin, frames) => {
2041
+ const startHeight = emitter.height;
2042
+ const unwind = () => {
2043
+ while (emitter.height > startHeight)
2044
+ emitter.op('DROP', expr.span, origin, -1);
2045
+ return 'Error';
2046
+ };
2047
+ if (expr.kind !== 'call') {
2048
+ this.problem('E0125', 'tuple destructuring requires a multi-return builtin call (mul128_wide, add_carry, sub_carry, split, less_swap, tx_token_balance)', expr.span, frames);
2049
+ return unwind();
2050
+ }
2051
+ const name = expr.value, args = expr.args ?? [];
2052
+ if (name === 'mul128_wide') {
2053
+ if (args.length !== 2) {
2054
+ this.problem('E0502', 'mul128_wide expects two numeric/byte operands', expr.span, frames);
2055
+ return unwind();
2056
+ }
2057
+ const a = expression(args[0], scope, origin, frames), b = expression(args[1], scope, origin, frames);
2058
+ if (a === 'Error' || b === 'Error')
2059
+ return unwind();
2060
+ if ((!isNumeric(a) && !acceptsBytes(a)) || (!isNumeric(b) && !acceptsBytes(b))) {
2061
+ const bad = (!isNumeric(a) && !acceptsBytes(a)) ? a : b;
2062
+ this.problem('E0405', 'mul128_wide expects Int/Amount or bytes operands', expr.span, frames, taggedHashHelp(bad, 'bytes'));
2063
+ return unwind();
2064
+ }
2065
+ // MUL128_WIDE pops b, a -> pushes high, low (delta 0).
2066
+ emitter.op('MUL128_WIDE', expr.span, origin, 0);
2067
+ return ['Bytes(8192)', 'Bytes(8192)'];
2068
+ }
2069
+ if (name === 'add_carry' || name === 'sub_carry') {
2070
+ if (args.length !== 3) {
2071
+ this.problem('E0502', `${name} expects a, b, and carry/borrow Int`, expr.span, frames);
2072
+ return unwind();
2073
+ }
2074
+ const a = expression(args[0], scope, origin, frames), b = expression(args[1], scope, origin, frames), cIn = expression(args[2], scope, origin, frames);
2075
+ if (a === 'Error' || b === 'Error' || cIn === 'Error')
2076
+ return unwind();
2077
+ if ((!isNumeric(a) && !acceptsBytes(a)) || (!isNumeric(b) && !acceptsBytes(b)) || cIn !== 'Int') {
2078
+ const bad = (!isNumeric(a) && !acceptsBytes(a)) ? a : (!isNumeric(b) && !acceptsBytes(b)) ? b : cIn;
2079
+ this.problem('E0405', `${name} expects Int/Amount/bytes operands and Int carry`, expr.span, frames, taggedHashHelp(bad, 'bytes'));
2080
+ return unwind();
2081
+ }
2082
+ // ADDCARRY/SUBCARRY pops carry, b, a -> pushes out, flag (delta -1).
2083
+ emitter.op(name === 'add_carry' ? 'ADDCARRY' : 'SUBCARRY', expr.span, origin, -1);
2084
+ return ['Bytes(8192)', 'Int'];
2085
+ }
2086
+ if (name === 'split') {
2087
+ if (args.length !== 2) {
2088
+ this.problem('E0502', 'split expects bytes value and Int offset', expr.span, frames);
2089
+ return unwind();
2090
+ }
2091
+ const a = expression(args[0], scope, origin, frames), b = expression(args[1], scope, origin, frames);
2092
+ if (a === 'Error' || b === 'Error')
2093
+ return unwind();
2094
+ if (!acceptsBytes(a) || b !== 'Int') {
2095
+ this.problem('E0405', 'split expects bytes and Int offset', expr.span, frames, !acceptsBytes(a) ? taggedHashHelp(a, 'bytes') : {});
2096
+ return unwind();
2097
+ }
2098
+ // SPLIT pops offset, value -> pushes left, right (delta 0).
2099
+ emitter.op('SPLIT', expr.span, origin, 0);
2100
+ return ['Bytes(8192)', 'Bytes(8192)'];
2101
+ }
2102
+ if (name === 'less_swap') {
2103
+ if (args.length !== 2) {
2104
+ this.problem('E0502', 'less_swap expects two byte values', expr.span, frames);
2105
+ return unwind();
2106
+ }
2107
+ const a = expression(args[0], scope, origin, frames), b = expression(args[1], scope, origin, frames);
2108
+ if (a === 'Error' || b === 'Error')
2109
+ return unwind();
2110
+ if (!acceptsBytes(a) || !acceptsBytes(b)) {
2111
+ this.problem('E0405', 'less_swap expects byte values', expr.span, frames, taggedHashHelp(!acceptsBytes(a) ? a : b, 'bytes'));
2112
+ return unwind();
2113
+ }
2114
+ // LESSSWAP pops b, a -> pushes smaller, larger (delta 0).
2115
+ emitter.op('LESSSWAP', expr.span, origin, 0);
2116
+ return [a === b ? a : 'Bytes(8192)', a === b ? b : 'Bytes(8192)'];
2117
+ }
2118
+ if (name === 'tx_token_balance') {
2119
+ if (args.length !== 1) {
2120
+ this.problem('E0502', strictHashes ? 'tx_token_balance expects TokenId' : 'tx_token_balance expects TokenId or Bytes32', expr.span, frames);
2121
+ return unwind();
2122
+ }
2123
+ const a = expression(args[0], scope, origin, frames);
2124
+ if (a === 'Error')
2125
+ return unwind();
2126
+ if (!acceptsTokenId(a)) {
2127
+ this.problem('E0405', strictHashes ? `tx_token_balance expects TokenId, got ${a}` : `tx_token_balance expects TokenId or Bytes32, got ${a}`, args[0].span, frames, taggedHashHelp(a, 'TokenId'));
2128
+ return unwind();
2129
+ }
2130
+ // TXTOKENBALANCE pops asset -> pushes N(in), N(out) (delta +1).
2131
+ emitter.op('TXTOKENBALANCE', expr.span, origin, 1);
2132
+ return ['Amount', 'Amount'];
2133
+ }
2134
+ this.problem('E0125', `function ${name} does not return a 2-tuple`, expr.span, frames);
2135
+ return unwind();
2136
+ };
2137
+ emitBlock = (body, scope, origin, frames, returning) => {
2138
+ const introduced = [];
2139
+ const forget = () => { for (const name of introduced)
2140
+ scope.delete(name); introduced.length = 0; };
2141
+ const dropTop = (span) => {
2142
+ for (let n = introduced.length; n > 0; n--)
2143
+ emitter.op('DROP', span, origin, -1);
2144
+ forget();
2145
+ };
2146
+ // Locals sit under the return value. ROLL 1 brings each one to the top.
2147
+ const buryReturn = (span) => {
2148
+ for (let n = introduced.length; n > 0; n--) {
2149
+ emitter.number(1n, span, origin);
2150
+ emitter.op('ROLL', span, origin, -1);
2151
+ emitter.op('DROP', span, origin, -1);
2152
+ }
2153
+ forget();
2154
+ };
2155
+ try {
2156
+ for (const stmt of body) {
2157
+ if (stmt.kind === 'let') {
2158
+ if (scope.has(stmt.name)) {
2159
+ this.problem('E0208', `let ${stmt.name} shadows a binding`, stmt.nameSpan, frames);
2160
+ continue;
2161
+ }
2162
+ const t = expression(stmt.expr, scope, origin, frames);
2163
+ if (t === 'Error')
2164
+ continue;
2165
+ if (!typeMatches(t, stmt.type)) {
2166
+ this.problem('E0414', `let ${stmt.name} expects ${stmt.type}, got ${t}`, stmt.expr.span, frames, taggedHashHelp(t, stmt.type));
2167
+ emitter.op('DROP', stmt.span, origin, -1);
2168
+ continue;
2169
+ }
2170
+ scope.set(stmt.name, { kind: 'local', type: stmt.type, index: emitter.height - 1 });
2171
+ introduced.push(stmt.name);
2172
+ }
2173
+ else if (stmt.kind === 'let_tuple') {
2174
+ const [va, vb] = stmt.variables;
2175
+ if (scope.has(va.name)) {
2176
+ this.problem('E0208', `let ${va.name} shadows a binding`, va.span, frames);
2177
+ continue;
2178
+ }
2179
+ if (scope.has(vb.name)) {
2180
+ this.problem('E0208', `let ${vb.name} shadows a binding`, vb.span, frames);
2181
+ continue;
2182
+ }
2183
+ const pair = emitTupleCall(stmt.expr, scope, origin, frames);
2184
+ if (pair === 'Error')
2185
+ continue;
2186
+ scope.set(va.name, { kind: 'local', type: pair[0], index: emitter.height - 2 });
2187
+ scope.set(vb.name, { kind: 'local', type: pair[1], index: emitter.height - 1 });
2188
+ introduced.push(va.name, vb.name);
2189
+ }
2190
+ else if (stmt.kind === 'require')
2191
+ emitRequire(stmt.expr, scope, origin, frames, stmt.span);
2192
+ else if (stmt.kind === 'if') {
2193
+ const t = expression(stmt.expr, scope, origin, frames);
2194
+ if (t === 'Error')
2195
+ continue;
2196
+ if (t !== 'Bool') {
2197
+ this.problem('E0404', `if requires Bool, got ${t}`, stmt.expr.span, frames);
2198
+ emitter.op('DROP', stmt.span, origin, -1);
2199
+ continue;
2200
+ }
2201
+ emitter.control('IF', stmt.span, origin);
2202
+ const before = emitter.height;
2203
+ if (emitBlock(stmt.then, scope, origin, frames, false) === 'Error')
2204
+ return 'Error';
2205
+ if (emitter.height !== before)
2206
+ this.fatal('E9001', 'then stack mismatch', stmt.span, frames);
2207
+ emitter.control('ELSE', stmt.span, origin);
2208
+ if (emitBlock(stmt.otherwise, scope, origin, frames, false) === 'Error')
2209
+ return 'Error';
2210
+ if (emitter.height !== before)
2211
+ this.fatal('E9001', 'else stack mismatch', stmt.span, frames);
2212
+ emitter.control('ENDIF', stmt.span, origin);
2213
+ }
2214
+ else {
2215
+ if (!returning)
2216
+ return this.problem('E0123', 'return must be the final statement of the helper', stmt.span, frames);
2217
+ const t = expression(stmt.expr, scope, origin, frames);
2218
+ if (t === 'Error')
2219
+ return 'Error';
2220
+ buryReturn(stmt.span);
2221
+ return t;
2222
+ }
2223
+ }
2224
+ if (returning)
2225
+ return this.problem('E0123', 'helper must end with return', body.at(-1)?.span ?? frames.at(-1)?.at, frames);
2226
+ dropTop(body.at(-1)?.span ?? frames.at(-1)?.at ?? { start: 0, end: 0 });
2227
+ return 'Bool';
2228
+ }
2229
+ finally {
2230
+ for (const name of introduced)
2231
+ scope.delete(name);
2232
+ }
2233
+ };
2234
+ const statements = (body, nested = false, loopBaseHeight) => {
2235
+ const introduced = [];
2236
+ try {
2237
+ for (let idx = 0; idx < body.length; idx++) {
2238
+ const stmt = body[idx];
2239
+ if (stmt.kind === 'break') {
2240
+ if (loopBaseHeight === undefined)
2241
+ this.fatal('E0124', 'break is only allowed inside a for loop', stmt.span);
2242
+ if (idx !== body.length - 1)
2243
+ this.fatal('E0124', 'unreachable statement after break', body[idx + 1].span);
2244
+ const savedHeight = emitter.height;
2245
+ for (let d = emitter.height - loopBaseHeight; d > 0; d--)
2246
+ emitter.op('DROP', stmt.span, undefined, -1);
2247
+ emitter.number(1n, stmt.span);
2248
+ emitter.number(1n, stmt.span);
2249
+ emitter.op('BREAK', stmt.span, undefined, -2);
2250
+ emitter.height = savedHeight;
2251
+ continue;
2252
+ }
2253
+ if (stmt.kind === 'let_tuple') {
2254
+ const [va, vb] = stmt.variables;
2255
+ if (env.has(va.name)) {
2256
+ this.problem('E0208', `let ${va.name} shadows a binding`, va.span);
2257
+ continue;
2258
+ }
2259
+ if (env.has(vb.name)) {
2260
+ this.problem('E0208', `let ${vb.name} shadows a binding`, vb.span);
2261
+ continue;
2262
+ }
2263
+ const pair = emitTupleCall(stmt.expr, env, undefined, []);
2264
+ if (pair === 'Error')
2265
+ continue;
2266
+ env.set(va.name, { kind: 'local', type: pair[0], index: emitter.height - 2 });
2267
+ env.set(vb.name, { kind: 'local', type: pair[1], index: emitter.height - 1 });
2268
+ if (nested)
2269
+ introduced.push(va.name, vb.name);
2270
+ continue;
2271
+ }
2272
+ if (stmt.kind === 'for') {
2273
+ const name = stmt.variable;
2274
+ if (env.has(name))
2275
+ this.fatal('E0206', `loop variable ${name} shadows binding`, stmt.span);
2276
+ const before = emitter.height;
2277
+ // P03: a loop over inputs or outputs is the count followed by
2278
+ // ENUMERATE, which pops it as the bound and pushes each index.
2279
+ emitter.op(stmt.collection === 'tx.inputs' ? 'TXINPUTCOUNT' : 'TXOUTPUTCOUNT', stmt.span, undefined, 1);
2280
+ emitter.op('ENUMERATE', stmt.span);
2281
+ env.set(name, { kind: 'local', type: stmt.collection === 'tx.inputs' ? 'InputIndex' : 'OutputIndex', index: before });
2282
+ statements(stmt.then, true, before);
2283
+ if (emitter.height !== before + 1)
2284
+ this.fatal('E9001', 'loop body stack mismatch', stmt.span);
2285
+ emitter.op('DROP', stmt.span, undefined, -1);
2286
+ emitter.op('ENDENUMERATE', stmt.span);
2287
+ env.delete(name);
2288
+ continue;
2289
+ }
2290
+ if (stmt.kind === 'assign') {
2291
+ const name = stmt.variable, existing = env.get(name);
2292
+ if (!existing && (nested || stmt.assignOp !== '='))
2293
+ this.fatal('E0410', `local ${name} must be initialized at method top level`, stmt.span);
2294
+ if (existing && (existing.kind !== 'local' || (existing.type !== 'Int' && existing.type !== 'Amount')))
2295
+ this.fatal('E0409', `cannot assign ${name}`, stmt.span);
2296
+ if (stmt.assignOp !== '=') {
2297
+ emitter.number(BigInt(emitter.height - 1 - existing.index), stmt.span);
2298
+ emitter.op('PICK', stmt.span);
2299
+ }
2300
+ const t = expression(stmt.expr, env);
2301
+ if (t === 'Error')
2302
+ continue;
2303
+ if (t !== 'Int' && t !== 'Amount')
2304
+ this.fatal('E0408', 'numeric local required', stmt.expr?.span ?? stmt.span);
2305
+ if (stmt.assignOp !== '=')
2306
+ emitter.op(stmt.assignOp === '+=' ? 'ADD' : 'SUB', stmt.span, undefined, -1);
2307
+ if (!existing)
2308
+ env.set(name, { kind: 'local', type: t, index: emitter.height - 1 });
2309
+ else {
2310
+ const oldHeight = emitter.height - 1;
2311
+ const depth = oldHeight - existing.index;
2312
+ emitter.number(BigInt(depth), stmt.span);
2313
+ emitter.op('ROLL', stmt.span, undefined, -1);
2314
+ emitter.op('DROP', stmt.span, undefined, -1);
2315
+ for (let i = 0; i < depth - 1; i++) {
2316
+ emitter.number(BigInt(depth - 1), stmt.span);
2317
+ emitter.op('ROLL', stmt.span, undefined, -1);
2318
+ }
2319
+ env.set(name, { ...existing, type: t === 'Amount' ? 'Amount' : existing.type });
2320
+ }
2321
+ continue;
2322
+ }
2323
+ if (stmt.kind === 'require') {
2324
+ emitRequire(stmt.expr, env, undefined, [], stmt.span);
2325
+ continue;
2326
+ }
2327
+ const t = expression(stmt.expr, env);
2328
+ if (t === 'Error')
2329
+ continue;
2330
+ if (t !== 'Bool') {
2331
+ this.problem('E0404', `${stmt.kind} requires Bool, got ${t}`, stmt.expr?.span ?? stmt.span);
2332
+ emitter.op('DROP', stmt.span, undefined, -1);
2333
+ continue;
2334
+ }
2335
+ {
2336
+ emitter.control('IF', stmt.span);
2337
+ const before = emitter.height;
2338
+ statements(stmt.then, true, loopBaseHeight);
2339
+ if (emitter.height !== before)
2340
+ this.fatal('E9001', 'then stack mismatch', stmt.span);
2341
+ emitter.control('ELSE', stmt.span);
2342
+ statements(stmt.otherwise, true, loopBaseHeight);
2343
+ if (emitter.height !== before)
2344
+ this.fatal('E9001', 'else stack mismatch', stmt.span);
2345
+ emitter.control('ENDIF', stmt.span);
2346
+ }
2347
+ }
2348
+ for (let n = introduced.length; n > 0; n--)
2349
+ emitter.op('DROP', body.at(-1)?.span ?? method.span, undefined, -1);
2350
+ }
2351
+ finally {
2352
+ for (const name of introduced)
2353
+ env.delete(name);
2354
+ }
2355
+ };
2356
+ statements(method.body);
2357
+ this.diag.checkpoint();
2358
+ for (let i = emitter.height - stackParams.length; i > 0; i--)
2359
+ emitter.op('DROP', method.span, undefined, -1);
2360
+ for (let i = 0; i < method.params.length; i++)
2361
+ emitter.op('DROP', method.span, undefined, -1);
2362
+ emitter.number(1n, method.span);
2363
+ if (emitter.height !== 1)
2364
+ this.fatal('E9001', 'compiled method final stack mismatch', method.span);
2365
+ const finished = emitter.finish(this.resolvedOptimizerVersion);
2366
+ const script = finished.script;
2367
+ let loopMultiplier = 1, worstCaseSignatureChecks = 0;
2368
+ for (const entry of finished.map) {
2369
+ // C06 caps inputs and outputs at 256, which is also ENUMERATE's bound.
2370
+ if (entry.op === 'ENUMERATE')
2371
+ loopMultiplier *= 256;
2372
+ else if (entry.op === 'ENDENUMERATE')
2373
+ loopMultiplier /= 256;
2374
+ else if (entry.op === 'CHECKSIG' || entry.op === 'CHECKSIGVERIFY' || entry.op === 'CHECKDATASIG')
2375
+ worstCaseSignatureChecks += loopMultiplier;
2376
+ }
2377
+ const compiled = { script, leaf: leafHash(script), map: finished.map,
2378
+ resources: { ...finished.resources,
2379
+ helperExpansions: emitter.expansions, dynamicSignatureChecks: worstCaseSignatureChecks } };
2380
+ this.methodMemo.set(key, compiled);
2381
+ return compiled;
2382
+ }
2383
+ finally {
2384
+ this.methodActive.delete(key);
2385
+ }
2386
+ }
2387
+ compile() {
2388
+ const c = this.contract(this.options.contract);
2389
+ const root = this.root(c.name);
2390
+ const bound = this.bound(c.name);
2391
+ const methods = c.methods.map(m => {
2392
+ const compiled = this.method(c.name, m.name);
2393
+ return { name: m.name, invocation: c.kind === 'token' ? 'mint' : 'spend',
2394
+ ...(c.kind === 'token' ? { mintAmountParam: m.params[0].name } : {}),
2395
+ args: (c.kind === 'token' ? m.params.slice(1) : m.params).map(p => ({ name: p.name, type: p.type })), scriptHex: hex(compiled.script), leaf: hex(compiled.leaf),
2396
+ proof: root.proofs.get(m.name).map(hex), root: hex(root.root), sourceMap: compiled.map, staticResources: compiled.resources };
2397
+ });
2398
+ return { ...(this.options.languageVersion === 1 ? { languageVersion: 1 } : {}), schema: 'lotus/contract-artifact/2', target: 'P01-P02-P03-candidate-2026-10-14', contract: c.name, kind: c.kind,
2399
+ constructor: c.params.map(p => ({ name: p.name, type: p.type })), bindings: c.params.map(p => ({ name: p.name, ...bound.get(p.name).binding })),
2400
+ methods, policy: { branches: [hex(root.root)], paths: [[0]], root: hex(root.root), treeRecipe: 'sorted-leaves-largest-power-split-v1' },
2401
+ compiler: { name: COMPILER_NAME, version: COMPILER_VERSION, edition: this.resolvedEdition, optimizerVersion: this.resolvedOptimizerVersion } };
2402
+ }
2403
+ /** Roots actually compiled for this program, including dependencies of the selected contract. */
2404
+ computedRoots() {
2405
+ const out = [];
2406
+ for (const [name, tree] of this.rootMemo) {
2407
+ const c = this.contract(name);
2408
+ out.push({ name, root: hex(tree.root), methods: c.methods.map(m => {
2409
+ const compiled = this.methodMemo.get(`${name}.${m.name}`);
2410
+ if (!compiled)
2411
+ this.fatal('E9001', `missing compiled method ${name}.${m.name}`, m.span);
2412
+ return { name: m.name, leaf: hex(compiled.leaf) };
2413
+ }) });
2414
+ }
2415
+ out.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
2416
+ return out;
2417
+ }
2418
+ }
2419
+ function requireOptions(options, bag) {
2420
+ if (options?.languageVersion !== undefined && options.languageVersion !== 0 && options.languageVersion !== 1)
2421
+ bag.raise('E0132', 'unsupported languageVersion; expected 0 or 1');
2422
+ if (options?.edition !== undefined && !isSupportedCompilerEdition(options.edition)) {
2423
+ bag.raise('E0133', `unsupported compiler edition "${String(options.edition)}"; expected one of: ${SUPPORTED_COMPILER_EDITIONS.join(', ')}`);
2424
+ }
2425
+ if (options?.optimizerVersion !== undefined && !isSupportedOptimizerVersion(options.optimizerVersion)) {
2426
+ bag.raise('E0134', `unsupported optimizerVersion "${String(options.optimizerVersion)}"; expected one of: ${SUPPORTED_OPTIMIZER_VERSIONS.join(', ')}`);
2427
+ }
2428
+ if (options?.optimize === false && options?.optimizerVersion !== undefined && options.optimizerVersion !== 'none') {
2429
+ bag.raise('E0134', `conflicting compile options: optimize: false cannot be combined with optimizerVersion: "${options.optimizerVersion}"`);
2430
+ }
2431
+ if (options?.optimize === true && options?.optimizerVersion === 'none') {
2432
+ bag.raise('E0134', 'conflicting compile options: optimize: true cannot be combined with optimizerVersion: "none"');
2433
+ }
2434
+ if (options?.target !== undefined) {
2435
+ try {
2436
+ resolveTarget(options.target);
2437
+ }
2438
+ catch (error) {
2439
+ bag.raise('E1200', error.message);
2440
+ }
2441
+ if (options.target !== 'lotus-v2')
2442
+ bag.raise('E1201', 'compileContract emits Lotus policies only; use compileTargetContract for an explicit eCash script artifact.');
2443
+ }
2444
+ if (typeof options?.contract !== 'string' || !options.bindings || typeof options.bindings !== 'object')
2445
+ bag.raise('E0601', 'compile options require contract and bindings');
2446
+ }
2447
+ function openSource(source, file, sources = new SourceManager()) {
2448
+ if (!sources.get(file))
2449
+ sources.add(file, source);
2450
+ return new DiagnosticBag(sources, file);
2451
+ }
2452
+ function singleModule(source, file, bag, languageVersion = 0) {
2453
+ const program = new Parser(lex(source, file, bag), bag, languageVersion).parse();
2454
+ if (program.imports.length)
2455
+ bag.raise('E0121', 'import requires a package build (compilePackage)', program.imports[0].span);
2456
+ bag.checkpoint();
2457
+ return program;
2458
+ }
2459
+ export function compileContract(source, options, file = '<source>') {
2460
+ const bag = openSource(source, file);
2461
+ requireOptions(options, bag);
2462
+ return withSource(new Compiler(singleModule(source, file, bag, options.languageVersion), options, bag).compile(), source, options, file);
2463
+ }
2464
+ function withSource(artifact, text, options, file) {
2465
+ return { ...artifact, source: { text, file, bindings: sourceBindings(options.bindings) } };
2466
+ }
2467
+ /**
2468
+ * Recompile a single-file artifact from its embedded source and options and require the
2469
+ * result to equal it, so the ABI, bindings and every other field a reader relies on match
2470
+ * the scripts. Package artifacts carry no single-file source and are rejected here.
2471
+ */
2472
+ export function verifyArtifactSource(artifact) {
2473
+ const s = artifact.source;
2474
+ const text = s && 'text' in s && typeof s.text === 'string' && typeof s.file === 'string';
2475
+ const linked = s && 'program' in s && s.program && Array.isArray(s.program.helpers) && Array.isArray(s.program.contracts);
2476
+ if (!s || (!text && !linked) || !s.bindings || typeof s.bindings !== 'object')
2477
+ throw new Error('artifact has no source; recompile it with this compiler');
2478
+ const c = artifact.compiler;
2479
+ if (!c || c.name !== COMPILER_NAME || c.version !== COMPILER_VERSION)
2480
+ throw new Error(`artifact compiler ${c?.name ?? '?'} ${c?.version ?? '?'} is not this compiler (${COMPILER_NAME} ${COMPILER_VERSION})`);
2481
+ const options = { contract: artifact.contract, bindings: s.bindings, edition: c.edition, optimizerVersion: c.optimizerVersion,
2482
+ ...(artifact.languageVersion === undefined ? {} : { languageVersion: artifact.languageVersion }) };
2483
+ let fresh, roots = [];
2484
+ try {
2485
+ if ('text' in s)
2486
+ fresh = compileContract(s.text, options, s.file);
2487
+ else {
2488
+ const program = {
2489
+ ...(s.program.languageVersion === 1 ? { languageVersion: 1 } : {}),
2490
+ ...(s.program.edition !== undefined ? { edition: s.program.edition } : {}),
2491
+ ...(s.program.optimizerVersion !== undefined ? { optimizerVersion: s.program.optimizerVersion } : {}),
2492
+ ...(s.program.states?.length ? { states: new Map(s.program.states.map(st => [st.name, st])) } : {}),
2493
+ helpers: new Map(s.program.helpers.map(h => [h.name, h])), contracts: new Map(s.program.contracts.map(x => [x.name, x])), imports: [],
2494
+ };
2495
+ const bag = new DiagnosticBag(new SourceManager(), '<source>');
2496
+ requireOptions(options, bag);
2497
+ const compiler = new Compiler(program, options, bag);
2498
+ fresh = { ...compiler.compile(), source: s };
2499
+ roots = compiler.computedRoots();
2500
+ }
2501
+ }
2502
+ catch (error) {
2503
+ throw new Error(`artifact does not match its source: ${error.message.split('\n')[0]}`);
2504
+ }
2505
+ if ('program' in s) {
2506
+ // Links name roots this program computed; their package digests are build metadata.
2507
+ for (const link of artifact.links ?? []) {
2508
+ const root = roots.find(r => r.name === link.name);
2509
+ if (!root || root.root !== link.root || JSON.stringify(root.methods) !== JSON.stringify(link.methods))
2510
+ throw new Error(`artifact does not match its source: links ${link.name}`);
2511
+ }
2512
+ fresh = { ...fresh, ...(artifact.links ? { links: artifact.links } : {}), ...(artifact.build ? { build: artifact.build } : {}) };
2513
+ }
2514
+ const keys = new Set([...Object.keys(fresh), ...Object.keys(artifact)]);
2515
+ for (const key of keys) {
2516
+ if (JSON.stringify(fresh[key]) !== JSON.stringify(artifact[key]))
2517
+ throw new Error(`artifact does not match its source: ${key}`);
2518
+ }
2519
+ }
2520
+ export const compileGenericContract = compileContract;
2521
+ export async function compileContractAsync(source, options, onEvent, file = '<source>') {
2522
+ const bag = openSource(source, file);
2523
+ requireOptions(options, bag);
2524
+ return withSource(await new Compiler(singleModule(source, file, bag, options.languageVersion), options, bag).compileAsync(onEvent), source, options, file);
2525
+ }
2526
+ export const compileGenericContractAsync = compileContractAsync;
2527
+ /** @internal Package linker entry: parse one module (declaration-only modules may omit contracts). */
2528
+ export function parseModuleSource(source, requireContract, file = '<source>', sources, languageVersion = 0) {
2529
+ const bag = openSource(source, file, sources);
2530
+ if (languageVersion !== 0 && languageVersion !== 1)
2531
+ bag.raise('E0132', 'unsupported languageVersion; expected 0 or 1');
2532
+ const program = new Parser(lex(source, file, bag), bag, languageVersion).parse(requireContract);
2533
+ bag.checkpoint();
2534
+ return program;
2535
+ }
2536
+ /** @internal Package linker entry: compile an already linked program through the promise scheduler. */
2537
+ export async function compileLinkedProgramAsync(program, options, onEvent, sources) {
2538
+ const bag = new DiagnosticBag(sources ?? new SourceManager(), '<source>');
2539
+ requireOptions(options, bag);
2540
+ const compiler = new Compiler(program, options, bag);
2541
+ const artifact = await compiler.compileAsync(onEvent);
2542
+ return { artifact, roots: compiler.computedRoots() };
2543
+ }
2544
+ export async function compileContractWithTrace(source, options, file = '<source>') {
2545
+ const trace = [];
2546
+ const artifact = await compileContractAsync(source, options, event => trace.push(event), file);
2547
+ return { artifact, trace };
2548
+ }
2549
+ export { lintProgram } from './lints.js';
2550
+ /**
2551
+ * Compile `source` (throwing on errors) and return advisory lint warnings for the selected
2552
+ * contract. Warnings never change the artifact.
2553
+ */
2554
+ export function lintContract(source, options, file = '<source>') {
2555
+ const compiled = compileContract(source, options, file);
2556
+ return lintProgram(parseModuleSource(source, true, file, undefined, options.languageVersion ?? 0), options.contract, file, compiled);
2557
+ }
2558
+ export function methodLeafHash(artifact, method) {
2559
+ const m = artifact.methods.find(x => x.name === method);
2560
+ if (!m)
2561
+ throw new Error(`unknown method ${method}`);
2562
+ return { kind: 'MethodLeafHash', hex: m.leaf };
2563
+ }
2564
+ export function contractRootHash(artifact) {
2565
+ return { kind: 'ContractRootHash', hex: artifact.policy.root };
2566
+ }