@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
package/dist/ast.d.ts ADDED
@@ -0,0 +1,292 @@
1
+ /** Core AST, type, binding, Merkle-tree, and artifact definitions for Lotus V2 contracts. */
2
+ import { type Span } from './compiler.js';
3
+ import type { CompilerEdition, OptimizerVersion } from './optimizer.js';
4
+ import type { TargetId } from './targets.js';
5
+ export type ValueType = 'PublicKey' | 'Signature' | 'Bytes32' | `Bytes(${number})` | 'Int' | 'Amount' | 'TokenId' | 'TxId' | 'StateRoot' | 'ChainId' | 'SigHash' | 'BranchRoot' | 'Bool' | 'MethodLeafHash' | 'ContractRootHash' | 'InputIndex' | 'OutputIndex';
6
+ export declare const TAGGED_HASH_TYPES: readonly ["TxId", "StateRoot", "ChainId", "SigHash", "TokenId", "BranchRoot", "ContractRootHash", "MethodLeafHash"];
7
+ export type TaggedHashType = (typeof TAGGED_HASH_TYPES)[number];
8
+ export declare function isTaggedHashType(type: ValueType): type is TaggedHashType;
9
+ /** BranchRoot and ContractRootHash are compatible nominal aliases for a 32-byte contract branch root. */
10
+ export declare function isBranchRootType(type: ValueType): boolean;
11
+ /** Omitted/0 preserves legacy source and artifact bytes; 1 selects explicit LC-1 entries. */
12
+ export type LanguageVersion = 0 | 1;
13
+ export type BoundValue = string | boolean | bigint;
14
+ export type Token = {
15
+ text: string;
16
+ span: Span;
17
+ };
18
+ export type Param = {
19
+ name: string;
20
+ type: ValueType;
21
+ span: Span;
22
+ };
23
+ export type Expr = {
24
+ kind: 'name' | 'number' | 'bool' | 'call' | 'binary' | 'unary' | 'index' | 'member' | 'member_call';
25
+ span: Span;
26
+ value?: string;
27
+ args?: Expr[];
28
+ left?: Expr;
29
+ right?: Expr;
30
+ };
31
+ export type Stmt = {
32
+ kind: 'require' | 'if' | 'for' | 'assign' | 'let_tuple' | 'break';
33
+ span: Span;
34
+ expr?: Expr;
35
+ then?: Stmt[];
36
+ otherwise?: Stmt[];
37
+ variable?: string;
38
+ variables?: {
39
+ name: string;
40
+ span: Span;
41
+ }[];
42
+ collection?: 'tx.inputs' | 'tx.outputs';
43
+ assignOp?: '=' | '+=' | '-=';
44
+ };
45
+ /** Statement-bodied helper. `return` is only legal as the function body's last statement. */
46
+ export type HelperStmt = {
47
+ kind: 'let';
48
+ name: string;
49
+ type: ValueType;
50
+ expr: Expr;
51
+ nameSpan: Span;
52
+ span: Span;
53
+ } | {
54
+ kind: 'let_tuple';
55
+ variables: {
56
+ name: string;
57
+ span: Span;
58
+ }[];
59
+ expr: Expr;
60
+ span: Span;
61
+ } | {
62
+ kind: 'require';
63
+ expr: Expr;
64
+ span: Span;
65
+ } | {
66
+ kind: 'if';
67
+ expr: Expr;
68
+ then: HelperStmt[];
69
+ otherwise: HelperStmt[];
70
+ span: Span;
71
+ } | {
72
+ kind: 'return';
73
+ expr: Expr;
74
+ span: Span;
75
+ };
76
+ /** `private` (default, module only), `package` (same package) or `export` (other packages via exported modules). */
77
+ export type Visibility = 'private' | 'package' | 'export';
78
+ export type StateMode = 'separate' | 'inline';
79
+ export type StateDecl = {
80
+ name: string;
81
+ mode: StateMode;
82
+ fields: Param[];
83
+ span: Span;
84
+ visibility: Visibility;
85
+ };
86
+ export type Helper = {
87
+ name: string;
88
+ params: Param[];
89
+ result: ValueType;
90
+ body: HelperStmt[];
91
+ span: Span;
92
+ visibility: Visibility;
93
+ };
94
+ export type Method = {
95
+ invocation?: 'spend' | 'mint';
96
+ name: string;
97
+ params: Param[];
98
+ body: Stmt[];
99
+ span: Span;
100
+ };
101
+ export type Contract = {
102
+ name: string;
103
+ kind: 'contract' | 'token';
104
+ params: Param[];
105
+ methods: Method[];
106
+ span: Span;
107
+ visibility: Visibility;
108
+ };
109
+ /** Compile-time link to a library contract. Not a VM call. Present only on package artifacts that commit to one. */
110
+ export type LinkedContract = {
111
+ name: string;
112
+ kind: 'contract' | 'token';
113
+ package: string;
114
+ module: string;
115
+ packageDigest: string;
116
+ root: string;
117
+ methods: {
118
+ name: string;
119
+ leaf: string;
120
+ }[];
121
+ };
122
+ /** `import TARGET::path::{a, b as c};` or `import TARGET::path as alias;`. TARGET is a dependency alias, `package`, or a quoted module selector (`"host/owner/repo@vX.Y.Z"`). */
123
+ export type ImportDecl = {
124
+ target: string;
125
+ targetSpan: Span;
126
+ path: string[];
127
+ pathSpan: Span;
128
+ span: Span;
129
+ items?: {
130
+ name: string;
131
+ local: string;
132
+ span: Span;
133
+ }[];
134
+ moduleAlias?: {
135
+ name: string;
136
+ span: Span;
137
+ };
138
+ };
139
+ export type Program = {
140
+ languageVersion?: LanguageVersion;
141
+ edition?: CompilerEdition;
142
+ optimizerVersion?: OptimizerVersion;
143
+ states?: Map<string, StateDecl>;
144
+ helpers: Map<string, Helper>;
145
+ contracts: Map<string, Contract>;
146
+ imports: ImportDecl[];
147
+ };
148
+ export type Binding = {
149
+ type: ValueType;
150
+ value: string | boolean;
151
+ };
152
+ export type MethodArtifact = {
153
+ name: string;
154
+ args: {
155
+ name: string;
156
+ type: ValueType;
157
+ }[];
158
+ invocation?: 'spend' | 'mint';
159
+ mintAmountParam?: string;
160
+ scriptHex: string;
161
+ leaf: string;
162
+ proof: string[];
163
+ root: string;
164
+ sourceMap: {
165
+ source: Span;
166
+ expandedFrom?: Span;
167
+ optimizedFrom?: {
168
+ op: string;
169
+ source: Span;
170
+ expandedFrom?: Span;
171
+ }[];
172
+ byteStart: number;
173
+ byteEnd: number;
174
+ op: string;
175
+ }[];
176
+ staticResources: {
177
+ scriptBytes: number;
178
+ opcodes: number;
179
+ maxStackItems: number;
180
+ helperExpansions: number;
181
+ dynamicSignatureChecks: number;
182
+ };
183
+ };
184
+ export type ArtifactCompiler = {
185
+ name: string;
186
+ version: string;
187
+ edition: CompilerEdition;
188
+ optimizerVersion: OptimizerVersion;
189
+ };
190
+ export type LinkedProgramSource = {
191
+ languageVersion?: LanguageVersion;
192
+ edition?: CompilerEdition;
193
+ optimizerVersion?: OptimizerVersion;
194
+ states?: StateDecl[];
195
+ helpers: Helper[];
196
+ contracts: Contract[];
197
+ };
198
+ /**
199
+ * How to reproduce an artifact: the single source file, or for package builds the linked
200
+ * program (every helper and contract after import resolution, with source spans) together
201
+ * with the constructor values of every tree.
202
+ */
203
+ export type ArtifactSource = {
204
+ text: string;
205
+ file: string;
206
+ bindings: Record<string, Record<string, string | boolean>>;
207
+ } | {
208
+ program: LinkedProgramSource;
209
+ bindings: Record<string, Record<string, string | boolean>>;
210
+ };
211
+ export type ContractArtifact = {
212
+ languageVersion?: LanguageVersion;
213
+ schema: 'lotus/contract-artifact/2';
214
+ target: 'P01-P02-P03-candidate-2026-10-14';
215
+ contract: string;
216
+ kind?: 'contract' | 'token';
217
+ constructor: {
218
+ name: string;
219
+ type: ValueType;
220
+ }[];
221
+ bindings: {
222
+ name: string;
223
+ type: ValueType;
224
+ value: string | boolean;
225
+ }[];
226
+ methods: MethodArtifact[];
227
+ policy: {
228
+ branches: [string];
229
+ paths: [[0]];
230
+ root: string;
231
+ treeRecipe: 'sorted-leaves-largest-power-split-v1';
232
+ };
233
+ /** Present only for package builds (CABI-07); see packages.ts. */
234
+ build?: import('./packages.js').BuildGraph;
235
+ /** Library contracts this artifact commits to (CABI-08). Omitted when empty so single-file artifacts stay unchanged. */
236
+ links?: LinkedContract[];
237
+ /** The compiler that produced the scripts; roots depend on its version, edition and optimizer. */
238
+ compiler: ArtifactCompiler;
239
+ /** Single-file builds: the exact source and options, so a reader can recompile and compare. */
240
+ source?: ArtifactSource;
241
+ };
242
+ export type CompileOptions = {
243
+ languageVersion?: LanguageVersion;
244
+ edition?: CompilerEdition;
245
+ optimizerVersion?: OptimizerVersion;
246
+ contract: string;
247
+ bindings: Record<string, Record<string, BoundValue>>;
248
+ optimize?: boolean;
249
+ target?: TargetId;
250
+ };
251
+ export declare const MAX_SOURCE = 65536;
252
+ export declare const MAX_SCRIPT = 8192;
253
+ export declare const MAX_OPS = 4096;
254
+ export declare const MAX_EXPANSIONS = 256;
255
+ export declare const MAX_METHODS = 16;
256
+ export declare const MAX_INFERENCE_VISITS = 8192;
257
+ export declare const MAX_DEPENDENCY_VISITS = 8192;
258
+ export declare const INT_MIN: bigint;
259
+ export declare const INT_MAX: bigint;
260
+ export declare const INT_RANGE = "Int exceeds signed 128-bit range";
261
+ /** @internal Package builds: the linked program in the artifact's `source.program` form. */
262
+ export declare function linkedProgramSource(program: Program): LinkedProgramSource;
263
+ /** @internal Constructor values in the artifact's string form. */
264
+ export declare function sourceBindings(bindings: CompileOptions['bindings']): Record<string, Record<string, string | boolean>>;
265
+ /** Top-level `&&` only. Nested `||` stays intact so it is not rewritten as `require`. */
266
+ export declare function conjuncts(expr: Expr): Expr[];
267
+ export declare function helperReturn(body: HelperStmt[]): Extract<HelperStmt, {
268
+ kind: 'return';
269
+ }> | undefined;
270
+ /**
271
+ * Equality operands: the same type, or compatible branch roots (BranchRoot / ContractRootHash).
272
+ * Under edition 2026.1, a plain Bytes32 also compares with any 32-byte tagged hash type so
273
+ * legacy contracts continue to typecheck identically. Under edition 2026.2, raw Bytes32 and
274
+ * tagged hash types are distinct and require explicit bytes32(...) or constructor conversion.
275
+ * Distinct tagged hash kinds always stay incomparable with each other.
276
+ */
277
+ export declare function comparable(a: ValueType, b: ValueType, edition?: CompilerEdition): boolean;
278
+ export declare function decodedInt(data: Uint8Array): bigint;
279
+ export declare function encodedInt(value: bigint): Uint8Array;
280
+ export declare function literal(value: BoundValue, type: ValueType): {
281
+ bytes: Uint8Array;
282
+ binding: Binding;
283
+ };
284
+ export declare function leafHash(script: Uint8Array): Uint8Array;
285
+ export type Tree = {
286
+ root: Uint8Array;
287
+ proofs: Map<string, Uint8Array[]>;
288
+ };
289
+ export declare function tree(leaves: {
290
+ name: string;
291
+ hash: Uint8Array;
292
+ }[]): Tree;
package/dist/ast.js ADDED
@@ -0,0 +1,150 @@
1
+ /** Core AST, type, binding, Merkle-tree, and artifact definitions for Lotus V2 contracts. */
2
+ import { bytes, concat, tagged, uint, unhex } from './compiler.js';
3
+ import { schnorr } from '@noble/curves/secp256k1';
4
+ export const TAGGED_HASH_TYPES = [
5
+ 'TxId',
6
+ 'StateRoot',
7
+ 'ChainId',
8
+ 'SigHash',
9
+ 'TokenId',
10
+ 'BranchRoot',
11
+ 'ContractRootHash',
12
+ 'MethodLeafHash',
13
+ ];
14
+ export function isTaggedHashType(type) {
15
+ return TAGGED_HASH_TYPES.includes(type);
16
+ }
17
+ /** BranchRoot and ContractRootHash are compatible nominal aliases for a 32-byte contract branch root. */
18
+ export function isBranchRootType(type) {
19
+ return type === 'BranchRoot' || type === 'ContractRootHash';
20
+ }
21
+ export const MAX_SOURCE = 65536;
22
+ export const MAX_SCRIPT = 8192;
23
+ export const MAX_OPS = 4096;
24
+ export const MAX_EXPANSIONS = 256;
25
+ export const MAX_METHODS = 16;
26
+ export const MAX_INFERENCE_VISITS = 8192;
27
+ export const MAX_DEPENDENCY_VISITS = 8192;
28
+ export const INT_MIN = -(1n << 127n);
29
+ export const INT_MAX = 1n << 127n;
30
+ export const INT_RANGE = 'Int exceeds signed 128-bit range';
31
+ /** @internal Package builds: the linked program in the artifact's `source.program` form. */
32
+ export function linkedProgramSource(program) {
33
+ return JSON.parse(JSON.stringify({
34
+ ...(program.languageVersion === 1 ? { languageVersion: 1 } : {}),
35
+ ...(program.edition !== undefined ? { edition: program.edition } : {}),
36
+ ...(program.optimizerVersion !== undefined ? { optimizerVersion: program.optimizerVersion } : {}),
37
+ ...(program.states && program.states.size > 0 ? { states: [...program.states.values()] } : {}),
38
+ helpers: [...program.helpers.values()],
39
+ contracts: [...program.contracts.values()],
40
+ }));
41
+ }
42
+ /** @internal Constructor values in the artifact's string form. */
43
+ export function sourceBindings(bindings) {
44
+ return Object.fromEntries(Object.entries(bindings).map(([tree, values]) => [
45
+ tree,
46
+ Object.fromEntries(Object.entries(values).map(([name, value]) => [name, typeof value === 'bigint' ? value.toString() : value])),
47
+ ]));
48
+ }
49
+ /** Top-level `&&` only. Nested `||` stays intact so it is not rewritten as `require`. */
50
+ export function conjuncts(expr) {
51
+ if (expr.kind === 'binary' && expr.value === '&&' && expr.left && expr.right)
52
+ return [...conjuncts(expr.left), ...conjuncts(expr.right)];
53
+ return [expr];
54
+ }
55
+ export function helperReturn(body) {
56
+ const stmt = body.find(item => item.kind === 'return');
57
+ return stmt?.kind === 'return' ? stmt : undefined;
58
+ }
59
+ /**
60
+ * Equality operands: the same type, or compatible branch roots (BranchRoot / ContractRootHash).
61
+ * Under edition 2026.1, a plain Bytes32 also compares with any 32-byte tagged hash type so
62
+ * legacy contracts continue to typecheck identically. Under edition 2026.2, raw Bytes32 and
63
+ * tagged hash types are distinct and require explicit bytes32(...) or constructor conversion.
64
+ * Distinct tagged hash kinds always stay incomparable with each other.
65
+ */
66
+ export function comparable(a, b, edition = '2026.1') {
67
+ if (a === b)
68
+ return true;
69
+ if (isBranchRootType(a) && isBranchRootType(b))
70
+ return true;
71
+ if (edition === '2026.2')
72
+ return false;
73
+ return (a === 'Bytes32' && isTaggedHashType(b)) || (b === 'Bytes32' && isTaggedHashType(a));
74
+ }
75
+ export function decodedInt(data) {
76
+ let n = 0n;
77
+ for (let i = data.length - 1; i >= 0; i--)
78
+ n = (n << 8n) | BigInt(data[i]);
79
+ return data.length && data[data.length - 1] & 0x80 ? n - (1n << BigInt(8 * data.length)) : n;
80
+ }
81
+ export function encodedInt(value) {
82
+ if (value < -(1n << 127n) || value >= (1n << 127n))
83
+ throw new Error('Int exceeds signed 128-bit range');
84
+ return uint(value < 0n ? (1n << 128n) + value : value, 16);
85
+ }
86
+ export function literal(value, type) {
87
+ if (type === 'Int' || type === 'Amount') {
88
+ const text = typeof value === 'bigint' ? value.toString() : value;
89
+ if (typeof text !== 'string' || !/^(0|-?[1-9][0-9]*)$/.test(text))
90
+ throw new Error('Int binding requires canonical decimal string or bigint');
91
+ const n = BigInt(text);
92
+ return { bytes: encodedInt(n), binding: { type, value: n.toString() } };
93
+ }
94
+ if (type === 'Bool') {
95
+ if (typeof value !== 'boolean')
96
+ throw new Error('Bool binding requires boolean');
97
+ return { bytes: encodedInt(value ? 1n : 0n), binding: { type, value } };
98
+ }
99
+ if (typeof value !== 'string')
100
+ throw new Error(`${type} binding requires lowercase hex`);
101
+ const x = unhex(value);
102
+ const exact32 = type === 'PublicKey' || type === 'Bytes32' || isTaggedHashType(type);
103
+ const limit = exact32 ? 32 : type === 'Signature' ? 64 : type.startsWith('Bytes(') ? Number(type.slice(6, -1)) : 0;
104
+ if (!limit || (exact32 ? x.length !== 32 : type === 'Signature' ? x.length !== 64 : x.length > limit))
105
+ throw new Error(`${type} binding width`);
106
+ if (type === 'PublicKey') {
107
+ try {
108
+ schnorr.utils.lift_x(BigInt(`0x${value}`));
109
+ }
110
+ catch {
111
+ throw new Error('PublicKey is not a BIP340 x-only curve point');
112
+ }
113
+ }
114
+ return { bytes: x, binding: { type, value } };
115
+ }
116
+ function compareLE(a, b) {
117
+ for (let i = 31; i >= 0; i--)
118
+ if (a[i] !== b[i])
119
+ return a[i] - b[i];
120
+ return 0;
121
+ }
122
+ function nodeHash(a, b) {
123
+ return tagged('branch', concat(Uint8Array.of(1), ...(compareLE(a, b) <= 0 ? [a, b] : [b, a])));
124
+ }
125
+ export function leafHash(script) {
126
+ return tagged('branch', concat(Uint8Array.of(0), bytes(script)));
127
+ }
128
+ export function tree(leaves) {
129
+ if (!leaves.length)
130
+ throw new Error('empty method tree');
131
+ const sorted = [...leaves].sort((a, b) => compareLE(a.hash, b.hash));
132
+ for (let i = 1; i < sorted.length; i++)
133
+ if (compareLE(sorted[i - 1].hash, sorted[i].hash) === 0)
134
+ throw new Error('duplicate method leaf');
135
+ function build(items) {
136
+ if (items.length === 1)
137
+ return { root: items[0].hash, proofs: new Map([[items[0].name, []]]) };
138
+ let k = 1;
139
+ while (k * 2 < items.length)
140
+ k *= 2;
141
+ const a = build(items.slice(0, k)), b = build(items.slice(k));
142
+ const proofs = new Map();
143
+ for (const [name, p] of a.proofs)
144
+ proofs.set(name, [...p, b.root]);
145
+ for (const [name, p] of b.proofs)
146
+ proofs.set(name, [...p, a.root]);
147
+ return { root: nodeHash(a.root, b.root), proofs };
148
+ }
149
+ return build(sorted);
150
+ }
@@ -0,0 +1,6 @@
1
+ import type { PaymentArtifact } from './compiler.js';
2
+ import type { ContractArtifact } from './generic.js';
3
+ export declare function generateTypeScript(a: PaymentArtifact): string;
4
+ export declare function generatePython(a: PaymentArtifact): string;
5
+ export declare function generateContractTypeScript(a: ContractArtifact): string;
6
+ export declare function generateContractPython(a: ContractArtifact): string;
@@ -0,0 +1,134 @@
1
+ import { assertPortableName } from './names.js';
2
+ function safeName(name) { return assertPortableName(name); }
3
+ export function generateTypeScript(a) {
4
+ const n = safeName(a.contract);
5
+ return `// Generated by @givelotus/compiler; artifact schema ${a.schema}.\n` +
6
+ `import type { PaymentArtifact } from '@givelotus/compiler';\nimport { preparePayment, finalizePayment, type PaymentContext, type PaymentPlan } from '@givelotus/compiler/runtime';\n` +
7
+ `export class ${n} {\n readonly artifact: PaymentArtifact;\n constructor(artifact: PaymentArtifact) { if (artifact.schema !== 'lotus/payment-artifact/1') throw new Error('artifact version'); this.artifact = artifact; }\n` +
8
+ ` prepareSpend(context: PaymentContext): PaymentPlan { return preparePayment(this.artifact, context); }\n` +
9
+ ` finalizeSpend(plan: PaymentPlan, signature: Uint8Array) { return finalizePayment(plan, signature); }\n}\n`;
10
+ }
11
+ export function generatePython(a) {
12
+ const n = safeName(a.contract);
13
+ return `# Generated by @givelotus/compiler; artifact schema ${a.schema}.\n` +
14
+ `from dataclasses import dataclass\nfrom typing import Protocol, Mapping, Any\n\n` +
15
+ `class PaymentRuntime(Protocol):\n def prepare_payment(self, artifact: Mapping[str, Any], context: Mapping[str, Any]) -> Any: ...\n def finalize_payment(self, plan: Any, signature: bytes) -> Any: ...\n\n` +
16
+ `@dataclass(frozen=True)\nclass ${n}:\n artifact: Mapping[str, Any]\n runtime: PaymentRuntime\n\n` +
17
+ ` def __post_init__(self) -> None:\n if self.artifact.get('schema') != 'lotus/payment-artifact/1':\n raise ValueError('artifact version')\n\n` +
18
+ ` def prepare_spend(self, context: Mapping[str, Any]) -> Any:\n return self.runtime.prepare_payment(self.artifact, context)\n\n` +
19
+ ` def finalize_spend(self, plan: Any, signature: bytes) -> Any:\n if type(signature) is not bytes or len(signature) != 64:\n raise ValueError('FULL signature must be 64 bytes')\n return self.runtime.finalize_payment(plan, signature)\n`;
20
+ }
21
+ const TAGGED_HASH_TYPE_SET = new Set([
22
+ 'TxId', 'StateRoot', 'ChainId', 'SigHash', 'TokenId', 'BranchRoot', 'ContractRootHash', 'MethodLeafHash',
23
+ ]);
24
+ function usedTaggedHashTypes(a) {
25
+ const seen = new Set();
26
+ for (const m of a.methods)
27
+ for (const arg of m.args)
28
+ if (TAGGED_HASH_TYPE_SET.has(arg.type))
29
+ seen.add(arg.type);
30
+ return [...seen];
31
+ }
32
+ function tsType(t) {
33
+ if (t === 'Int' || t === 'Amount')
34
+ return 'bigint';
35
+ if (t === 'Bool')
36
+ return 'boolean';
37
+ if (t === 'Signature')
38
+ return 'SigningMode | null';
39
+ if (TAGGED_HASH_TYPE_SET.has(t))
40
+ return t;
41
+ return 'Uint8Array';
42
+ }
43
+ function linkedRows(a) {
44
+ const links = a.links ?? [];
45
+ for (const link of links) {
46
+ if (!/^[0-9a-f]{64}$/.test(link.root) || !/^[0-9a-f]{64}$/.test(link.packageDigest))
47
+ throw new Error('linked contract root is not 32-byte hex');
48
+ safeName(link.name);
49
+ for (const method of link.methods)
50
+ safeName(method.name);
51
+ }
52
+ return links;
53
+ }
54
+ export function generateContractTypeScript(a) {
55
+ const contract = safeName(a.contract);
56
+ const mint = a.kind === 'token';
57
+ const lines = [
58
+ `// Generated from ${a.schema}; constructor values and method proofs remain in the artifact.`,
59
+ `// Calls are planned by the transaction planner: the contract input can be combined with other`,
60
+ `// inputs, and the fee policy (C14a/C14b/C14c, P05 cu share) and C16a amount limits apply.`,
61
+ `import type { ContractArtifact } from '@givelotus/compiler/generic';`,
62
+ `import { ${mint ? 'contractMintIntent' : 'contractSpendIntent'}, finalizeTransactionCall, planInvokes, prepareTransactionCall, type ${mint ? 'ContractMintContext' : 'ContractSpendContext'}, type SigningMode, type TransactionFinal, type TransactionPlan } from '@givelotus/compiler/transaction-runtime';`,
63
+ ];
64
+ for (const hashType of usedTaggedHashTypes(a))
65
+ lines.push(`export type ${hashType} = Uint8Array;`);
66
+ for (const m of a.methods) {
67
+ const name = safeName(m.name);
68
+ const title = `${contract}${name[0].toUpperCase()}${name.slice(1)}`;
69
+ lines.push(`export type ${title}Args = Readonly<{ ${m.args.map(x => `${safeName(x.name)}: ${tsType(x.type)};`).join(' ')} }>;`);
70
+ }
71
+ lines.push('/** Signatures keyed by the plan\'s request keys (`input:witness:argument`). */', 'export type Signatures = Readonly<Record<string, Uint8Array>>;', `export class ${contract} {`, ` readonly artifact: ContractArtifact;`, ` constructor(artifact: ContractArtifact) { if (artifact.schema !== 'lotus/contract-artifact/2' || artifact.contract !== '${contract}') throw new Error('artifact identity'); this.artifact = artifact; }`);
72
+ for (const m of a.methods) {
73
+ const name = safeName(m.name), upper = `${name[0].toUpperCase()}${name.slice(1)}`, title = `${contract}${upper}`;
74
+ lines.push(mint
75
+ ? ` prepare${upper}(context: ContractMintContext, args: ${title}Args): TransactionPlan { return prepareTransactionCall(contractMintIntent(this.artifact, '${name}', context, args)); }`
76
+ : ` prepare${upper}(context: ContractSpendContext, args: ${title}Args): TransactionPlan { return prepareTransactionCall(contractSpendIntent(this.artifact, '${name}', context, args)); }`, ` finalize${upper}(plan: TransactionPlan, signatures: Signatures): TransactionFinal { if (!planInvokes(plan, this.artifact, '${name}')) throw new Error('method plan mismatch'); return finalizeTransactionCall(plan, signatures); }`);
77
+ }
78
+ lines.push('}');
79
+ const links = linkedRows(a);
80
+ if (links.length) {
81
+ lines.push('', '/** Linked library contracts. Roots are compile-time commitments, not VM calls. */', 'export const linkedContracts = [', ...links.map(link => ` { name: '${safeName(link.name)}', packageDigest: '${link.packageDigest}', root: '${link.root}', methods: [${link.methods.map(m => `'${safeName(m.name)}'`).join(', ')}] },`), '] as const;');
82
+ }
83
+ lines.push('');
84
+ return lines.join('\n');
85
+ }
86
+ function pyType(t) {
87
+ if (t === 'Int' || t === 'Amount')
88
+ return 'int';
89
+ if (t === 'Bool')
90
+ return 'bool';
91
+ if (t === 'Signature')
92
+ return 'Optional[str]';
93
+ if (TAGGED_HASH_TYPE_SET.has(t))
94
+ return t;
95
+ return 'bytes';
96
+ }
97
+ export function generateContractPython(a) {
98
+ const contract = safeName(a.contract);
99
+ const mint = a.kind === 'token';
100
+ const lines = [
101
+ `# Generated from ${a.schema}; requires the maintained lotus_v2_transaction_runtime module.`,
102
+ `# Calls are planned by the transaction planner: the contract input can be combined with other`,
103
+ `# inputs, and the fee policy and amount limits apply.`,
104
+ `from typing import Optional, TypedDict`,
105
+ `from lotus_v2_transaction_runtime import (`,
106
+ ` TransactionPlan,`,
107
+ ` ${mint ? 'contract_mint_intent' : 'contract_spend_intent'},`,
108
+ ` finalize_transaction_call,`,
109
+ ` plan_invokes,`,
110
+ ` prepare_transaction_call,`,
111
+ `)`,
112
+ '',
113
+ ];
114
+ const pyHashes = usedTaggedHashTypes(a);
115
+ if (pyHashes.length) {
116
+ for (const hashType of pyHashes)
117
+ lines.push(`${hashType} = bytes`);
118
+ lines.push('');
119
+ }
120
+ for (const m of a.methods) {
121
+ const name = safeName(m.name), title = `${contract}${name[0].toUpperCase()}${name.slice(1)}`;
122
+ lines.push(`class ${title}Args(TypedDict):`, ...(m.args.length ? m.args.map(x => ` ${safeName(x.name)}: ${pyType(x.type)}`) : [' pass']), '');
123
+ }
124
+ lines.push(`class ${contract}:`, ` def __init__(self, artifact: dict):`, ` if artifact.get('schema') != 'lotus/contract-artifact/2' or artifact.get('contract') != '${contract}':`, ` raise ValueError('artifact identity')`, ` self.artifact = artifact`, '');
125
+ for (const m of a.methods) {
126
+ const name = safeName(m.name), upper = `${name[0].toUpperCase()}${name.slice(1)}`, title = `${contract}${upper}`;
127
+ lines.push(` def prepare${upper}(self, context: dict, args: ${title}Args) -> TransactionPlan:`, ` return prepare_transaction_call(${mint ? 'contract_mint_intent' : 'contract_spend_intent'}(self.artifact, '${name}', context, args))`, '', ` def finalize${upper}(self, plan: TransactionPlan, signatures: dict[str, bytes]) -> dict:`, ` if not plan_invokes(plan, self.artifact, '${name}'):`, ` raise ValueError('method plan mismatch')`, ` return finalize_transaction_call(plan, signatures)`, '');
128
+ }
129
+ const links = linkedRows(a);
130
+ if (links.length) {
131
+ lines.push('LINKED_CONTRACTS = (', ...links.map(link => ` {"name": "${safeName(link.name)}", "package_digest": "${link.packageDigest}", "root": "${link.root}", "methods": (${link.methods.map(m => `"${safeName(m.name)}"`).join(', ')},)},`), ')');
132
+ }
133
+ return lines.join('\n');
134
+ }
@@ -0,0 +1,84 @@
1
+ import { type PaymentOutput } from './runtime.js';
2
+ export type ContractArtifact = {
3
+ schema: 'lotus/contract-artifact/2';
4
+ target: 'P01-P02-P03-candidate-2026-10-14';
5
+ contract: string;
6
+ kind?: 'contract' | 'token';
7
+ constructor: {
8
+ name: string;
9
+ type: string;
10
+ }[];
11
+ bindings: {
12
+ name: string;
13
+ type: string;
14
+ value: string | boolean;
15
+ }[];
16
+ methods: {
17
+ name: string;
18
+ invocation?: 'spend' | 'mint';
19
+ mintAmountParam?: string;
20
+ args: {
21
+ name: string;
22
+ type: string;
23
+ }[];
24
+ scriptHex: string;
25
+ leaf: string;
26
+ proof: string[];
27
+ root: string;
28
+ }[];
29
+ policy: {
30
+ branches: string[];
31
+ paths: number[][];
32
+ root: string;
33
+ treeRecipe: string;
34
+ };
35
+ };
36
+ export type CallContext = {
37
+ chainId: string;
38
+ prevTxid: string;
39
+ prevIndex: number;
40
+ sequence: number;
41
+ coin: PaymentOutput;
42
+ outputs: PaymentOutput[];
43
+ lock?: bigint;
44
+ profile: 'P01-P02-P03-candidate-2026-10-14';
45
+ };
46
+ export type CallValue = Uint8Array | bigint | boolean | null;
47
+ export type SignatureRequest = {
48
+ argument: string;
49
+ mode: 0;
50
+ digest: string;
51
+ chainId: string;
52
+ txid: string;
53
+ inputIndex: 0;
54
+ branchIndex: 0;
55
+ leaf: string;
56
+ feeAtoms: bigint;
57
+ };
58
+ export type CallPlan = {
59
+ artifact: ContractArtifact;
60
+ methodName: string;
61
+ context: CallContext;
62
+ arguments: Record<string, CallValue>;
63
+ unsignedWire: Uint8Array;
64
+ txid: string;
65
+ requests: SignatureRequest[];
66
+ };
67
+ export type CallFinal = {
68
+ wire: Uint8Array;
69
+ txid: string;
70
+ txhash: string;
71
+ stages: {
72
+ assembly: 'passed';
73
+ framing: 'passed';
74
+ signature: 'unavailable';
75
+ invocation: 'unavailable';
76
+ contextual: 'unavailable';
77
+ block: 'unavailable';
78
+ };
79
+ };
80
+ export declare function methodRoot(scriptHex: string, proof: string[]): string;
81
+ export declare function assertContractArtifact(a: ContractArtifact): void;
82
+ export declare function encodeCallValue(type: string, value: CallValue): Uint8Array;
83
+ export declare function prepareContractCall(a: ContractArtifact, methodName: string, c: CallContext, args: Record<string, CallValue>): CallPlan;
84
+ export declare function finalizeContractCall(plan: CallPlan, signatures: Record<string, Uint8Array>): CallFinal;