@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.
- package/README.md +331 -2
- package/artifact-v2.schema.json +58 -0
- package/artifact.schema.json +19 -0
- package/dist/ast.d.ts +292 -0
- package/dist/ast.js +150 -0
- package/dist/bindings.d.ts +6 -0
- package/dist/bindings.js +134 -0
- package/dist/call-runtime.d.ts +84 -0
- package/dist/call-runtime.js +249 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +22 -0
- package/dist/compiler.d.ts +79 -0
- package/dist/compiler.js +125 -0
- package/dist/diagnostics.d.ts +163 -0
- package/dist/diagnostics.js +498 -0
- package/dist/ecash.d.ts +41 -0
- package/dist/ecash.js +190 -0
- package/dist/fees.d.ts +164 -0
- package/dist/fees.js +208 -0
- package/dist/fixture-cli.d.ts +2 -0
- package/dist/fixture-cli.js +41 -0
- package/dist/fixtures.d.ts +68 -0
- package/dist/fixtures.js +46 -0
- package/dist/forth-ir.d.ts +73 -0
- package/dist/forth-ir.js +147 -0
- package/dist/generic-cli.d.ts +2 -0
- package/dist/generic-cli.js +140 -0
- package/dist/generic.d.ts +48 -0
- package/dist/generic.js +2566 -0
- package/dist/lints.d.ts +8 -0
- package/dist/lints.js +204 -0
- package/dist/names.d.ts +1 -0
- package/dist/names.js +7 -0
- package/dist/opcodes.d.ts +154 -0
- package/dist/opcodes.js +162 -0
- package/dist/optimizer.d.ts +58 -0
- package/dist/optimizer.js +786 -0
- package/dist/package-fetch-cli.d.ts +2 -0
- package/dist/package-fetch-cli.js +17 -0
- package/dist/package-lock-cli.d.ts +2 -0
- package/dist/package-lock-cli.js +28 -0
- package/dist/package-sources.d.ts +82 -0
- package/dist/package-sources.js +785 -0
- package/dist/package-update-cli.d.ts +2 -0
- package/dist/package-update-cli.js +20 -0
- package/dist/packages.d.ts +231 -0
- package/dist/packages.js +1307 -0
- package/dist/parser.d.ts +32 -0
- package/dist/parser.js +575 -0
- package/dist/policy.d.ts +83 -0
- package/dist/policy.js +207 -0
- package/dist/runtime.d.ts +58 -0
- package/dist/runtime.js +126 -0
- package/dist/scheduler.d.ts +38 -0
- package/dist/scheduler.js +76 -0
- package/dist/semantic-ir.d.ts +76 -0
- package/dist/semantic-ir.js +231 -0
- package/dist/std.d.ts +27 -0
- package/dist/std.js +225 -0
- package/dist/target-compiler.d.ts +9 -0
- package/dist/target-compiler.js +139 -0
- package/dist/targets.d.ts +53 -0
- package/dist/targets.js +67 -0
- package/dist/toml-subset.d.ts +19 -0
- package/dist/toml-subset.js +81 -0
- package/dist/transaction-runtime.d.ts +182 -0
- package/dist/transaction-runtime.js +646 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.js +3 -0
- package/dist/vm-cost.d.ts +11 -0
- package/dist/vm-cost.js +541 -0
- package/package.json +71 -4
- package/policy-artifact.schema.json +20 -0
- package/std/custody/arbiter-escrow.lotus +20 -0
- package/std/custody/htlc.lotus +15 -0
- package/std/custody/multisig-2of3.lotus +13 -0
- package/std/custody/single-owner-wallet.lotus +9 -0
- package/std/custody/vault-with-recovery.lotus +14 -0
- package/std/defi/amm-pool-v2.lotus +97 -0
- package/std/defi/indexed-limit-order.lotus +37 -0
- package/std/nft/nft-collection.lotus +51 -0
- package/std/nft/royalty-transfer-rules.lotus +38 -0
- package/std/nft/unique-nft.lotus +30 -0
- package/std/tokens/capped-supply-token.lotus +76 -0
- package/std/tokens/fixed-supply-token.lotus +29 -0
- package/std/tokens/standard-transfer-rules.lotus +15 -0
- package/std/tokens/voucher-mint-token.lotus +31 -0
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { schnorr } from '@noble/curves/secp256k1';
|
|
2
|
+
import { bytes, concat, cs, hex, tagged, uint, unhex } from './compiler.js';
|
|
3
|
+
import { assertMoneyRange, encodeOutput } from './runtime.js';
|
|
4
|
+
import { verifyArtifactSource } from './generic.js';
|
|
5
|
+
function u32(n) { if (!Number.isInteger(n) || n < 0 || n > 0xffffffff)
|
|
6
|
+
throw new Error('u32 range'); return uint(BigInt(n), 4); }
|
|
7
|
+
function equal(a, b) { return JSON.stringify(a) === JSON.stringify(b); }
|
|
8
|
+
function validName(value) { return typeof value === 'string' && /^[A-Za-z_][A-Za-z_0-9]*$/.test(value); }
|
|
9
|
+
function validType(type) { return ['PublicKey', 'Signature', 'Bytes32', 'TokenId', 'TxId', 'StateRoot', 'ChainId', 'SigHash', 'BranchRoot', 'Int', 'Amount', 'Bool', 'MethodLeafHash', 'ContractRootHash'].includes(type) || /^Bytes\(([1-9][0-9]*)\)$/.test(type) && Number(type.slice(6, -1)) <= 8192; }
|
|
10
|
+
function node(a, b) {
|
|
11
|
+
let cmp = 0;
|
|
12
|
+
for (let i = 31; i >= 0; i--)
|
|
13
|
+
if (a[i] !== b[i]) {
|
|
14
|
+
cmp = a[i] - b[i];
|
|
15
|
+
break;
|
|
16
|
+
}
|
|
17
|
+
return tagged('branch', concat(Uint8Array.of(1), ...(cmp <= 0 ? [a, b] : [b, a])));
|
|
18
|
+
}
|
|
19
|
+
export function methodRoot(scriptHex, proof) {
|
|
20
|
+
let result = tagged('branch', concat(Uint8Array.of(0), bytes(unhex(scriptHex))));
|
|
21
|
+
if (proof.length > 64)
|
|
22
|
+
throw new Error('proof depth');
|
|
23
|
+
for (const sibling of proof)
|
|
24
|
+
result = node(result, unhex(sibling, 32));
|
|
25
|
+
return hex(result);
|
|
26
|
+
}
|
|
27
|
+
export function assertContractArtifact(a) {
|
|
28
|
+
if (a.schema !== 'lotus/contract-artifact/2' || a.target !== 'P01-P02-P03-candidate-2026-10-14' || !validName(a.contract))
|
|
29
|
+
throw new Error('unsupported artifact');
|
|
30
|
+
if (a.kind !== undefined && a.kind !== 'contract' && a.kind !== 'token')
|
|
31
|
+
throw new Error('unsupported artifact kind');
|
|
32
|
+
if (a.policy.treeRecipe !== 'sorted-leaves-largest-power-split-v1' || a.policy.branches.length !== 1 || a.policy.branches[0] !== a.policy.root || !equal(a.policy.paths, [[0]]))
|
|
33
|
+
throw new Error('unsupported policy');
|
|
34
|
+
unhex(a.policy.root, 32);
|
|
35
|
+
if (!Array.isArray(a.constructor) || !Array.isArray(a.bindings) || a.constructor.length !== a.bindings.length)
|
|
36
|
+
throw new Error('constructor/binding mismatch');
|
|
37
|
+
if (new Set(a.constructor.map(x => x.name)).size !== a.constructor.length)
|
|
38
|
+
throw new Error('duplicate constructor names');
|
|
39
|
+
for (let i = 0; i < a.constructor.length; i++) {
|
|
40
|
+
const declaration = a.constructor[i], binding = a.bindings[i];
|
|
41
|
+
if (!validName(declaration.name) || !validType(declaration.type) || binding.name !== declaration.name || binding.type !== declaration.type)
|
|
42
|
+
throw new Error('constructor/binding mismatch');
|
|
43
|
+
if (binding.type === 'Bool') {
|
|
44
|
+
if (typeof binding.value !== 'boolean')
|
|
45
|
+
throw new Error('noncanonical Bool binding');
|
|
46
|
+
}
|
|
47
|
+
else if (binding.type === 'Int' || binding.type === 'Amount') {
|
|
48
|
+
if (typeof binding.value !== 'string' || !/^(0|-?[1-9][0-9]*)$/.test(binding.value))
|
|
49
|
+
throw new Error('noncanonical Int binding');
|
|
50
|
+
encodeCallValue('Int', BigInt(binding.value));
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
if (typeof binding.value !== 'string')
|
|
54
|
+
throw new Error('noncanonical byte binding');
|
|
55
|
+
const raw = unhex(binding.value);
|
|
56
|
+
if (binding.type === 'Signature') {
|
|
57
|
+
if (raw.length !== 64 && !(raw.length === 65 && (raw[64] === 1 || raw[64] === 2)))
|
|
58
|
+
throw new Error('noncanonical Signature binding');
|
|
59
|
+
}
|
|
60
|
+
else
|
|
61
|
+
encodeCallValue(binding.type, raw);
|
|
62
|
+
if (binding.type === 'PublicKey')
|
|
63
|
+
try {
|
|
64
|
+
schnorr.utils.lift_x(BigInt(`0x${binding.value}`));
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
throw new Error('PublicKey is not a BIP340 x-only curve point');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (!Array.isArray(a.methods) || !a.methods.length || a.methods.length > 16 || new Set(a.methods.map(m => m.name)).size !== a.methods.length)
|
|
72
|
+
throw new Error('invalid methods');
|
|
73
|
+
const leaves = [];
|
|
74
|
+
for (const m of a.methods) {
|
|
75
|
+
if (!validName(m.name) || (m.invocation !== undefined && m.invocation !== 'spend' && m.invocation !== 'mint') || !Array.isArray(m.args) || new Set(m.args.map(x => x.name)).size !== m.args.length || m.args.some(x => !validName(x.name) || !validType(x.type)))
|
|
76
|
+
throw new Error('invalid method arguments');
|
|
77
|
+
if (a.kind === 'token') {
|
|
78
|
+
if (m.invocation !== 'mint' || !validName(m.mintAmountParam) || m.args.some(x => x.name === m.mintAmountParam))
|
|
79
|
+
throw new Error('invalid mint amount metadata');
|
|
80
|
+
}
|
|
81
|
+
else if (m.invocation === 'mint' || m.mintAmountParam !== undefined)
|
|
82
|
+
throw new Error('mint metadata on spend artifact');
|
|
83
|
+
const script = unhex(m.scriptHex);
|
|
84
|
+
if (!script.length || script.length > 8192)
|
|
85
|
+
throw new Error('script width');
|
|
86
|
+
const leaf = tagged('branch', concat(Uint8Array.of(0), bytes(script)));
|
|
87
|
+
if (m.leaf !== hex(leaf) || methodRoot(m.scriptHex, m.proof) !== m.root || m.root !== a.policy.root)
|
|
88
|
+
throw new Error('method proof or root mismatch');
|
|
89
|
+
leaves.push(leaf);
|
|
90
|
+
}
|
|
91
|
+
const ordered = leaves.sort((a, b) => { for (let i = 31; i >= 0; i--)
|
|
92
|
+
if (a[i] !== b[i])
|
|
93
|
+
return a[i] - b[i]; return 0; });
|
|
94
|
+
if (new Set(ordered.map(hex)).size !== ordered.length)
|
|
95
|
+
throw new Error('duplicate method leaf');
|
|
96
|
+
function tree(items) {
|
|
97
|
+
if (items.length === 1)
|
|
98
|
+
return items[0];
|
|
99
|
+
let k = 1;
|
|
100
|
+
while (k * 2 < items.length)
|
|
101
|
+
k *= 2;
|
|
102
|
+
return node(tree(items.slice(0, k)), tree(items.slice(k)));
|
|
103
|
+
}
|
|
104
|
+
if (hex(tree(ordered)) !== a.policy.root)
|
|
105
|
+
throw new Error('method tree recipe mismatch');
|
|
106
|
+
authenticated(a);
|
|
107
|
+
}
|
|
108
|
+
// Recompiling is the only check that ties the ABI and the displayed bindings to the
|
|
109
|
+
// scripts. Results are cached by the artifact's exact JSON, so a later edit is re-checked.
|
|
110
|
+
const verified = new Set();
|
|
111
|
+
function authenticated(a) {
|
|
112
|
+
const text = JSON.stringify(a);
|
|
113
|
+
if (verified.has(text))
|
|
114
|
+
return;
|
|
115
|
+
verifyArtifactSource(a);
|
|
116
|
+
if (verified.size >= 256)
|
|
117
|
+
verified.clear();
|
|
118
|
+
verified.add(text);
|
|
119
|
+
}
|
|
120
|
+
function methodOf(a, name) {
|
|
121
|
+
assertContractArtifact(a);
|
|
122
|
+
const m = a.methods.find(x => x.name === name);
|
|
123
|
+
if (!m)
|
|
124
|
+
throw new Error('unknown method');
|
|
125
|
+
if (a.kind === 'token' || m.invocation === 'mint')
|
|
126
|
+
throw new Error('mint artifact requires transaction runtime');
|
|
127
|
+
const leaf = hex(tagged('branch', concat(Uint8Array.of(0), bytes(unhex(m.scriptHex)))));
|
|
128
|
+
if (m.leaf !== leaf || methodRoot(m.scriptHex, m.proof) !== m.root || m.root !== a.policy.root)
|
|
129
|
+
throw new Error('method proof or root mismatch');
|
|
130
|
+
if (new Set(m.args.map(x => x.name)).size !== m.args.length)
|
|
131
|
+
throw new Error('duplicate argument names');
|
|
132
|
+
return m;
|
|
133
|
+
}
|
|
134
|
+
function int128(n) {
|
|
135
|
+
if (typeof n !== 'bigint' || n < -(1n << 127n) || n >= (1n << 127n))
|
|
136
|
+
throw new Error('int128 range');
|
|
137
|
+
return uint(n < 0n ? (1n << 128n) + n : n, 16);
|
|
138
|
+
}
|
|
139
|
+
export function encodeCallValue(type, value) {
|
|
140
|
+
if (type === 'Signature') {
|
|
141
|
+
if (!(value instanceof Uint8Array) || value.length !== 64)
|
|
142
|
+
throw new Error('FULL signature must be 64 bytes');
|
|
143
|
+
return Uint8Array.from(value);
|
|
144
|
+
}
|
|
145
|
+
if (type === 'Int' || type === 'Amount')
|
|
146
|
+
return int128(value);
|
|
147
|
+
if (type === 'Bool') {
|
|
148
|
+
if (typeof value !== 'boolean')
|
|
149
|
+
throw new Error('Bool required');
|
|
150
|
+
return int128(value ? 1n : 0n);
|
|
151
|
+
}
|
|
152
|
+
const fixed = ['PublicKey', 'Bytes32', 'TokenId', 'TxId', 'StateRoot', 'ChainId', 'SigHash', 'BranchRoot', 'MethodLeafHash', 'ContractRootHash'].includes(type) ? 32 : undefined;
|
|
153
|
+
const bounded = /^Bytes\(([0-9]+)\)$/.exec(type)?.[1];
|
|
154
|
+
if (!(value instanceof Uint8Array))
|
|
155
|
+
throw new Error('byte value required');
|
|
156
|
+
if (fixed !== undefined && value.length !== Number(fixed))
|
|
157
|
+
throw new Error(`${type} length`);
|
|
158
|
+
if (bounded !== undefined && value.length > Number(bounded))
|
|
159
|
+
throw new Error(`${type} length`);
|
|
160
|
+
if (type !== 'Bytes' && fixed === undefined && bounded === undefined)
|
|
161
|
+
throw new Error(`unsupported argument type ${type}`);
|
|
162
|
+
if (value.length > 8192)
|
|
163
|
+
throw new Error('argument too large');
|
|
164
|
+
return Uint8Array.from(value);
|
|
165
|
+
}
|
|
166
|
+
function indexedRoot(leaves) {
|
|
167
|
+
if (!leaves.length)
|
|
168
|
+
return tagged('merkleidx', Uint8Array.of(2));
|
|
169
|
+
let nodes = leaves;
|
|
170
|
+
let level = 0;
|
|
171
|
+
while (nodes.length > 1) {
|
|
172
|
+
if (nodes.length & 1)
|
|
173
|
+
nodes = [...nodes, new Uint8Array(32)];
|
|
174
|
+
const next = [];
|
|
175
|
+
for (let i = 0; i < nodes.length; i += 2)
|
|
176
|
+
next.push(tagged('merkleidx', concat(Uint8Array.of(1), uint(BigInt(level), 2), nodes[i], nodes[i + 1])));
|
|
177
|
+
nodes = next;
|
|
178
|
+
level++;
|
|
179
|
+
}
|
|
180
|
+
return nodes[0];
|
|
181
|
+
}
|
|
182
|
+
function core(c, m) {
|
|
183
|
+
return concat(unhex(c.prevTxid, 32), u32(c.prevIndex), u32(c.sequence), Uint8Array.of(1), cs(0), cs(1), bytes(unhex(m.scriptHex)), cs(m.proof.length), ...m.proof.map(x => unhex(x, 32)));
|
|
184
|
+
}
|
|
185
|
+
function header(c) { return concat(u32(7), uint(c.lock ?? 0n, 8), uint(1n, 2), uint(BigInt(c.outputs.length), 2)); }
|
|
186
|
+
function full(c, m, values) { return concat(core(c, m), cs(values.length), ...values.map(bytes)); }
|
|
187
|
+
function hashes(c, m, values) {
|
|
188
|
+
const h = header(c);
|
|
189
|
+
const outputBytes = c.outputs.map(encodeOutput);
|
|
190
|
+
const outRoot = indexedRoot(outputBytes.map(x => tagged('output', bytes(x))));
|
|
191
|
+
const id = tagged('txid', concat(unhex(c.chainId, 32), h, indexedRoot([tagged('inputcore', core(c, m))]), outRoot));
|
|
192
|
+
const th = tagged('txhash', concat(unhex(c.chainId, 32), h, indexedRoot([tagged('inputfull', full(c, m, values))]), outRoot));
|
|
193
|
+
const coinRoot = indexedRoot([tagged('coinentry', bytes(encodeOutput(c.coin)))]);
|
|
194
|
+
const selector = concat(Uint8Array.of(1), u32(0), u32(0), unhex(m.leaf, 32));
|
|
195
|
+
const message = tagged('sighash', concat(unhex(c.chainId, 32), Uint8Array.of(0), id, coinRoot, selector));
|
|
196
|
+
return { txid: hex(id), txhash: hex(th), message: hex(message), wire: concat(h, full(c, m, values), ...outputBytes) };
|
|
197
|
+
}
|
|
198
|
+
function encodedArgs(m, args, signatures) {
|
|
199
|
+
if (Object.keys(args).sort().join(',') !== m.args.map(x => x.name).sort().join(','))
|
|
200
|
+
throw new Error('argument names mismatch');
|
|
201
|
+
return m.args.map(x => {
|
|
202
|
+
if (x.type === 'Signature') {
|
|
203
|
+
if (args[x.name] !== null)
|
|
204
|
+
throw new Error('Signature argument must be an empty signing slot');
|
|
205
|
+
return signatures ? encodeCallValue('Signature', signatures[x.name] ?? null) : new Uint8Array();
|
|
206
|
+
}
|
|
207
|
+
return encodeCallValue(x.type, args[x.name] ?? null);
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
export function prepareContractCall(a, methodName, c, args) {
|
|
211
|
+
const m = methodOf(a, methodName);
|
|
212
|
+
if (c.profile !== a.target)
|
|
213
|
+
throw new Error('unsupported profile');
|
|
214
|
+
unhex(c.chainId, 32);
|
|
215
|
+
unhex(c.prevTxid, 32);
|
|
216
|
+
u32(c.prevIndex);
|
|
217
|
+
u32(c.sequence);
|
|
218
|
+
const lock = c.lock ?? 0n;
|
|
219
|
+
uint(lock, 8);
|
|
220
|
+
if ((lock & 255n) > 2n || ((lock & 255n) === 0n && lock !== 0n))
|
|
221
|
+
throw new Error('invalid P01 lock encoding');
|
|
222
|
+
if (c.sequence !== 0xffffffff && (c.sequence & ~0x40ffff) !== 0)
|
|
223
|
+
throw new Error('invalid P01 sequence bits');
|
|
224
|
+
if (!equal(c.coin.paths, [[0]]) || !equal(c.coin.branches, [a.policy.root]))
|
|
225
|
+
throw new Error('resolved coin policy mismatch');
|
|
226
|
+
if (c.outputs.length > 256)
|
|
227
|
+
throw new Error('too many outputs: C06 caps outputs at 256');
|
|
228
|
+
assertMoneyRange(c.coin.value, 'coin value');
|
|
229
|
+
c.outputs.forEach((o, j) => assertMoneyRange(o.value, `output ${j} value`));
|
|
230
|
+
const encoded = encodedArgs(m, args);
|
|
231
|
+
const amount = c.outputs.reduce((n, o) => n + o.value, 0n);
|
|
232
|
+
if (amount > c.coin.value)
|
|
233
|
+
throw new Error('negative fee');
|
|
234
|
+
const result = hashes(c, m, encoded);
|
|
235
|
+
const requests = m.args.filter(x => x.type === 'Signature').map(x => ({ argument: x.name, mode: 0, digest: result.message, chainId: c.chainId,
|
|
236
|
+
txid: result.txid, inputIndex: 0, branchIndex: 0, leaf: m.leaf, feeAtoms: c.coin.value - amount }));
|
|
237
|
+
return { artifact: a, methodName, context: c, arguments: args, unsignedWire: result.wire, txid: result.txid, requests };
|
|
238
|
+
}
|
|
239
|
+
export function finalizeContractCall(plan, signatures) {
|
|
240
|
+
const fresh = prepareContractCall(plan.artifact, plan.methodName, plan.context, plan.arguments);
|
|
241
|
+
if (fresh.txid !== plan.txid || hex(fresh.unsignedWire) !== hex(plan.unsignedWire) || fresh.requests.length !== plan.requests.length ||
|
|
242
|
+
fresh.requests.some((r, i) => r.argument !== plan.requests[i]?.argument || r.digest !== plan.requests[i]?.digest || r.feeAtoms !== plan.requests[i]?.feeAtoms))
|
|
243
|
+
throw new Error('stale signing plan');
|
|
244
|
+
if (Object.keys(signatures).sort().join(',') !== fresh.requests.map(x => x.argument).sort().join(','))
|
|
245
|
+
throw new Error('signature slots mismatch');
|
|
246
|
+
const result = hashes(plan.context, methodOf(plan.artifact, plan.methodName), encodedArgs(methodOf(plan.artifact, plan.methodName), plan.arguments, signatures));
|
|
247
|
+
return { wire: result.wire, txid: result.txid, txhash: result.txhash,
|
|
248
|
+
stages: { assembly: 'passed', framing: 'passed', signature: 'unavailable', invocation: 'unavailable', contextual: 'unavailable', block: 'unavailable' } };
|
|
249
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { compilePayment } from './compiler.js';
|
|
5
|
+
import { generatePython, generateTypeScript } from './bindings.js';
|
|
6
|
+
function main(args) {
|
|
7
|
+
if (args.length !== 3)
|
|
8
|
+
throw new Error('usage: lotus-compile SOURCE OWNER_XONLY_HEX OUTPUT_DIR');
|
|
9
|
+
const [sourceFile, owner, out] = args;
|
|
10
|
+
const artifact = compilePayment(readFileSync(sourceFile, 'utf8'), owner);
|
|
11
|
+
mkdirSync(out, { recursive: true });
|
|
12
|
+
writeFileSync(join(out, 'artifact.json'), JSON.stringify(artifact, null, 2) + '\n');
|
|
13
|
+
writeFileSync(join(out, `${artifact.contract}.ts`), generateTypeScript(artifact));
|
|
14
|
+
writeFileSync(join(out, `${artifact.contract}.py`), generatePython(artifact));
|
|
15
|
+
}
|
|
16
|
+
try {
|
|
17
|
+
main(process.argv.slice(2));
|
|
18
|
+
}
|
|
19
|
+
catch (err) {
|
|
20
|
+
process.stderr.write(`${err.message}\n`);
|
|
21
|
+
process.exitCode = 1;
|
|
22
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* UTF-8 (schema 2) or UTF-16 (schema 1) offsets; `end` is exclusive. `module` is set
|
|
3
|
+
* only by package builds and is part of emitted schema-2 source maps. `file` is the
|
|
4
|
+
* internal diagnostic identity of the source file (project-relative path or the
|
|
5
|
+
* single-file source name); it never appears in artifacts (see `artifactSpan`).
|
|
6
|
+
*/
|
|
7
|
+
export type Span = {
|
|
8
|
+
start: number;
|
|
9
|
+
end: number;
|
|
10
|
+
module?: string;
|
|
11
|
+
file?: string;
|
|
12
|
+
};
|
|
13
|
+
/** The artifact/trace form of a span: exactly `{ start, end[, module] }`, in that key order. */
|
|
14
|
+
export declare function artifactSpan(span: Span): Span;
|
|
15
|
+
export type PaymentAst = {
|
|
16
|
+
kind: 'Payment';
|
|
17
|
+
name: string;
|
|
18
|
+
ownerName: string;
|
|
19
|
+
signatureName: string;
|
|
20
|
+
span: Span;
|
|
21
|
+
ownerSpan: Span;
|
|
22
|
+
checkSpan: Span;
|
|
23
|
+
};
|
|
24
|
+
export type PaymentIr = {
|
|
25
|
+
kind: 'checksig';
|
|
26
|
+
signature: 'Signature';
|
|
27
|
+
publicKey: 'PublicKey';
|
|
28
|
+
stackBefore: ['Signature'];
|
|
29
|
+
stackAfter: ['Boolean'];
|
|
30
|
+
span: Span;
|
|
31
|
+
};
|
|
32
|
+
export type PaymentArtifact = {
|
|
33
|
+
schema: 'lotus/payment-artifact/1';
|
|
34
|
+
target: 'P01-P02-P03-candidate-2026-10-14';
|
|
35
|
+
contract: string;
|
|
36
|
+
constructor: {
|
|
37
|
+
name: string;
|
|
38
|
+
type: 'PublicKey';
|
|
39
|
+
bytes: 32;
|
|
40
|
+
}[];
|
|
41
|
+
methods: {
|
|
42
|
+
name: 'spend';
|
|
43
|
+
args: {
|
|
44
|
+
name: string;
|
|
45
|
+
type: 'Signature';
|
|
46
|
+
bytes: [64, 64];
|
|
47
|
+
}[];
|
|
48
|
+
path: [0];
|
|
49
|
+
}[];
|
|
50
|
+
scriptHex: string;
|
|
51
|
+
policy: {
|
|
52
|
+
branches: [string];
|
|
53
|
+
paths: [[0]];
|
|
54
|
+
leaf: string;
|
|
55
|
+
};
|
|
56
|
+
sourceMap: {
|
|
57
|
+
source: Span;
|
|
58
|
+
byteStart: number;
|
|
59
|
+
byteEnd: number;
|
|
60
|
+
op: string;
|
|
61
|
+
}[];
|
|
62
|
+
staticResources: {
|
|
63
|
+
scriptBytes: number;
|
|
64
|
+
opcodes: 2;
|
|
65
|
+
maxStackItems: 2;
|
|
66
|
+
dynamicSignatureCheck: true;
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
export declare function hex(bytes: Uint8Array): string;
|
|
70
|
+
export declare function unhex(value: string, length?: number): Uint8Array;
|
|
71
|
+
export declare function concat(...parts: Uint8Array[]): Uint8Array;
|
|
72
|
+
export declare function cs(n: number): Uint8Array;
|
|
73
|
+
export declare function uint(n: bigint, bytes: number): Uint8Array;
|
|
74
|
+
export declare function bytes(x: Uint8Array): Uint8Array;
|
|
75
|
+
export declare function tagged(name: string, payload: Uint8Array): Uint8Array;
|
|
76
|
+
export declare function parsePayment(source: string): PaymentAst;
|
|
77
|
+
export declare function lowerPayment(ast: PaymentAst): PaymentIr;
|
|
78
|
+
export declare function compilePayment(source: string, ownerHex: string): PaymentArtifact;
|
|
79
|
+
export declare const PAYMENT_SOURCE = "contract Payment<owner: PublicKey> { function spend(signature: Signature) { require(checksig(signature, owner)); } }";
|
package/dist/compiler.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { blake3 } from '@noble/hashes/blake3';
|
|
2
|
+
import { schnorr } from '@noble/curves/secp256k1';
|
|
3
|
+
import { assertPortableName } from './names.js';
|
|
4
|
+
/** The artifact/trace form of a span: exactly `{ start, end[, module] }`, in that key order. */
|
|
5
|
+
export function artifactSpan(span) {
|
|
6
|
+
return span.module !== undefined ? { start: span.start, end: span.end, module: span.module } : { start: span.start, end: span.end };
|
|
7
|
+
}
|
|
8
|
+
export function hex(bytes) { return Buffer.from(bytes).toString('hex'); }
|
|
9
|
+
export function unhex(value, length) {
|
|
10
|
+
if (!/^(?:[0-9a-f]{2})*$/.test(value) || (length !== undefined && value.length !== length * 2))
|
|
11
|
+
throw new Error(`expected lowercase hex${length === undefined ? '' : ` of ${length} bytes`}`);
|
|
12
|
+
return Uint8Array.from(Buffer.from(value, 'hex'));
|
|
13
|
+
}
|
|
14
|
+
export function concat(...parts) { return Uint8Array.from(Buffer.concat(parts)); }
|
|
15
|
+
export function cs(n) {
|
|
16
|
+
if (!Number.isSafeInteger(n) || n < 0)
|
|
17
|
+
throw new Error('invalid CompactSize');
|
|
18
|
+
if (n < 253)
|
|
19
|
+
return Uint8Array.of(n);
|
|
20
|
+
if (n <= 0xffff)
|
|
21
|
+
return Uint8Array.of(253, n & 255, n >> 8);
|
|
22
|
+
if (n <= 0xffffffff)
|
|
23
|
+
return concat(Uint8Array.of(254), uint(BigInt(n), 4));
|
|
24
|
+
return concat(Uint8Array.of(255), uint(BigInt(n), 8));
|
|
25
|
+
}
|
|
26
|
+
export function uint(n, bytes) {
|
|
27
|
+
if (typeof n !== 'bigint' || n < 0n || n >= (1n << BigInt(bytes * 8)))
|
|
28
|
+
throw new Error(`u${bytes * 8} range`);
|
|
29
|
+
const result = new Uint8Array(bytes);
|
|
30
|
+
for (let i = 0; i < bytes; i++) {
|
|
31
|
+
result[i] = Number(n & 255n);
|
|
32
|
+
n >>= 8n;
|
|
33
|
+
}
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
36
|
+
export function bytes(x) { return concat(cs(x.length), x); }
|
|
37
|
+
export function tagged(name, payload) { return blake3(concat(new TextEncoder().encode(`Lotus/v2/${name}\0`), payload)); }
|
|
38
|
+
function tokenize(source) {
|
|
39
|
+
const out = [];
|
|
40
|
+
const re = /\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/|[A-Za-z_][A-Za-z_0-9]*|[<>{}():;,]/gy;
|
|
41
|
+
let i = 0;
|
|
42
|
+
while (i < source.length) {
|
|
43
|
+
re.lastIndex = i;
|
|
44
|
+
const m = re.exec(source);
|
|
45
|
+
if (!m)
|
|
46
|
+
throw new Error(`unsupported character at offset ${i}`);
|
|
47
|
+
if (!/^\s|^\//.test(m[0]))
|
|
48
|
+
out.push({ text: m[0], span: { start: i, end: re.lastIndex } });
|
|
49
|
+
i = re.lastIndex;
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
export function parsePayment(source) {
|
|
54
|
+
const t = tokenize(source);
|
|
55
|
+
let i = 0;
|
|
56
|
+
function take(expected) {
|
|
57
|
+
const x = t[i++];
|
|
58
|
+
if (!x || (expected !== undefined && x.text !== expected))
|
|
59
|
+
throw new Error(`expected ${expected ?? 'identifier'} at offset ${x?.span.start ?? source.length}`);
|
|
60
|
+
return x;
|
|
61
|
+
}
|
|
62
|
+
function ident() { const x = take(); if (!/^[A-Za-z_][A-Za-z_0-9]*$/.test(x.text))
|
|
63
|
+
throw new Error(`expected identifier at offset ${x.span.start}`); return x; }
|
|
64
|
+
const start = take('contract').span.start;
|
|
65
|
+
const name = ident();
|
|
66
|
+
take('<');
|
|
67
|
+
const owner = ident();
|
|
68
|
+
take(':');
|
|
69
|
+
take('PublicKey');
|
|
70
|
+
take('>');
|
|
71
|
+
take('{');
|
|
72
|
+
take('function');
|
|
73
|
+
take('spend');
|
|
74
|
+
take('(');
|
|
75
|
+
const signature = ident();
|
|
76
|
+
take(':');
|
|
77
|
+
take('Signature');
|
|
78
|
+
take(')');
|
|
79
|
+
take('{');
|
|
80
|
+
const checkStart = take('require').span.start;
|
|
81
|
+
take('(');
|
|
82
|
+
take('checksig');
|
|
83
|
+
take('(');
|
|
84
|
+
const sigUse = ident();
|
|
85
|
+
take(',');
|
|
86
|
+
const ownerUse = ident();
|
|
87
|
+
take(')');
|
|
88
|
+
take(')');
|
|
89
|
+
take(';');
|
|
90
|
+
take('}');
|
|
91
|
+
const end = take('}').span.end;
|
|
92
|
+
if (i !== t.length)
|
|
93
|
+
throw new Error(`unsupported syntax at offset ${t[i].span.start}`);
|
|
94
|
+
if (sigUse.text !== signature.text || ownerUse.text !== owner.text)
|
|
95
|
+
throw new Error(`typed name mismatch at offset ${sigUse.span.start}`);
|
|
96
|
+
for (const value of [name.text, owner.text, signature.text])
|
|
97
|
+
assertPortableName(value);
|
|
98
|
+
if (owner.text === signature.text)
|
|
99
|
+
throw new Error('method parameter shadows constructor');
|
|
100
|
+
return { kind: 'Payment', name: name.text, ownerName: owner.text, signatureName: signature.text, span: { start, end }, ownerSpan: ownerUse.span, checkSpan: { start: checkStart, end: t[i - 3].span.end } };
|
|
101
|
+
}
|
|
102
|
+
export function lowerPayment(ast) { return { kind: 'checksig', signature: 'Signature', publicKey: 'PublicKey', stackBefore: ['Signature'], stackAfter: ['Boolean'], span: ast.checkSpan }; }
|
|
103
|
+
export function compilePayment(source, ownerHex) {
|
|
104
|
+
const ast = parsePayment(source);
|
|
105
|
+
lowerPayment(ast);
|
|
106
|
+
const owner = unhex(ownerHex, 32);
|
|
107
|
+
try {
|
|
108
|
+
schnorr.utils.lift_x(BigInt(`0x${ownerHex}`));
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
throw new Error('PublicKey is not a BIP340 x-only curve point');
|
|
112
|
+
}
|
|
113
|
+
// P03 PUSH_32 (0x20), then CHECKSIG (0xbb). P02 one-leaf branch root.
|
|
114
|
+
const script = concat(Uint8Array.of(0x20), owner, Uint8Array.of(0xbb));
|
|
115
|
+
const leaf = tagged('branch', concat(Uint8Array.of(0), bytes(script)));
|
|
116
|
+
return {
|
|
117
|
+
schema: 'lotus/payment-artifact/1', target: 'P01-P02-P03-candidate-2026-10-14', contract: ast.name,
|
|
118
|
+
constructor: [{ name: ast.ownerName, type: 'PublicKey', bytes: 32 }],
|
|
119
|
+
methods: [{ name: 'spend', args: [{ name: ast.signatureName, type: 'Signature', bytes: [64, 64] }], path: [0] }],
|
|
120
|
+
scriptHex: hex(script), policy: { branches: [hex(leaf)], paths: [[0]], leaf: hex(leaf) },
|
|
121
|
+
sourceMap: [{ source: ast.ownerSpan, byteStart: 0, byteEnd: 33, op: 'PUSH_32' }, { source: ast.checkSpan, byteStart: 33, byteEnd: 34, op: 'CHECKSIG' }],
|
|
122
|
+
staticResources: { scriptBytes: 34, opcodes: 2, maxStackItems: 2, dynamicSignatureCheck: true },
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
export const PAYMENT_SOURCE = `contract Payment<owner: PublicKey> { function spend(signature: Signature) { require(checksig(signature, owner)); } }`;
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structured compiler diagnostics, source positions and clang/rustc-style rendering.
|
|
3
|
+
*
|
|
4
|
+
* Build-time only. Offsets are UTF-8 byte offsets into the exact source text of a
|
|
5
|
+
* file (schema-2 convention). Reported `line:column` positions are 1-based; the
|
|
6
|
+
* column counts **Unicode scalar values** (code points) from the start of the line,
|
|
7
|
+
* so `é` (2 bytes) or `𝔸` (4 bytes) each advance the column by one and a tab counts
|
|
8
|
+
* as one column. The JSON form additionally carries the raw byte offsets. Excerpts
|
|
9
|
+
* expand tabs to the next multiple of 4 display cells and treat East Asian wide
|
|
10
|
+
* characters as two cells and combining marks as zero, so carets line up in a
|
|
11
|
+
* monospace terminal.
|
|
12
|
+
*/
|
|
13
|
+
import type { Span } from './compiler.js';
|
|
14
|
+
export type Severity = 'error' | 'warning' | 'note';
|
|
15
|
+
/** A file plus an optional UTF-8 byte range in it. A missing span marks a file-level diagnostic. */
|
|
16
|
+
export type Location = {
|
|
17
|
+
file: string;
|
|
18
|
+
span?: Span;
|
|
19
|
+
};
|
|
20
|
+
export type Label = {
|
|
21
|
+
file?: string;
|
|
22
|
+
span: Span;
|
|
23
|
+
message: string;
|
|
24
|
+
primary?: boolean;
|
|
25
|
+
};
|
|
26
|
+
export type Related = {
|
|
27
|
+
file: string;
|
|
28
|
+
span?: Span;
|
|
29
|
+
message: string;
|
|
30
|
+
};
|
|
31
|
+
export type Diagnostic = {
|
|
32
|
+
severity: Severity;
|
|
33
|
+
/** Stable code, `E` (error) or `W` (lint warning) + four digits; see DIAGNOSTIC_CODES and docs. */
|
|
34
|
+
code: string;
|
|
35
|
+
message: string;
|
|
36
|
+
/** Absent only for global diagnostics (e.g. malformed compile options). */
|
|
37
|
+
primary?: Location;
|
|
38
|
+
labels: Label[];
|
|
39
|
+
notes: string[];
|
|
40
|
+
help?: string;
|
|
41
|
+
related: Related[];
|
|
42
|
+
};
|
|
43
|
+
/** Maximum diagnostics reported by one compile before recovery stops. */
|
|
44
|
+
export declare const MAX_DIAGNOSTICS = 20;
|
|
45
|
+
/** Stable codes. Messages may be refined; codes are not reused. */
|
|
46
|
+
export declare const DIAGNOSTIC_CODES: Record<string, string>;
|
|
47
|
+
export type Position = {
|
|
48
|
+
line: number;
|
|
49
|
+
column: number;
|
|
50
|
+
byteColumn: number;
|
|
51
|
+
};
|
|
52
|
+
/** One source file: text, UTF-8 bytes and line starts (byte offsets). */
|
|
53
|
+
export declare class SourceFile {
|
|
54
|
+
readonly name: string;
|
|
55
|
+
readonly text: string;
|
|
56
|
+
readonly bytes: Uint8Array;
|
|
57
|
+
readonly lineStarts: number[];
|
|
58
|
+
constructor(name: string, text: string);
|
|
59
|
+
/** 0-based line index containing byte offset. */
|
|
60
|
+
lineIndex(offset: number): number;
|
|
61
|
+
/** Line text without its terminator (`\n` or `\r\n`). */
|
|
62
|
+
lineText(index: number): string;
|
|
63
|
+
get lineCount(): number;
|
|
64
|
+
/** 1-based line and Unicode-scalar column of a byte offset (clamped into the file). */
|
|
65
|
+
position(offset: number): Position;
|
|
66
|
+
}
|
|
67
|
+
/** Source registry keyed by the file names used in diagnostics. */
|
|
68
|
+
export declare class SourceManager {
|
|
69
|
+
private readonly files;
|
|
70
|
+
add(name: string, text: string): SourceFile;
|
|
71
|
+
get(name: string | undefined): SourceFile | undefined;
|
|
72
|
+
merge(other: SourceManager | undefined): this;
|
|
73
|
+
}
|
|
74
|
+
export type DiagnosticExtra = {
|
|
75
|
+
labels?: Label[];
|
|
76
|
+
notes?: string[];
|
|
77
|
+
help?: string;
|
|
78
|
+
related?: Related[];
|
|
79
|
+
severity?: Severity;
|
|
80
|
+
};
|
|
81
|
+
export declare function diagnostic(code: string, message: string, primary: Location | undefined, extra?: DiagnosticExtra): Diagnostic;
|
|
82
|
+
/** Location of a span, taking the file from the span's own identity when present. */
|
|
83
|
+
export declare function at(span: Span | undefined, fallbackFile?: string): Location;
|
|
84
|
+
/** Order-preserving de-duplication (same code, primary location and message) and capping. */
|
|
85
|
+
export declare function dedupe(list: Diagnostic[], cap?: number): Diagnostic[];
|
|
86
|
+
/**
|
|
87
|
+
* Error thrown by the compiler APIs. `diagnostics` holds every collected diagnostic
|
|
88
|
+
* (first = the one that stopped compilation); `message` is a one-line
|
|
89
|
+
* `file:line:col: error[CODE]: message` header for the first.
|
|
90
|
+
*/
|
|
91
|
+
export declare class CompileError extends Error {
|
|
92
|
+
readonly diagnostics: Diagnostic[];
|
|
93
|
+
sources: SourceManager;
|
|
94
|
+
constructor(diagnostics: Diagnostic[], sources?: SourceManager);
|
|
95
|
+
get code(): string;
|
|
96
|
+
/** Full rendered text of all diagnostics. */
|
|
97
|
+
render(options?: RenderOptions): string;
|
|
98
|
+
toJSON(): DiagnosticJson[];
|
|
99
|
+
}
|
|
100
|
+
/** Merge diagnostics from CompileErrors (others rethrown as-is by callers). */
|
|
101
|
+
export declare function mergeErrors(errors: CompileError[], sources?: SourceManager): CompileError;
|
|
102
|
+
/**
|
|
103
|
+
* Collects diagnostics for one compile. Recovery may continue until
|
|
104
|
+
* `MAX_DIAGNOSTICS`; the next report then throws, and the first diagnostic is kept.
|
|
105
|
+
* `raise` records one more diagnostic (unless the cap is already full) and stops.
|
|
106
|
+
*/
|
|
107
|
+
export declare class DiagnosticBag {
|
|
108
|
+
readonly sources: SourceManager;
|
|
109
|
+
readonly fallbackFile: string;
|
|
110
|
+
readonly diagnostics: Diagnostic[];
|
|
111
|
+
constructor(sources: SourceManager, fallbackFile?: string);
|
|
112
|
+
report(code: string, message: string, span?: Span, extra?: DiagnosticExtra): void;
|
|
113
|
+
raise(code: string, message: string, span?: Span, extra?: DiagnosticExtra): never;
|
|
114
|
+
finish(): never;
|
|
115
|
+
/** Throw if any diagnostic was recorded and compilation continued. */
|
|
116
|
+
checkpoint(): void;
|
|
117
|
+
}
|
|
118
|
+
export declare function headline(d: Diagnostic, sources?: SourceManager): string;
|
|
119
|
+
export type RenderOptions = {
|
|
120
|
+
color?: boolean;
|
|
121
|
+
};
|
|
122
|
+
/** Whether to colour output for a stream: TTY and NO_COLOR unset (FORCE_COLOR forces). */
|
|
123
|
+
export declare function shouldColor(stream: {
|
|
124
|
+
isTTY?: boolean;
|
|
125
|
+
}, env?: Record<string, string | undefined>): boolean;
|
|
126
|
+
export declare function renderDiagnostics(list: Diagnostic[], sources?: SourceManager, options?: RenderOptions): string;
|
|
127
|
+
export declare function renderDiagnostic(d: Diagnostic, sources?: SourceManager, options?: RenderOptions): string;
|
|
128
|
+
export declare const DIAGNOSTICS_SCHEMA = "lotus/diagnostics/1";
|
|
129
|
+
export type JsonLocation = {
|
|
130
|
+
file: string;
|
|
131
|
+
start?: number;
|
|
132
|
+
end?: number;
|
|
133
|
+
line?: number;
|
|
134
|
+
column?: number;
|
|
135
|
+
endLine?: number;
|
|
136
|
+
endColumn?: number;
|
|
137
|
+
module?: string;
|
|
138
|
+
};
|
|
139
|
+
export type DiagnosticJson = {
|
|
140
|
+
severity: Severity;
|
|
141
|
+
code: string;
|
|
142
|
+
message: string;
|
|
143
|
+
primary: JsonLocation | null;
|
|
144
|
+
labels: (JsonLocation & {
|
|
145
|
+
message: string;
|
|
146
|
+
primary: boolean;
|
|
147
|
+
})[];
|
|
148
|
+
notes: string[];
|
|
149
|
+
help: string | null;
|
|
150
|
+
related: (JsonLocation & {
|
|
151
|
+
message: string;
|
|
152
|
+
})[];
|
|
153
|
+
};
|
|
154
|
+
/** Stable JSON (fixed key order). `column`/`endColumn` are 1-based Unicode-scalar columns; `end` is exclusive. */
|
|
155
|
+
export declare function diagnosticToJson(d: Diagnostic, sources?: SourceManager): DiagnosticJson;
|
|
156
|
+
export declare function diagnosticsJson(list: Diagnostic[], sources?: SourceManager): string;
|
|
157
|
+
/** Levenshtein-based suggestion: closest candidate within distance max(1, len/3). Ties break lexicographically. */
|
|
158
|
+
export declare function suggest(name: string, candidates: Iterable<string>): string | undefined;
|
|
159
|
+
/** Render any thrown value (CompileError or plain Error) as diagnostics text or JSON. */
|
|
160
|
+
export declare function errorDiagnostics(error: unknown, fallbackFile?: string): {
|
|
161
|
+
diagnostics: Diagnostic[];
|
|
162
|
+
sources: SourceManager;
|
|
163
|
+
};
|