@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,83 @@
1
+ import { type ContractArtifact, type CallValue } from './call-runtime.js';
2
+ export type PolicyBranch = {
3
+ name: string;
4
+ index: number;
5
+ kind: 'spend' | 'data';
6
+ root: string;
7
+ artifactDigest?: string;
8
+ };
9
+ export type PolicySpec = {
10
+ name: string;
11
+ branches: PolicyBranch[];
12
+ paths: {
13
+ name: string;
14
+ branches: string[];
15
+ }[];
16
+ };
17
+ export type PolicyMetadata = {
18
+ target: string;
19
+ targetDigest: string;
20
+ profileDigest: string;
21
+ compilerRevision: string;
22
+ optimizerMode: string;
23
+ constructor: unknown[];
24
+ bindings: Record<string, unknown>;
25
+ provenance: Record<string, unknown>;
26
+ };
27
+ export type PolicyArtifact = PolicyMetadata & {
28
+ schema: 'lotus/policy-artifact/1';
29
+ languageVersion: 1;
30
+ name: string;
31
+ branches: PolicyBranch[];
32
+ paths: {
33
+ name: string;
34
+ pathIndex: number;
35
+ slots: number[];
36
+ }[];
37
+ policyEncoding: string;
38
+ policyDigest: string;
39
+ };
40
+ export type NamedWitness = {
41
+ branchName: string;
42
+ artifact: ContractArtifact & {
43
+ languageVersion?: number;
44
+ };
45
+ methodName: string;
46
+ arguments: Record<string, CallValue>;
47
+ };
48
+ /** Sorted ASCII keys/strings and safe integral numbers, identically encoded in Python. */
49
+ export declare function canonicalPolicyJson(v: unknown): string;
50
+ export declare function programArtifactDigest(a: ContractArtifact): string;
51
+ export declare function buildPolicy(spec: PolicySpec, metadata: PolicyMetadata): PolicyArtifact;
52
+ export declare function assertPolicyArtifact(a: PolicyArtifact): void;
53
+ export declare function selectPolicyWitnesses(policy: PolicyArtifact, pathName: string, witnesses: NamedWitness[]): {
54
+ pathName: string;
55
+ pathIndex: number;
56
+ witnesses: {
57
+ methodName: string;
58
+ scriptHex: string;
59
+ leaf: string;
60
+ proof: string[];
61
+ witnessCore: string;
62
+ argumentNames: string[];
63
+ argumentOrder: (string | null)[];
64
+ branchName: string;
65
+ branchIndex: number;
66
+ root: string;
67
+ }[];
68
+ };
69
+ /** Mint identity has no output slot or path index. */
70
+ export declare function selectMintWitness(w: Omit<NamedWitness, 'branchName'>): {
71
+ methodName: string;
72
+ scriptHex: string;
73
+ leaf: string;
74
+ proof: string[];
75
+ witnessCore: string;
76
+ argumentNames: string[];
77
+ argumentOrder: (string | null)[];
78
+ tokenId: string;
79
+ };
80
+ /** Construct an executable branch from a verified spend program, never a mint. */
81
+ export declare function spendPolicyBranch(name: string, index: number, artifact: NamedWitness['artifact']): PolicyBranch;
82
+ /** Build-time assertion only. On-chain covenants must check successors themselves. */
83
+ export declare function requireEveryPath(policy: PolicyArtifact, branchName: string): void;
package/dist/policy.js ADDED
@@ -0,0 +1,207 @@
1
+ /** LC-1 companion policy metadata; diagnostic hashes add no consensus fields. */
2
+ import { bytes, concat, cs, hex, tagged, unhex } from './compiler.js';
3
+ import { assertContractArtifact, encodeCallValue } from './call-runtime.js';
4
+ function fail(s) { throw new Error(s); }
5
+ function name(v) {
6
+ if (typeof v !== 'string' || !/^[A-Za-z_][A-Za-z_0-9]*$/.test(v))
7
+ fail('policy name');
8
+ }
9
+ function hash(v) {
10
+ if (typeof v !== 'string' || !/^[0-9a-f]{64}$/.test(v))
11
+ fail('policy hash');
12
+ }
13
+ const metadataKeys = ['target', 'targetDigest', 'profileDigest', 'compilerRevision', 'optimizerMode', 'constructor', 'bindings', 'provenance'];
14
+ const branchKeys = ['name', 'index', 'kind', 'root', 'artifactDigest'];
15
+ function fields(value, allowed) {
16
+ if (Object.keys(value).some(key => !allowed.includes(key)))
17
+ fail('policy unknown field');
18
+ }
19
+ /** Sorted ASCII keys/strings and safe integral numbers, identically encoded in Python. */
20
+ export function canonicalPolicyJson(v) {
21
+ if (v === null || typeof v === 'boolean')
22
+ return JSON.stringify(v);
23
+ if (typeof v === 'string') {
24
+ if (/[^\x20-\x7e]/.test(v))
25
+ fail('policy JSON string');
26
+ return JSON.stringify(v);
27
+ }
28
+ if (typeof v === 'number') {
29
+ if (!Number.isSafeInteger(v))
30
+ fail('policy JSON number');
31
+ return String(v);
32
+ }
33
+ if (Array.isArray(v))
34
+ return '[' + v.map(canonicalPolicyJson).join(',') + ']';
35
+ if (v && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype)
36
+ return '{' + Object.keys(v).sort().map(k => canonicalPolicyJson(k) + ':' + canonicalPolicyJson(v[k])).join(',') + '}';
37
+ return fail('policy JSON value');
38
+ }
39
+ export function programArtifactDigest(a) { return hex(tagged('app/program-artifact/1', new TextEncoder().encode(canonicalPolicyJson(a)))); }
40
+ function compare(a, b) {
41
+ for (let i = 0; i < Math.min(a.length, b.length); i++)
42
+ if (a[i] !== b[i])
43
+ return a[i] - b[i];
44
+ return a.length - b.length;
45
+ }
46
+ export function buildPolicy(spec, metadata) {
47
+ fields(spec, ['name', 'branches', 'paths']);
48
+ fields(metadata, metadataKeys);
49
+ name(spec.name);
50
+ if (!Array.isArray(spec.branches) || spec.branches.length < 1 || spec.branches.length > 16 || !Array.isArray(spec.paths) || spec.paths.length < 1 || spec.paths.length > 16)
51
+ fail('policy branch/path count');
52
+ hash(metadata.targetDigest);
53
+ hash(metadata.profileDigest);
54
+ for (const k of ['target', 'compilerRevision', 'optimizerMode'])
55
+ if (typeof metadata[k] !== 'string' || !metadata[k])
56
+ fail('policy metadata');
57
+ if (!Array.isArray(metadata.constructor) || !metadata.bindings || Object.getPrototypeOf(metadata.bindings) !== Object.prototype || !metadata.provenance || Object.getPrototypeOf(metadata.provenance) !== Object.prototype)
58
+ fail('policy metadata');
59
+ canonicalPolicyJson(metadata);
60
+ for (const branch of spec.branches) {
61
+ if (!branch || typeof branch !== 'object' || Array.isArray(branch))
62
+ fail('policy artifact structure');
63
+ fields(branch, branchKeys);
64
+ if (!Number.isInteger(branch.index) || branch.index < 0 || branch.index > 15)
65
+ fail('policy slots');
66
+ }
67
+ for (const path of spec.paths) {
68
+ if (!path || typeof path !== 'object' || Array.isArray(path))
69
+ fail('policy artifact structure');
70
+ fields(path, ['name', 'branches']);
71
+ }
72
+ const branches = spec.branches.map(b => ({ ...b })).sort((a, b) => a.index - b.index), names = new Set(), roots = new Set();
73
+ branches.forEach((b, i) => {
74
+ name(b.name);
75
+ hash(b.root);
76
+ if (!Number.isInteger(b.index) || b.index !== i)
77
+ fail('policy slots');
78
+ if (names.has(b.name.toLowerCase()))
79
+ fail('duplicate branch name');
80
+ names.add(b.name.toLowerCase());
81
+ if (roots.has(b.root))
82
+ fail('duplicate branch root');
83
+ roots.add(b.root);
84
+ if (b.kind !== 'spend' && b.kind !== 'data')
85
+ fail('policy branch kind');
86
+ if (b.kind === 'spend')
87
+ hash(b.artifactDigest);
88
+ else if (b.artifactDigest !== undefined)
89
+ fail('data artifact digest');
90
+ });
91
+ const pn = new Set();
92
+ const paths = spec.paths.map(p => {
93
+ name(p.name);
94
+ if (pn.has(p.name.toLowerCase()))
95
+ fail('duplicate path name');
96
+ pn.add(p.name.toLowerCase());
97
+ if (!Array.isArray(p.branches) || !p.branches.length || p.branches.length > 16)
98
+ fail('policy path');
99
+ const slots = p.branches.map(n => {
100
+ const b = branches.find(b => b.name === n);
101
+ if (!b)
102
+ return fail('unknown branch');
103
+ if (b.kind !== 'spend')
104
+ fail('data branch in path');
105
+ return b.index;
106
+ }).sort((a, b) => a - b);
107
+ if (new Set(slots).size !== slots.length)
108
+ fail('duplicate path slot');
109
+ return { name: p.name, pathIndex: 0, slots };
110
+ }).sort((a, b) => compare(a.slots, b.slots));
111
+ paths.forEach((p, i) => {
112
+ if (i && compare(paths[i - 1].slots, p.slots) === 0)
113
+ fail('duplicate path');
114
+ p.pathIndex = i;
115
+ });
116
+ const encoding = concat(cs(branches.length), ...branches.map(b => unhex(b.root, 32)), cs(paths.length), ...paths.map(p => concat(cs(p.slots.length), ...p.slots.map(cs))));
117
+ return { ...metadata, schema: 'lotus/policy-artifact/1', languageVersion: 1, name: spec.name, branches, paths, policyEncoding: hex(encoding), policyDigest: hex(tagged('app/policy/1', encoding)) };
118
+ }
119
+ export function assertPolicyArtifact(a) {
120
+ if (!a || typeof a !== 'object' || !Array.isArray(a.branches) || !Array.isArray(a.paths) || a.branches.some(b => !b || typeof b !== 'object' || Array.isArray(b)) || a.paths.some(p => !p || typeof p !== 'object' || Array.isArray(p) || !Array.isArray(p.slots) || p.slots.some(i => !Number.isInteger(i))))
121
+ fail('policy artifact structure');
122
+ fields(a, [...metadataKeys, 'schema', 'languageVersion', 'name', 'branches', 'paths', 'policyEncoding', 'policyDigest']);
123
+ for (const branch of a.branches)
124
+ fields(branch, branchKeys);
125
+ for (const path of a.paths)
126
+ fields(path, ['name', 'pathIndex', 'slots']);
127
+ if (a.schema !== 'lotus/policy-artifact/1' || a.languageVersion !== 1)
128
+ fail('unsupported policy artifact');
129
+ const { schema: _s, languageVersion: _l, name: n, branches, paths, policyEncoding: _e, policyDigest: _d, ...metadata } = a;
130
+ const fresh = buildPolicy({ name: n, branches, paths: paths.map(p => ({ name: p.name, branches: p.slots.map(i => branches[i]?.name ?? '') })) }, metadata);
131
+ if (canonicalPolicyJson(a) !== canonicalPolicyJson(fresh))
132
+ fail('policy artifact mismatch');
133
+ }
134
+ function selected(w, kind, root, digest) {
135
+ if (new Set(w.artifact.methods.map(m => m.name.toLowerCase())).size !== w.artifact.methods.length)
136
+ fail('policy program artifact');
137
+ if (w.artifact.languageVersion !== 1 || w.artifact.methods.some(m => m.invocation !== kind) || (w.artifact.kind === 'token' ? 'mint' : 'spend') !== kind)
138
+ fail('policy invocation kind');
139
+ try {
140
+ assertContractArtifact(w.artifact);
141
+ }
142
+ catch {
143
+ fail('policy program artifact');
144
+ }
145
+ if (w.artifact.policy.root !== root || (digest !== undefined && programArtifactDigest(w.artifact) !== digest))
146
+ fail('policy program identity');
147
+ const m = w.artifact.methods.find(m => m.name === w.methodName);
148
+ if (!m)
149
+ return fail('policy method');
150
+ const args = m.args.map(a => a.name);
151
+ if (Object.keys(w.arguments).length !== args.length || args.some(n => !Object.hasOwn(w.arguments, n)))
152
+ fail('policy arguments');
153
+ const argumentOrder = m.args.map(a => {
154
+ const v = w.arguments[a.name];
155
+ if (v === null && a.type === 'Signature')
156
+ return null;
157
+ try {
158
+ return hex(encodeCallValue(a.type, v));
159
+ }
160
+ catch {
161
+ return fail('policy argument value');
162
+ }
163
+ });
164
+ const witnessCore = hex(concat(bytes(unhex(m.scriptHex)), cs(m.proof.length), ...m.proof.map(p => unhex(p, 32))));
165
+ return { methodName: w.methodName, scriptHex: m.scriptHex, leaf: m.leaf, proof: [...m.proof], witnessCore, argumentNames: args, argumentOrder };
166
+ }
167
+ export function selectPolicyWitnesses(policy, pathName, witnesses) {
168
+ assertPolicyArtifact(policy);
169
+ const path = policy.paths.find(p => p.name === pathName);
170
+ if (!path)
171
+ return fail('policy path name');
172
+ if (!Array.isArray(witnesses) || new Set(witnesses.map(w => w.branchName)).size !== witnesses.length)
173
+ fail('duplicate named witness');
174
+ const required = path.slots.map(i => policy.branches[i]);
175
+ if (witnesses.length !== required.length || required.some(b => !witnesses.some(w => w.branchName === b.name)))
176
+ fail('policy witness membership');
177
+ for (const w of witnesses)
178
+ if (w.artifact.target !== policy.target)
179
+ fail('policy program target');
180
+ return { pathName, pathIndex: path.pathIndex, witnesses: required.map(b => ({ branchName: b.name, branchIndex: b.index, root: b.root, ...selected(witnesses.find(w => w.branchName === b.name), 'spend', b.root, b.artifactDigest) })) };
181
+ }
182
+ /** Mint identity has no output slot or path index. */
183
+ export function selectMintWitness(w) {
184
+ const result = selected(w, 'mint', w.artifact.policy.root);
185
+ if (['branchName', 'branchIndex', 'pathName', 'pathIndex'].some(k => Object.hasOwn(w, k)))
186
+ fail('mint policy selector');
187
+ return { tokenId: w.artifact.policy.root, ...result };
188
+ }
189
+ /** Construct an executable branch from a verified spend program, never a mint. */
190
+ export function spendPolicyBranch(name, index, artifact) {
191
+ if (artifact.languageVersion !== 1 || artifact.kind === 'token' || artifact.methods.some(m => m.invocation !== 'spend'))
192
+ fail('policy invocation kind');
193
+ try {
194
+ assertContractArtifact(artifact);
195
+ }
196
+ catch {
197
+ fail('policy program artifact');
198
+ }
199
+ return { name, index, kind: 'spend', root: artifact.policy.root, artifactDigest: programArtifactDigest(artifact) };
200
+ }
201
+ /** Build-time assertion only. On-chain covenants must check successors themselves. */
202
+ export function requireEveryPath(policy, branchName) {
203
+ assertPolicyArtifact(policy);
204
+ const b = policy.branches.find(b => b.name === branchName);
205
+ if (!b || b.kind !== 'spend' || policy.paths.some(p => !p.slots.includes(b.index)))
206
+ fail('policy every path');
207
+ }
@@ -0,0 +1,58 @@
1
+ import { type PaymentArtifact } from './compiler.js';
2
+ export type PaymentOutput = {
3
+ value: bigint;
4
+ branches: string[];
5
+ paths: number[][];
6
+ flags?: 0;
7
+ };
8
+ export type PaymentCoin = PaymentOutput & {
9
+ flags?: 0;
10
+ };
11
+ export type PaymentContext = {
12
+ chainId: string;
13
+ prevTxid: string;
14
+ prevIndex: number;
15
+ sequence: number;
16
+ coin: PaymentCoin;
17
+ outputs: PaymentOutput[];
18
+ lock?: bigint;
19
+ profile: 'payment-fixture-p01-v1';
20
+ };
21
+ export type PaymentPlan = {
22
+ artifact: PaymentArtifact;
23
+ context: PaymentContext;
24
+ unsignedWire: Uint8Array;
25
+ txid: string;
26
+ message: Uint8Array;
27
+ signingIntent: {
28
+ chainId: string;
29
+ mode: 0;
30
+ inputIndex: 0;
31
+ branchIndex: 0;
32
+ leaf: string;
33
+ outputs: PaymentOutput[];
34
+ feeAtoms: bigint;
35
+ };
36
+ };
37
+ export type PaymentFinal = {
38
+ wire: Uint8Array;
39
+ txid: string;
40
+ txhash: string;
41
+ message: string;
42
+ signature: string;
43
+ stages: {
44
+ assembly: 'passed';
45
+ framing: 'passed';
46
+ signature: 'passed';
47
+ invocation: 'unavailable';
48
+ contextual: 'unavailable';
49
+ block: 'unavailable';
50
+ };
51
+ };
52
+ /** C16a: MAX_MONEY = 2^62 atoms bounds every amount, native or token. */
53
+ export declare const MAX_MONEY: bigint;
54
+ export declare function assertMoneyRange(value: bigint, what: string): void;
55
+ export declare function encodeOutput(o: PaymentOutput): Uint8Array;
56
+ export declare function encodePaymentWireUnchecked(a: PaymentArtifact, c: PaymentContext, signature: Uint8Array): Uint8Array;
57
+ export declare function preparePayment(a: PaymentArtifact, c: PaymentContext): PaymentPlan;
58
+ export declare function finalizePayment(plan: PaymentPlan, signature: Uint8Array): PaymentFinal;
@@ -0,0 +1,126 @@
1
+ import { schnorr } from '@noble/curves/secp256k1';
2
+ import { bytes, concat, cs, hex, tagged, uint, unhex } from './compiler.js';
3
+ function u32(n) { if (!Number.isInteger(n) || n < 0 || n > 0xffffffff)
4
+ throw new Error('u32 range'); return uint(BigInt(n), 4); }
5
+ /** C16a: MAX_MONEY = 2^62 atoms bounds every amount, native or token. */
6
+ export const MAX_MONEY = 1n << 62n;
7
+ export function assertMoneyRange(value, what) {
8
+ if (typeof value !== 'bigint' || value < 0n || value > MAX_MONEY)
9
+ throw new Error(`${what} ${value} is outside MoneyRange 0..2^62 (C16a)`);
10
+ }
11
+ function validateOutput(o, what = 'output value') {
12
+ if (o.flags !== undefined && o.flags !== 0)
13
+ throw new Error('only native spendable output supported');
14
+ assertMoneyRange(o.value, what);
15
+ if (o.branches.length < 1 || o.branches.length > 16 || o.paths.length < 1 || o.paths.length > 16)
16
+ throw new Error('output branch/path count');
17
+ const roots = o.branches.map(x => hex(unhex(x, 32)));
18
+ if (new Set(roots).size !== roots.length)
19
+ throw new Error('duplicate branches');
20
+ let prev = '';
21
+ for (const path of o.paths) {
22
+ if (!path.length || path.length > 16 || path.some((x, i) => !Number.isInteger(x) || x < 0 || x >= roots.length || (i > 0 && x <= path[i - 1])))
23
+ throw new Error('invalid path');
24
+ const key = path.map(x => String.fromCharCode(x + 1)).join('');
25
+ if (prev && !(prev < key))
26
+ throw new Error('path order');
27
+ prev = key;
28
+ }
29
+ }
30
+ export function encodeOutput(o) {
31
+ validateOutput(o);
32
+ return concat(Uint8Array.of(0), uint(o.value, 8), cs(o.branches.length), ...o.branches.map(x => unhex(x, 32)), cs(o.paths.length), ...o.paths.map(path => concat(cs(path.length), ...path.map(cs))));
33
+ }
34
+ function indexedRoot(leaves) {
35
+ if (!leaves.length)
36
+ return tagged('merkleidx', Uint8Array.of(2));
37
+ let nodes = leaves;
38
+ let level = 0;
39
+ while (nodes.length > 1) {
40
+ if (nodes.length & 1)
41
+ nodes = [...nodes, new Uint8Array(32)];
42
+ const next = [];
43
+ for (let i = 0; i < nodes.length; i += 2)
44
+ next.push(tagged('merkleidx', concat(Uint8Array.of(1), uint(BigInt(level), 2), nodes[i], nodes[i + 1])));
45
+ nodes = next;
46
+ level++;
47
+ }
48
+ return nodes[0];
49
+ }
50
+ function inputParts(a, c, signature) {
51
+ const script = unhex(a.scriptHex);
52
+ const prefix = concat(unhex(c.prevTxid, 32), u32(c.prevIndex), u32(c.sequence), Uint8Array.of(1), cs(0), cs(1), bytes(script), cs(0));
53
+ return { core: prefix, full: concat(prefix, cs(signature ? 1 : 0), ...(signature ? [bytes(signature)] : [])) };
54
+ }
55
+ function header(c) { return concat(u32(7), uint(c.lock ?? 0n, 8), uint(1n, 2), uint(BigInt(c.outputs.length), 2)); }
56
+ function outputLeaves(c) { return c.outputs.map(o => tagged('output', bytes(encodeOutput(o)))); }
57
+ function txid(a, c) {
58
+ const root = indexedRoot([tagged('inputcore', inputParts(a, c).core)]);
59
+ return tagged('txid', concat(unhex(c.chainId, 32), header(c), root, indexedRoot(outputLeaves(c))));
60
+ }
61
+ function wire(a, c, signature) {
62
+ return concat(header(c), inputParts(a, c, signature).full, ...c.outputs.map(encodeOutput));
63
+ }
64
+ // Offline negative-fixture construction only; this does not verify an invocation.
65
+ export function encodePaymentWireUnchecked(a, c, signature) {
66
+ assertArtifact(a);
67
+ if (!(signature instanceof Uint8Array) || signature.length !== 64)
68
+ throw new Error('FULL signature must be 64 bytes');
69
+ preparePayment(a, c);
70
+ return wire(a, c, signature);
71
+ }
72
+ function assertArtifact(a) {
73
+ if (a.schema !== 'lotus/payment-artifact/1' || a.target !== 'P01-P02-P03-candidate-2026-10-14' || a.methods.length !== 1 || a.methods[0]?.name !== 'spend')
74
+ throw new Error('unsupported artifact');
75
+ const script = unhex(a.scriptHex, 34);
76
+ if (script[0] !== 0x20 || script[33] !== 0xbb)
77
+ throw new Error('unsupported script');
78
+ const leaf = hex(tagged('branch', concat(Uint8Array.of(0), bytes(script))));
79
+ if (a.policy.leaf !== leaf || a.policy.branches.length !== 1 || a.policy.branches[0] !== leaf || JSON.stringify(a.policy.paths) !== '[[0]]')
80
+ throw new Error('artifact policy mismatch');
81
+ }
82
+ export function preparePayment(a, c) {
83
+ assertArtifact(a);
84
+ if (c.profile !== 'payment-fixture-p01-v1')
85
+ throw new Error('unsupported profile');
86
+ unhex(c.chainId, 32);
87
+ unhex(c.prevTxid, 32);
88
+ u32(c.prevIndex);
89
+ u32(c.sequence);
90
+ uint(c.lock ?? 0n, 8);
91
+ const lock = c.lock ?? 0n;
92
+ if ((lock & 255n) > 2n || ((lock & 255n) === 0n && lock !== 0n))
93
+ throw new Error('invalid P01 lock encoding');
94
+ if (c.sequence !== 0xffffffff && (c.sequence & ~0x40ffff) !== 0)
95
+ throw new Error('invalid P01 sequence bits');
96
+ if (!c.outputs.length || c.outputs.length > 32)
97
+ throw new Error('fixture profile output count');
98
+ validateOutput(c.coin, 'coin value');
99
+ c.outputs.forEach((o, j) => validateOutput(o, `output ${j} value`));
100
+ if (c.coin.branches.length !== 1 || c.coin.branches[0] !== a.policy.leaf || JSON.stringify(c.coin.paths) !== '[[0]]')
101
+ throw new Error('resolved coin policy mismatch');
102
+ const sum = c.outputs.reduce((n, o) => n + o.value, 0n);
103
+ if (sum > c.coin.value)
104
+ throw new Error('negative fee');
105
+ const id = txid(a, c);
106
+ const coinRoot = indexedRoot([tagged('coinentry', bytes(encodeOutput(c.coin)))]);
107
+ const selector = concat(Uint8Array.of(1), u32(0), u32(0), unhex(a.policy.leaf, 32));
108
+ const message = tagged('sighash', concat(unhex(c.chainId, 32), Uint8Array.of(0), id, coinRoot, selector));
109
+ return { artifact: a, context: c, unsignedWire: wire(a, c), txid: hex(id), message,
110
+ signingIntent: { chainId: c.chainId, mode: 0, inputIndex: 0, branchIndex: 0, leaf: a.policy.leaf, outputs: c.outputs, feeAtoms: c.coin.value - sum } };
111
+ }
112
+ export function finalizePayment(plan, signature) {
113
+ const fresh = preparePayment(plan.artifact, plan.context);
114
+ if (hex(fresh.message) !== hex(plan.message) || fresh.txid !== plan.txid)
115
+ throw new Error('stale signing plan');
116
+ if (!(signature instanceof Uint8Array) || signature.length !== 64)
117
+ throw new Error('FULL signature must be 64 bytes');
118
+ const pubkey = unhex(plan.artifact.scriptHex.slice(2, 66), 32);
119
+ if (!schnorr.verify(signature, fresh.message, pubkey))
120
+ throw new Error('signature verification failed');
121
+ const full = inputParts(plan.artifact, plan.context, signature).full;
122
+ const fullRoot = indexedRoot([tagged('inputfull', full)]);
123
+ const txhash = tagged('txhash', concat(unhex(plan.context.chainId, 32), header(plan.context), fullRoot, indexedRoot(outputLeaves(plan.context))));
124
+ return { wire: wire(plan.artifact, plan.context, signature), txid: fresh.txid, txhash: hex(txhash), message: hex(fresh.message), signature: hex(signature),
125
+ stages: { assembly: 'passed', framing: 'passed', signature: 'passed', invocation: 'unavailable', contextual: 'unavailable', block: 'unavailable' } };
126
+ }
@@ -0,0 +1,38 @@
1
+ /** Deterministic dependency jobs for the contract compiler. */
2
+ export type SchedulerEvent = {
3
+ kind: 'start' | 'await' | 'resolve' | 'reject';
4
+ job: string;
5
+ dependency?: string;
6
+ error?: string;
7
+ source?: {
8
+ start: number;
9
+ end: number;
10
+ };
11
+ };
12
+ export type SchedulerLimits = {
13
+ maxJobs: number;
14
+ maxEdges: number;
15
+ maxDepth: number;
16
+ };
17
+ type Job<T> = {
18
+ dependencies?: string[];
19
+ discover: () => string[];
20
+ run: () => T | Promise<T>;
21
+ source?: SchedulerEvent['source'];
22
+ };
23
+ export declare class PromiseScheduler<T> {
24
+ private readonly onEvent?;
25
+ private readonly jobs;
26
+ private readonly promises;
27
+ private edges;
28
+ private readonly limits;
29
+ constructor(onEvent?: ((event: SchedulerEvent) => void) | undefined, limits?: Partial<SchedulerLimits>);
30
+ private emit;
31
+ register(name: string, dependencies: string[] | (() => string[]), run: Job<T>['run'], source?: SchedulerEvent['source']): void;
32
+ private dependencies;
33
+ private label;
34
+ private check;
35
+ run(name: string): Promise<T>;
36
+ private start;
37
+ }
38
+ export {};
@@ -0,0 +1,76 @@
1
+ export class PromiseScheduler {
2
+ onEvent;
3
+ jobs = new Map();
4
+ promises = new Map();
5
+ edges = 0;
6
+ limits;
7
+ constructor(onEvent, limits = {}) {
8
+ this.onEvent = onEvent;
9
+ this.limits = { maxJobs: limits.maxJobs ?? 1024, maxEdges: limits.maxEdges ?? 8192, maxDepth: limits.maxDepth ?? 256 };
10
+ }
11
+ emit(event) {
12
+ // Trace observers cannot interrupt dependency attachment or strand sibling jobs.
13
+ try {
14
+ this.onEvent?.(event);
15
+ }
16
+ catch { /* observer is advisory */ }
17
+ }
18
+ register(name, dependencies, run, source) {
19
+ if (this.jobs.has(name))
20
+ throw new Error(`duplicate compiler job ${name}`);
21
+ if (this.jobs.size >= this.limits.maxJobs)
22
+ throw new Error(`compiler job limit exceeded (${this.limits.maxJobs})`);
23
+ this.jobs.set(name, { discover: typeof dependencies === 'function' ? dependencies : () => dependencies, run, source });
24
+ }
25
+ dependencies(name, job) {
26
+ if (job.dependencies)
27
+ return job.dependencies;
28
+ const dependencies = [...new Set(job.discover())];
29
+ this.edges += dependencies.length;
30
+ if (this.edges > this.limits.maxEdges)
31
+ throw new Error(`compiler dependency edge limit exceeded (${this.limits.maxEdges}) at ${this.label(name)}`);
32
+ job.dependencies = dependencies;
33
+ return dependencies;
34
+ }
35
+ label(name) {
36
+ const source = this.jobs.get(name)?.source;
37
+ return source ? `${name}@UTF-8 bytes ${source.start}..${source.end}` : name;
38
+ }
39
+ check(name, active, visited) {
40
+ const at = active.indexOf(name);
41
+ if (at >= 0)
42
+ throw new Error(`dependency cycle: ${[...active.slice(at), name].map(part => this.label(part)).join(' -> ')}`);
43
+ if (visited.has(name))
44
+ return;
45
+ const job = this.jobs.get(name);
46
+ if (!job)
47
+ throw new Error(`unknown compiler job ${name}`);
48
+ if (active.length >= this.limits.maxDepth)
49
+ throw new Error(`compiler dependency depth limit exceeded (${this.limits.maxDepth}) at ${this.label(name)}`);
50
+ active.push(name);
51
+ for (const dependency of this.dependencies(name, job))
52
+ this.check(dependency, active, visited);
53
+ active.pop();
54
+ visited.add(name);
55
+ }
56
+ run(name) {
57
+ // Validate the whole reachable graph before creating promises. In particular,
58
+ // a cycle can never turn into two promises waiting on each other forever.
59
+ this.check(name, [], new Set());
60
+ return this.start(name);
61
+ }
62
+ start(name) {
63
+ const prior = this.promises.get(name);
64
+ if (prior)
65
+ return prior;
66
+ const job = this.jobs.get(name);
67
+ this.emit({ kind: 'start', job: name, source: job.source });
68
+ const dependencies = job.dependencies.map(dependency => {
69
+ this.emit({ kind: 'await', job: name, dependency, source: job.source });
70
+ return this.start(dependency);
71
+ });
72
+ const promise = Promise.all(dependencies).then(() => job.run()).then(value => { this.emit({ kind: 'resolve', job: name, source: job.source }); return value; }, error => { this.emit({ kind: 'reject', job: name, error: error.message, source: job.source }); throw error; });
73
+ this.promises.set(name, promise);
74
+ return promise;
75
+ }
76
+ }
@@ -0,0 +1,76 @@
1
+ /** Portable typed expression IR. Contains no opcode, transaction or chain constants. */
2
+ import type { SourceSpan, CapabilityRequirement, TargetDiagnostic } from './targets.js';
3
+ /** Byte widths are exact, including the empty byte string. */
4
+ export type SemanticType = {
5
+ kind: 'bytes';
6
+ length: number;
7
+ } | {
8
+ kind: 'bool';
9
+ };
10
+ export type SemanticExpr = {
11
+ kind: 'bytes';
12
+ hex: string;
13
+ span: SourceSpan;
14
+ } | {
15
+ kind: 'bool';
16
+ value: boolean;
17
+ span: SourceSpan;
18
+ } | {
19
+ kind: 'arg';
20
+ name: string;
21
+ span: SourceSpan;
22
+ } | {
23
+ kind: 'sha256' | 'hash256';
24
+ value: SemanticExpr;
25
+ span: SourceSpan;
26
+ } | {
27
+ kind: 'equal';
28
+ left: SemanticExpr;
29
+ right: SemanticExpr;
30
+ span: SourceSpan;
31
+ };
32
+ export type SemanticStmt = {
33
+ kind: 'require';
34
+ condition: SemanticExpr;
35
+ span: SourceSpan;
36
+ } | {
37
+ kind: 'if';
38
+ condition: SemanticExpr;
39
+ then: SemanticStmt[];
40
+ otherwise: SemanticStmt[];
41
+ span: SourceSpan;
42
+ };
43
+ export type SemanticProgram = {
44
+ schema: 'lotus/semantic-ir/1';
45
+ entrypoint: string;
46
+ args: {
47
+ name: string;
48
+ type: SemanticType;
49
+ span: SourceSpan;
50
+ }[];
51
+ body: SemanticStmt[];
52
+ span: SourceSpan;
53
+ };
54
+ export type SemanticValidation = {
55
+ ok: true;
56
+ program: SemanticProgram;
57
+ requirements: CapabilityRequirement[];
58
+ } | {
59
+ ok: false;
60
+ diagnostics: TargetDiagnostic[];
61
+ };
62
+ /** Parser/validation safety ceilings, not target execution or consensus limits. */
63
+ export declare const SEMANTIC_IR_LIMITS: Readonly<{
64
+ maxBytes: 8192;
65
+ maxDepth: 64;
66
+ maxNodes: 8192;
67
+ maxArgs: 256;
68
+ }>;
69
+ /**
70
+ * Validate imported IR before backend selection. Fail closed on unknown constructs.
71
+ * The returned tree and spans are detached copies; capability occurrences retain
72
+ * source order and are not deduplicated. Equal requires matching exact byte widths
73
+ * (or two Bools); byte padding and Boolean/numeric coercion are never implicit.
74
+ * This checks semantics/shape only, not target support, stack bounds or execution.
75
+ */
76
+ export declare function validateSemanticProgram(input: unknown): SemanticValidation;