@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,46 @@
1
+ import { schnorr } from '@noble/curves/secp256k1';
2
+ import { compilePayment, hex, unhex } from './compiler.js';
3
+ import { encodeOutput, encodePaymentWireUnchecked, finalizePayment, preparePayment } from './runtime.js';
4
+ function jsonOutput(o) { return { flags: 0, valueAtoms: o.value.toString(), branches: [...o.branches], paths: o.paths.map(p => [...p]) }; }
5
+ function alterRoot(root) { return (root[0] === '0' ? '1' : '0') + root.slice(1); }
6
+ export function buildPaymentFixture(input) {
7
+ if (input.signingMode !== 0)
8
+ throw new Error('fixture builder supports FULL signing mode 0 only');
9
+ const secret = unhex(input.testSecret, 32);
10
+ if (hex(schnorr.getPublicKey(secret)) !== input.owner)
11
+ throw new Error('owner does not match deterministic fixture key');
12
+ const artifact = compilePayment(input.source, input.owner);
13
+ const base = { profile: input.profile, chainId: input.chainId, prevTxid: input.outpoint.txid, prevIndex: input.outpoint.index,
14
+ sequence: input.sequence, lock: input.lock, coin: input.coin, outputs: input.outputs };
15
+ const plan = preparePayment(artifact, base);
16
+ if (base.outputs[0].value === 0n)
17
+ throw new Error('first output must have positive value for named mutation');
18
+ const signature = schnorr.sign(plan.message, secret, new Uint8Array(32));
19
+ const valid = finalizePayment(plan, signature);
20
+ const variants = [
21
+ { name: 'changed-output-value', context: { ...base, outputs: [{ ...base.outputs[0], value: base.outputs[0].value - 1n }, ...base.outputs.slice(1)] }, artifact },
22
+ { name: 'changed-chain-id', context: { ...base, chainId: alterRoot(base.chainId) }, artifact },
23
+ ];
24
+ const alternativeSecret = input.testSecret === '00'.repeat(31) + '03' ? '00'.repeat(31) + '04' : '00'.repeat(31) + '03';
25
+ const changedOwner = compilePayment(input.source, hex(schnorr.getPublicKey(unhex(alternativeSecret, 32))));
26
+ variants.push({ name: 'changed-owner', context: { ...base, coin: { ...base.coin, branches: changedOwner.policy.branches } }, artifact: changedOwner });
27
+ const mutations = variants.map(({ name, context, artifact: selected }) => {
28
+ let reason = '';
29
+ try {
30
+ finalizePayment(preparePayment(selected, context), signature);
31
+ }
32
+ catch (err) {
33
+ reason = err.message;
34
+ }
35
+ if (reason !== 'signature verification failed')
36
+ throw new Error(`mutation ${name} failed at unexpected stage: ${reason}`);
37
+ return { name, wire: hex(encodePaymentWireUnchecked(selected, context, signature)),
38
+ context: { chainId: context.chainId, owner: selected.scriptHex.slice(2, 66), coin: jsonOutput(context.coin), coinWire: hex(encodeOutput(context.coin)), outputs: context.outputs.map(jsonOutput) },
39
+ expectedStage: 'signature', expectedReason: reason };
40
+ });
41
+ return { schema: 'lotus/payment-fixture/1', source: input.source, artifact,
42
+ context: { chainId: base.chainId, outpoint: { txid: base.prevTxid, index: base.prevIndex }, sequence: base.sequence, lock: base.lock.toString(), profile: base.profile,
43
+ signingMode: 0, coin: jsonOutput(base.coin), coinWire: hex(encodeOutput(base.coin)), outputs: base.outputs.map(jsonOutput) },
44
+ valid: { wire: hex(valid.wire), txid: valid.txid, txhash: valid.txhash, message: valid.message, signature: valid.signature,
45
+ feeAtoms: plan.signingIntent.feeAtoms.toString(), expectedStage: 'signature', stages: valid.stages }, mutations };
46
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Symbolic Forth-like stack IR and lowering pipeline for Lotus V2 contracts.
3
+ *
4
+ * AST lowering emits structured `ForthNode` values rather than raw wire bytes.
5
+ * `ForthEmitter.finish()` lowers the IR to `Instruction[]`, runs the versioned
6
+ * bounded fixed-point symbolic optimizer (`optimizer.ts`), validates stack
7
+ * invariants, and serializes final P03 bytecode with full source maps.
8
+ */
9
+ import { type Span } from './compiler.js';
10
+ import type { DiagnosticExtra } from './diagnostics.js';
11
+ import { type MethodArtifact } from './ast.js';
12
+ import { type P03OpcodeName } from './opcodes.js';
13
+ import { type OptimizerVersion } from './optimizer.js';
14
+ export type Frame = {
15
+ name: string;
16
+ at: Span;
17
+ };
18
+ export type ForthNode = {
19
+ kind: 'op';
20
+ op: P03OpcodeName;
21
+ span: Span;
22
+ origin?: Span;
23
+ delta: number;
24
+ } | {
25
+ kind: 'number';
26
+ value: bigint;
27
+ span: Span;
28
+ origin?: Span;
29
+ } | {
30
+ kind: 'push';
31
+ data: Uint8Array;
32
+ span: Span;
33
+ origin?: Span;
34
+ foldable: boolean;
35
+ } | {
36
+ kind: 'control';
37
+ op: 'IF' | 'ELSE' | 'ENDIF';
38
+ span: Span;
39
+ origin?: Span;
40
+ };
41
+ export type ForthProgram = {
42
+ readonly args: number;
43
+ readonly nodes: readonly ForthNode[];
44
+ };
45
+ export type LoweredMethod = {
46
+ script: Uint8Array;
47
+ map: MethodArtifact['sourceMap'];
48
+ resources: Pick<MethodArtifact['staticResources'], 'scriptBytes' | 'opcodes' | 'maxStackItems'>;
49
+ };
50
+ export declare class ForthEmitter {
51
+ readonly args: number;
52
+ private readonly fail;
53
+ private readonly ir;
54
+ private readonly instructions;
55
+ private length;
56
+ readonly map: MethodArtifact['sourceMap'];
57
+ height: number;
58
+ maxHeight: number;
59
+ opcodes: number;
60
+ signatureChecks: number;
61
+ expansions: number;
62
+ /** Inline chain of the expression currently being lowered. */
63
+ frames: Frame[];
64
+ constructor(args: number, fail: (code: string, message: string, span: Span, frames: Frame[], extra?: DiagnosticExtra) => never);
65
+ private record;
66
+ push(data: Uint8Array, span: Span, origin?: Span, foldable?: boolean): void;
67
+ number(n: bigint, span: Span, origin?: Span): void;
68
+ op(name: P03OpcodeName, span: Span, origin?: Span, delta?: number): void;
69
+ control(name: 'IF' | 'ELSE' | 'ENDIF', span: Span, origin?: Span): void;
70
+ program(): ForthProgram;
71
+ finish(optimizeOrVersion: boolean | OptimizerVersion): LoweredMethod;
72
+ get bytes(): number;
73
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Symbolic Forth-like stack IR and lowering pipeline for Lotus V2 contracts.
3
+ *
4
+ * AST lowering emits structured `ForthNode` values rather than raw wire bytes.
5
+ * `ForthEmitter.finish()` lowers the IR to `Instruction[]`, runs the versioned
6
+ * bounded fixed-point symbolic optimizer (`optimizer.ts`), validates stack
7
+ * invariants, and serializes final P03 bytecode with full source maps.
8
+ */
9
+ import { artifactSpan, bytes, concat } from './compiler.js';
10
+ import { encodedInt, MAX_OPS, MAX_SCRIPT } from './ast.js';
11
+ import { opcodeByte } from './opcodes.js';
12
+ import { OptimizerError, optimizeInstructions } from './optimizer.js';
13
+ function encodeNode(node) {
14
+ if (node.kind === 'number') {
15
+ const n = node.value;
16
+ if (n === 0n)
17
+ return { wire: Uint8Array.of(0), op: 'ZERO', delta: 1, foldable: true };
18
+ if (n === -1n)
19
+ return { wire: Uint8Array.of(0x4d), op: 'NEGATIVE_ONE', delta: 1, foldable: true };
20
+ if (n >= 1n && n <= 16n)
21
+ return { wire: Uint8Array.of(0x4d + Number(n)), op: `N(${n})`, delta: 1, foldable: true };
22
+ const data = encodedInt(n);
23
+ const wire = concat(Uint8Array.of(data.length), data);
24
+ return { wire, op: `PUSH_${data.length}`, delta: 1, foldable: true };
25
+ }
26
+ if (node.kind === 'push') {
27
+ const data = node.data;
28
+ const wire = data.length > 0 && data.length <= 75
29
+ ? concat(Uint8Array.of(data.length), data)
30
+ : concat(Uint8Array.of(0x4c), bytes(data));
31
+ const op = data.length <= 75 && data.length > 0 ? `PUSH_${data.length}` : 'PUSHDATA';
32
+ return { wire, op, delta: 1, foldable: node.foldable };
33
+ }
34
+ if (node.kind === 'control') {
35
+ return { wire: Uint8Array.of(opcodeByte(node.op)), op: node.op, delta: node.op === 'IF' ? -1 : 0, foldable: false };
36
+ }
37
+ return { wire: Uint8Array.of(opcodeByte(node.op)), op: node.op, delta: node.delta, foldable: false };
38
+ }
39
+ export class ForthEmitter {
40
+ args;
41
+ fail;
42
+ ir = [];
43
+ instructions = [];
44
+ length = 0;
45
+ map = [];
46
+ height;
47
+ maxHeight;
48
+ opcodes = 0;
49
+ signatureChecks = 0;
50
+ expansions = 0;
51
+ /** Inline chain of the expression currently being lowered. */
52
+ frames = [];
53
+ constructor(args, fail) {
54
+ this.args = args;
55
+ this.fail = fail;
56
+ this.height = args;
57
+ this.maxHeight = args;
58
+ }
59
+ record(node) {
60
+ const { wire, op, delta, foldable } = encodeNode(node);
61
+ if (this.length + wire.length > MAX_SCRIPT)
62
+ this.fail('E0701', 'MAX_SCRIPT_BYTES exceeded', node.span, this.frames);
63
+ if (++this.opcodes > MAX_OPS)
64
+ this.fail('E0702', 'opcode budget exceeded', node.span, this.frames);
65
+ // Artifacts and traces keep `{start,end[,module]}` only; `file` is diagnostic-only.
66
+ const entryMap = {
67
+ source: artifactSpan(node.span),
68
+ ...(node.origin ? { expandedFrom: artifactSpan(node.origin) } : {}),
69
+ byteStart: this.length,
70
+ byteEnd: this.length + wire.length,
71
+ op,
72
+ };
73
+ this.ir.push(node);
74
+ this.map.push(entryMap);
75
+ this.instructions.push({ wire, map: entryMap, delta, foldable, ...(node.span.file ? { file: node.span.file } : {}) });
76
+ this.length += wire.length;
77
+ this.height += delta;
78
+ if (this.height < 0)
79
+ this.fail('E9001', 'compiler stack underflow', node.span, this.frames);
80
+ this.maxHeight = Math.max(this.maxHeight, this.height);
81
+ }
82
+ push(data, span, origin, foldable = false) {
83
+ if (data.length > 8192)
84
+ this.fail('E0707', 'MAX_ELEMENT_BYTES exceeded', span, this.frames);
85
+ this.record({ kind: 'push', data, span, ...(origin ? { origin } : {}), foldable });
86
+ }
87
+ number(n, span, origin) {
88
+ this.record({ kind: 'number', value: n, span, ...(origin ? { origin } : {}) });
89
+ }
90
+ op(name, span, origin, delta = 0) {
91
+ this.record({ kind: 'op', op: name, span, ...(origin ? { origin } : {}), delta });
92
+ if (name === 'CHECKSIG' || name === 'CHECKDATASIG')
93
+ this.signatureChecks++;
94
+ }
95
+ control(name, span, origin) {
96
+ this.record({ kind: 'control', op: name, span, ...(origin ? { origin } : {}) });
97
+ }
98
+ program() {
99
+ return { args: this.args, nodes: this.ir };
100
+ }
101
+ finish(optimizeOrVersion) {
102
+ const version = typeof optimizeOrVersion === 'boolean' ? (optimizeOrVersion ? 'v1' : 'none') : optimizeOrVersion;
103
+ let entries;
104
+ try {
105
+ entries = version === 'none' ? this.instructions : optimizeInstructions(this.instructions, this.args, version);
106
+ }
107
+ catch (error) {
108
+ if (error instanceof OptimizerError) {
109
+ const span = error.span ?? this.map.at(-1)?.source ?? { start: 0, end: 0 };
110
+ const labels = error.relatedSpans.map((r, idx) => ({
111
+ span: r.source,
112
+ message: `while optimizing ${r.op} emitted here`,
113
+ primary: idx === 0,
114
+ }));
115
+ this.fail(error.code, error.message, span, this.frames, labels.length ? { labels } : {});
116
+ }
117
+ throw error;
118
+ }
119
+ const structured = entries.some(entry => ['IF', 'ELSE', 'ENDIF', 'ENUMERATE', 'ENDENUMERATE'].includes(entry.map.op));
120
+ const map = [];
121
+ let offset = 0, height = this.args, maxStackItems = height;
122
+ for (const entry of entries) {
123
+ map.push({ ...entry.map, byteStart: offset, byteEnd: offset + entry.wire.length });
124
+ offset += entry.wire.length;
125
+ if (!structured) {
126
+ height += entry.delta;
127
+ if (height < 0)
128
+ this.fail('E9001', 'optimized compiler stack underflow', entry.map.source, this.frames);
129
+ maxStackItems = Math.max(maxStackItems, height);
130
+ }
131
+ }
132
+ if (structured) {
133
+ height = this.height;
134
+ maxStackItems = this.maxHeight;
135
+ }
136
+ if (height !== 1)
137
+ this.fail('E9001', 'optimized method final stack mismatch', map.at(-1)?.source ?? { start: 0, end: 0 }, this.frames);
138
+ return {
139
+ script: concat(...entries.map(entry => entry.wire)),
140
+ map,
141
+ resources: { scriptBytes: offset, opcodes: entries.length, maxStackItems },
142
+ };
143
+ }
144
+ get bytes() {
145
+ return this.length;
146
+ }
147
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,140 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { compileContractWithTrace, lintContract } from './generic.js';
5
+ import { compilePackage, PackageError, packageCompileError } from './packages.js';
6
+ import { generateContractPython, generateContractTypeScript } from './bindings.js';
7
+ import { compileTargetContract } from './target-compiler.js';
8
+ import { resolveTarget } from './targets.js';
9
+ import { unhex } from './compiler.js';
10
+ import { CompileError, DIAGNOSTIC_CODES, DiagnosticBag, SourceManager, errorDiagnostics, renderDiagnostics, shouldColor } from './diagnostics.js';
11
+ import { staticInvocationCu } from './fees.js';
12
+ function present(err, packageDir) {
13
+ const color = shouldColor(process.stderr);
14
+ if (err instanceof CompileError)
15
+ return err.render({ color });
16
+ if (err instanceof PackageError) {
17
+ const sources = new SourceManager();
18
+ if (packageDir && err.file) {
19
+ try {
20
+ sources.add(err.file, readFileSync(join(packageDir, err.file), 'utf8'));
21
+ }
22
+ catch { /* file-level diagnostic */ }
23
+ }
24
+ return packageCompileError(err, sources).render({ color });
25
+ }
26
+ return renderDiagnostics(errorDiagnostics(err).diagnostics, new SourceManager(), { color });
27
+ }
28
+ try {
29
+ const rawArgs = process.argv.slice(2);
30
+ if (rawArgs[0] === '--explain') {
31
+ const code = rawArgs[1];
32
+ if (!code || !Object.hasOwn(DIAGNOSTIC_CODES, code)) {
33
+ throw new Error(`unknown diagnostic code ${JSON.stringify(code ?? '')}; usage: lotus-contract-compile --explain <E|W-CODE>`);
34
+ }
35
+ process.stdout.write(`${code}: ${DIAGNOSTIC_CODES[code]}\n`);
36
+ process.exit(0);
37
+ }
38
+ const flags = new Set();
39
+ const positional = [];
40
+ let packageMode = false;
41
+ for (let i = 0; i < rawArgs.length; i++) {
42
+ const arg = rawArgs[i];
43
+ if (arg === '--package' && i === 0) {
44
+ packageMode = true;
45
+ continue;
46
+ }
47
+ if (['--trace', '--check', '--emit-ir', '--cost'].includes(arg)) {
48
+ flags.add(arg);
49
+ continue;
50
+ }
51
+ positional.push(arg);
52
+ }
53
+ const checkOnly = flags.has('--check');
54
+ const expectedPositional = checkOnly ? 2 : 3;
55
+ if (positional.length !== expectedPositional) {
56
+ throw new Error('usage: lotus-contract-compile (SOURCE | --package DIR) OPTIONS.json [OUTPUT_DIR] [--check] [--trace] [--emit-ir] [--cost] | --explain <CODE>');
57
+ }
58
+ const inputPath = positional[0];
59
+ const optionsPath = positional[1];
60
+ const outDir = positional[2];
61
+ const options = JSON.parse(readFileSync(optionsPath, 'utf8'));
62
+ function fail(code, message) { return new DiagnosticBag(new SourceManager()).raise(code, message); }
63
+ if (!options || typeof options !== 'object' || Array.isArray(options))
64
+ fail('E0601', 'compile options must be an object with contract and bindings');
65
+ let selected;
66
+ try {
67
+ selected = resolveTarget(options.target === undefined ? 'lotus-v2' : options.target);
68
+ }
69
+ catch (error) {
70
+ fail('E1200', error.message);
71
+ }
72
+ let artifact, trace = [];
73
+ if (packageMode) {
74
+ if (selected.id !== 'lotus-v2')
75
+ fail('E1203', 'eCash package linking is not implemented; compile a single selected source method.');
76
+ if (options.method !== undefined)
77
+ fail('E1202', 'Lotus package compilation commits the complete policy; selected-method output is not supported.');
78
+ ({ artifact, trace } = await compilePackage(inputPath, { ...options, target: 'lotus-v2' }));
79
+ }
80
+ else if (selected.id === 'ecash') {
81
+ if (flags.has('--trace'))
82
+ fail('E1203', 'eCash source compilation does not produce a Lotus scheduler trace.');
83
+ artifact = compileTargetContract(readFileSync(inputPath, 'utf8'), options, inputPath);
84
+ }
85
+ else {
86
+ if (options.method !== undefined)
87
+ fail('E1202', 'Lotus compilation commits the complete policy; selected-method output is not supported.');
88
+ const source = readFileSync(inputPath, 'utf8');
89
+ ({ artifact, trace } = await compileContractWithTrace(source, { ...options, target: 'lotus-v2' }, inputPath));
90
+ // Advisory lints go to stderr; they never change the artifact or the exit status.
91
+ const warnings = lintContract(source, { ...options, target: 'lotus-v2' }, inputPath);
92
+ if (warnings.length) {
93
+ const sources = new SourceManager();
94
+ sources.add(inputPath, source);
95
+ process.stderr.write(renderDiagnostics(warnings, sources, { color: shouldColor(process.stderr) }));
96
+ }
97
+ }
98
+ if (artifact.schema !== 'ecash/script-artifact/1') {
99
+ if (flags.has('--emit-ir')) {
100
+ for (const m of artifact.methods) {
101
+ process.stdout.write(`method ${artifact.contract}.${m.name} (${m.staticResources.scriptBytes}B, ${m.staticResources.opcodes} ops, maxStack=${m.staticResources.maxStackItems}):\n`);
102
+ for (const entry of m.sourceMap) {
103
+ const optNote = entry.optimizedFrom ? ` ; folded from [${entry.optimizedFrom.map(o => o.op).join(', ')}]` : '';
104
+ process.stdout.write(` ${String(entry.byteStart).padStart(4, '0')}..${String(entry.byteEnd).padStart(4, '0')} ${entry.op}${optNote}\n`);
105
+ }
106
+ }
107
+ }
108
+ if (flags.has('--cost')) {
109
+ for (const m of artifact.methods) {
110
+ const cu = staticInvocationCu(unhex(m.scriptHex), m.args.map(() => 32), 1, 1);
111
+ process.stdout.write(`cost ${artifact.contract}.${m.name}: bytes=${m.staticResources.scriptBytes} ops=${m.staticResources.opcodes} maxStack=${m.staticResources.maxStackItems} sigs=${m.staticResources.dynamicSignatureChecks} staticCu=${cu}\n`);
112
+ }
113
+ }
114
+ }
115
+ if (checkOnly) {
116
+ const label = artifact.schema === 'ecash/script-artifact/1' ? artifact.entrypoint : artifact.contract;
117
+ const root = artifact.schema === 'ecash/script-artifact/1' ? artifact.scriptHex.slice(0, 16) : artifact.policy.root;
118
+ process.stdout.write(`OK ${label} root=${root}\n`);
119
+ }
120
+ else {
121
+ const out = outDir;
122
+ mkdirSync(out, { recursive: true });
123
+ writeFileSync(join(out, 'artifact.json'), JSON.stringify(artifact, null, 2) + '\n');
124
+ if (artifact.schema === 'ecash/script-artifact/1') {
125
+ writeFileSync(join(out, 'script.hex'), artifact.scriptHex + '\n');
126
+ }
127
+ else {
128
+ writeFileSync(join(out, `${artifact.contract}.ts`), generateContractTypeScript(artifact));
129
+ writeFileSync(join(out, `${artifact.contract}.py`), generateContractPython(artifact));
130
+ }
131
+ if (flags.has('--trace'))
132
+ writeFileSync(join(out, 'scheduler-trace.json'), JSON.stringify(trace, null, 2) + '\n');
133
+ }
134
+ }
135
+ catch (err) {
136
+ const packageDir = process.argv[2] === '--package' ? process.argv[3] : undefined;
137
+ const text = present(err, packageDir);
138
+ process.stderr.write(text.endsWith('\n') ? text : `${text}\n`);
139
+ process.exitCode = 1;
140
+ }
@@ -0,0 +1,48 @@
1
+ import { SourceManager, type Diagnostic } from './diagnostics.js';
2
+ import { type SchedulerEvent } from './scheduler.js';
3
+ import { type CompileOptions, type ContractArtifact, type LanguageVersion, type Program } from './ast.js';
4
+ export { DEFAULT_COMPILER_EDITION, DEFAULT_OPTIMIZER_VERSION, OPTIMIZER_PASSES_BY_VERSION, SUPPORTED_COMPILER_EDITIONS, SUPPORTED_OPTIMIZER_VERSIONS, isSupportedCompilerEdition, isSupportedOptimizerVersion, resolveCompilerEdition, resolveOptimizerVersion, type CompilerEdition, type OptimizerVersion, } from './optimizer.js';
5
+ export type { SchedulerEvent } from './scheduler.js';
6
+ export { TAGGED_HASH_TYPES, isBranchRootType, isTaggedHashType, linkedProgramSource, sourceBindings, type ArtifactCompiler, type ArtifactSource, type BoundValue, type CompileOptions, type Contract, type ContractArtifact, type Expr, type Helper, type HelperStmt, type ImportDecl, type LanguageVersion, type LinkedContract, type LinkedProgramSource, type Method, type MethodArtifact, type Param, type Program, type StateDecl, type StateMode, type Stmt, type TaggedHashType, type ValueType, type Visibility, } from './ast.js';
7
+ export declare function compileContract(source: string, options: CompileOptions, file?: string): ContractArtifact;
8
+ /**
9
+ * Recompile a single-file artifact from its embedded source and options and require the
10
+ * result to equal it, so the ABI, bindings and every other field a reader relies on match
11
+ * the scripts. Package artifacts carry no single-file source and are rejected here.
12
+ */
13
+ export declare function verifyArtifactSource(artifact: ContractArtifact): void;
14
+ export declare const compileGenericContract: typeof compileContract;
15
+ export declare function compileContractAsync(source: string, options: CompileOptions, onEvent?: (event: SchedulerEvent) => void, file?: string): Promise<ContractArtifact>;
16
+ export declare const compileGenericContractAsync: typeof compileContractAsync;
17
+ /** @internal Package linker entry: parse one module (declaration-only modules may omit contracts). */
18
+ export declare function parseModuleSource(source: string, requireContract: boolean, file?: string, sources?: SourceManager, languageVersion?: LanguageVersion): Program;
19
+ /** @internal Package linker entry: compile an already linked program through the promise scheduler. */
20
+ export declare function compileLinkedProgramAsync(program: Program, options: CompileOptions, onEvent?: (event: SchedulerEvent) => void, sources?: SourceManager): Promise<{
21
+ artifact: ContractArtifact;
22
+ roots: {
23
+ name: string;
24
+ root: string;
25
+ methods: {
26
+ name: string;
27
+ leaf: string;
28
+ }[];
29
+ }[];
30
+ }>;
31
+ export declare function compileContractWithTrace(source: string, options: CompileOptions, file?: string): Promise<{
32
+ artifact: ContractArtifact;
33
+ trace: SchedulerEvent[];
34
+ }>;
35
+ export { lintProgram } from './lints.js';
36
+ /**
37
+ * Compile `source` (throwing on errors) and return advisory lint warnings for the selected
38
+ * contract. Warnings never change the artifact.
39
+ */
40
+ export declare function lintContract(source: string, options: CompileOptions, file?: string): Diagnostic[];
41
+ export declare function methodLeafHash(artifact: ContractArtifact, method: string): {
42
+ kind: 'MethodLeafHash';
43
+ hex: string;
44
+ };
45
+ export declare function contractRootHash(artifact: ContractArtifact): {
46
+ kind: 'ContractRootHash';
47
+ hex: string;
48
+ };