@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,231 @@
1
+ /** Parser/validation safety ceilings, not target execution or consensus limits. */
2
+ export const SEMANTIC_IR_LIMITS = Object.freeze({ maxBytes: 8192, maxDepth: 64, maxNodes: 8192, maxArgs: 256 });
3
+ class InvalidSemanticIR extends Error {
4
+ diagnostic;
5
+ constructor(diagnostic) {
6
+ super(diagnostic.message);
7
+ this.diagnostic = diagnostic;
8
+ }
9
+ }
10
+ function record(value) {
11
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
12
+ return false;
13
+ const proto = Object.getPrototypeOf(value);
14
+ return (proto === null || proto === Object.prototype) && Object.getOwnPropertySymbols(value).length === 0
15
+ && Object.values(Object.getOwnPropertyDescriptors(value)).every(descriptor => Object.hasOwn(descriptor, 'value'));
16
+ }
17
+ function validSpan(value) {
18
+ return record(value) && Object.keys(value).every(key => ['start', 'end', 'file'].includes(key))
19
+ && Number.isSafeInteger(value.start) && Number.isSafeInteger(value.end)
20
+ && value.start >= 0 && value.end >= value.start
21
+ && (value.file === undefined || typeof value.file === 'string');
22
+ }
23
+ function copySpan(value) {
24
+ return value.file === undefined ? { start: value.start, end: value.end } : { start: value.start, end: value.end, file: value.file };
25
+ }
26
+ function fail(code, message, value) {
27
+ const span = record(value) && validSpan(value.span) ? copySpan(value.span) : undefined;
28
+ throw new InvalidSemanticIR({ code: `semantic-ir-${code}`, message, ...(span ? { span } : {}) });
29
+ }
30
+ function shape(value, fields, context) {
31
+ if (!record(value))
32
+ fail('shape', `${context} must be a plain object`, value);
33
+ const extra = Object.keys(value).find(key => !fields.includes(key));
34
+ if (extra !== undefined)
35
+ fail('shape', `unsupported ${context} field ${extra}`, value);
36
+ for (const field of fields)
37
+ if (!Object.hasOwn(value, field))
38
+ fail('shape', `${context} is missing ${field}`, value);
39
+ return value;
40
+ }
41
+ function span(value) {
42
+ if (!validSpan(value.span))
43
+ fail('span', 'span requires nonnegative safe UTF-8 byte offsets start <= end and optional file', value);
44
+ return copySpan(value.span);
45
+ }
46
+ function name(value, context, at) {
47
+ if (typeof value !== 'string' || !/^[A-Za-z_][A-Za-z_0-9]*$/.test(value))
48
+ fail('name', `${context} must be an identifier`, at);
49
+ return value;
50
+ }
51
+ function denseArray(value, context) {
52
+ if (Object.getOwnPropertySymbols(value).length || Object.keys(value).some(key => !/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length))
53
+ fail('shape', `${context} must contain only array entries`);
54
+ for (let i = 0; i < value.length; i++) {
55
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(i));
56
+ if (!descriptor || !Object.hasOwn(descriptor, 'value'))
57
+ fail('shape', `${context} must be dense and contain no accessors`);
58
+ }
59
+ }
60
+ function semanticType(value, at) {
61
+ if (!record(value))
62
+ fail('type', 'argument type must be bytes or bool', at);
63
+ if (value.kind === 'bool') {
64
+ shape(value, ['kind'], 'Boolean type');
65
+ return { kind: 'bool' };
66
+ }
67
+ if (value.kind === 'bytes') {
68
+ shape(value, ['kind', 'length'], 'byte type');
69
+ if (!Number.isSafeInteger(value.length) || value.length < 0 || value.length > SEMANTIC_IR_LIMITS.maxBytes)
70
+ fail('type', `exact byte length must be 0..${SEMANTIC_IR_LIMITS.maxBytes}`, at);
71
+ return { kind: 'bytes', length: value.length };
72
+ }
73
+ fail('unsupported', 'only portable bytes and bool types are supported; integers, signatures and reflection require a chain-specific IR', at);
74
+ }
75
+ function sameType(left, right) {
76
+ return left.kind === right.kind && (left.kind !== 'bytes' || right.kind === 'bytes' && left.length === right.length);
77
+ }
78
+ /**
79
+ * Validate imported IR before backend selection. Fail closed on unknown constructs.
80
+ * The returned tree and spans are detached copies; capability occurrences retain
81
+ * source order and are not deduplicated. Equal requires matching exact byte widths
82
+ * (or two Bools); byte padding and Boolean/numeric coercion are never implicit.
83
+ * This checks semantics/shape only, not target support, stack bounds or execution.
84
+ */
85
+ export function validateSemanticProgram(input) {
86
+ const requirements = [];
87
+ const args = new Map();
88
+ const active = new Set();
89
+ let nodes = 0;
90
+ const requireCapability = (capability, at) => {
91
+ requirements.push({ capability, span: copySpan(at) });
92
+ };
93
+ const typed = (type, at) => {
94
+ requireCapability(type.kind, at);
95
+ return type;
96
+ };
97
+ const visit = (value, depth) => {
98
+ if (depth > SEMANTIC_IR_LIMITS.maxDepth)
99
+ fail('limit', `IR nesting exceeds ${SEMANTIC_IR_LIMITS.maxDepth}`, value);
100
+ if (++nodes > SEMANTIC_IR_LIMITS.maxNodes)
101
+ fail('limit', `IR node budget exceeds ${SEMANTIC_IR_LIMITS.maxNodes}`, value);
102
+ if (value !== null && typeof value === 'object') {
103
+ if (active.has(value))
104
+ fail('cycle', 'cyclic IR is unsupported', value);
105
+ active.add(value);
106
+ }
107
+ };
108
+ const expression = (value, depth) => {
109
+ visit(value, depth);
110
+ if (!record(value))
111
+ fail('shape', 'expression must be a plain object', value);
112
+ let node, type;
113
+ const at = span(value);
114
+ switch (value.kind) {
115
+ case 'bytes': {
116
+ shape(value, ['kind', 'hex', 'span'], 'byte constant');
117
+ if (typeof value.hex !== 'string' || value.hex.length > SEMANTIC_IR_LIMITS.maxBytes * 2 || !/^(?:[0-9a-f]{2})*$/.test(value.hex))
118
+ fail('constant', `byte constant must be lowercase even-length hex of at most ${SEMANTIC_IR_LIMITS.maxBytes} bytes`, value);
119
+ node = { kind: 'bytes', hex: value.hex, span: at };
120
+ type = { kind: 'bytes', length: value.hex.length / 2 };
121
+ break;
122
+ }
123
+ case 'bool':
124
+ shape(value, ['kind', 'value', 'span'], 'Boolean constant');
125
+ if (typeof value.value !== 'boolean')
126
+ fail('constant', 'Boolean constant must be true or false', value);
127
+ node = { kind: 'bool', value: value.value, span: at };
128
+ type = { kind: 'bool' };
129
+ break;
130
+ case 'arg': {
131
+ shape(value, ['kind', 'name', 'span'], 'argument reference');
132
+ const arg = name(value.name, 'argument reference', value), found = args.get(arg);
133
+ if (!found)
134
+ fail('argument', `unbound argument ${arg}`, value);
135
+ node = { kind: 'arg', name: arg, span: at };
136
+ type = { ...found };
137
+ break;
138
+ }
139
+ case 'sha256':
140
+ case 'hash256': {
141
+ shape(value, ['kind', 'value', 'span'], 'hash expression');
142
+ const operand = expression(value.value, depth + 1);
143
+ if (operand.type.kind !== 'bytes')
144
+ fail('type', `${value.kind} requires bytes`, value);
145
+ node = { kind: value.kind, value: operand.node, span: at };
146
+ type = { kind: 'bytes', length: 32 };
147
+ requireCapability(value.kind, at);
148
+ break;
149
+ }
150
+ case 'equal': {
151
+ shape(value, ['kind', 'left', 'right', 'span'], 'equality expression');
152
+ const left = expression(value.left, depth + 1), right = expression(value.right, depth + 1);
153
+ if (!sameType(left.type, right.type))
154
+ fail('type', 'equal requires two Bools or byte values of the same exact length', value);
155
+ node = { kind: 'equal', left: left.node, right: right.node, span: at };
156
+ type = { kind: 'bool' };
157
+ requireCapability('byte-equality', at);
158
+ break;
159
+ }
160
+ default: fail('unsupported', `unsupported portable expression ${typeof value.kind === 'string' ? value.kind : typeof value.kind}; chain-specific integer, signature and reflection operations are unavailable`, value);
161
+ }
162
+ typed(type, at);
163
+ active.delete(value);
164
+ return { node, type };
165
+ };
166
+ const statements = (value, depth) => {
167
+ if (!Array.isArray(value))
168
+ fail('shape', 'statement body must be an array');
169
+ if (value.length > SEMANTIC_IR_LIMITS.maxNodes)
170
+ fail('limit', 'statement array exceeds IR node budget');
171
+ denseArray(value, 'statement array');
172
+ return value.map(raw => {
173
+ visit(raw, depth);
174
+ if (!record(raw))
175
+ fail('shape', 'statement must be a plain object', raw);
176
+ const at = span(raw);
177
+ let result;
178
+ if (raw.kind === 'require') {
179
+ shape(raw, ['kind', 'condition', 'span'], 'require statement');
180
+ const condition = expression(raw.condition, depth + 1);
181
+ if (condition.type.kind !== 'bool')
182
+ fail('type', 'require condition must be Bool', raw);
183
+ requireCapability('require', at);
184
+ result = { kind: 'require', condition: condition.node, span: at };
185
+ }
186
+ else if (raw.kind === 'if') {
187
+ shape(raw, ['kind', 'condition', 'then', 'otherwise', 'span'], 'if statement');
188
+ const condition = expression(raw.condition, depth + 1);
189
+ if (condition.type.kind !== 'bool')
190
+ fail('type', 'if condition must be Bool', raw);
191
+ requireCapability('if', at);
192
+ result = { kind: 'if', condition: condition.node, then: statements(raw.then, depth + 1), otherwise: statements(raw.otherwise, depth + 1), span: at };
193
+ }
194
+ else
195
+ fail('unsupported', `unsupported portable statement ${typeof raw.kind === 'string' ? raw.kind : typeof raw.kind}; chain-specific invocation, loops and reflection are unavailable`, raw);
196
+ active.delete(raw);
197
+ return result;
198
+ });
199
+ };
200
+ try {
201
+ const raw = shape(input, ['schema', 'entrypoint', 'args', 'body', 'span'], 'semantic program');
202
+ if (raw.schema !== 'lotus/semantic-ir/1')
203
+ fail('schema', 'unsupported semantic IR schema', raw);
204
+ const at = span(raw), entrypoint = name(raw.entrypoint, 'entrypoint', raw);
205
+ visit(raw, 0);
206
+ if (!Array.isArray(raw.args))
207
+ fail('shape', 'args must be an array', raw);
208
+ if (raw.args.length > SEMANTIC_IR_LIMITS.maxArgs)
209
+ fail('limit', `argument count exceeds ${SEMANTIC_IR_LIMITS.maxArgs}`, raw);
210
+ denseArray(raw.args, 'argument array');
211
+ const declarations = raw.args.map(arg => {
212
+ visit(arg, 1);
213
+ const item = shape(arg, ['name', 'type', 'span'], 'argument declaration'), location = span(item);
214
+ const identifier = name(item.name, 'argument name', item);
215
+ if (args.has(identifier))
216
+ fail('argument', `duplicate argument ${identifier}`, item);
217
+ const type = semanticType(item.type, item);
218
+ args.set(identifier, type);
219
+ typed(type, location);
220
+ active.delete(item);
221
+ return { name: identifier, type, span: location };
222
+ });
223
+ const program = { schema: 'lotus/semantic-ir/1', entrypoint, args: declarations, body: statements(raw.body, 1), span: at };
224
+ return { ok: true, program, requirements };
225
+ }
226
+ catch (error) {
227
+ if (error instanceof InvalidSemanticIR)
228
+ return { ok: false, diagnostics: [error.diagnostic] };
229
+ throw error;
230
+ }
231
+ }
package/dist/std.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { type BoundValue, type ContractArtifact } from './generic.js';
2
+ import type { Diagnostic } from './diagnostics.js';
3
+ export type StandardContractCategory = 'tokens' | 'nft' | 'custody' | 'defi';
4
+ export type StandardContractSpec = {
5
+ readonly id: string;
6
+ readonly contract: string;
7
+ readonly kind: 'contract' | 'token';
8
+ readonly category: StandardContractCategory;
9
+ readonly file: string;
10
+ readonly summary: string;
11
+ readonly walletBadge: string;
12
+ /** Human-readable method action templates for wallet signing prompts. */
13
+ readonly actions: Readonly<Record<string, string>>;
14
+ /** For zero-parameter universal templates, the fixed well-known MAST BranchRoot. */
15
+ readonly universalRoot?: string;
16
+ };
17
+ /** Universal BranchRoot of StandardTransferRules (zero-parameter, zero-freeze, zero-tax). */
18
+ export declare const UNIVERSAL_STANDARD_TRANSFER_RULES_ROOT = "985e7562c70c1577cd7acdd208c0dfa36683860e0ed1931ed77574866389dbdc";
19
+ export declare const STANDARD_CONTRACTS: readonly StandardContractSpec[];
20
+ export declare function getStandardContract(id: string): StandardContractSpec | undefined;
21
+ export declare function readStandardContractSource(id: string): string;
22
+ export declare function compileStandardContract(id: string, bindings?: Record<string, BoundValue>): {
23
+ spec: StandardContractSpec;
24
+ artifact: ContractArtifact;
25
+ warnings: Diagnostic[];
26
+ };
27
+ export declare function identifyStandardTemplate(rootHex: string): StandardContractSpec | undefined;
package/dist/std.js ADDED
@@ -0,0 +1,225 @@
1
+ /**
2
+ * 95/5 Canonical Standard Contract Library for Lotus (`@givelotus/compiler/std`).
3
+ *
4
+ * Pre-distributed, pragma-pinned standard templates with deterministic MAST BranchRoots
5
+ * and human-readable wallet/exchange intent metadata.
6
+ */
7
+ import { readFileSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { compileContract, lintContract } from './generic.js';
11
+ const STD_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', 'std');
12
+ /** Universal BranchRoot of StandardTransferRules (zero-parameter, zero-freeze, zero-tax). */
13
+ export const UNIVERSAL_STANDARD_TRANSFER_RULES_ROOT = '985e7562c70c1577cd7acdd208c0dfa36683860e0ed1931ed77574866389dbdc';
14
+ export const STANDARD_CONTRACTS = Object.freeze([
15
+ // Fungible Tokens
16
+ {
17
+ id: 'std/tokens/standard-transfer-rules',
18
+ contract: 'StandardTransferRules',
19
+ kind: 'contract',
20
+ category: 'tokens',
21
+ file: 'tokens/standard-transfer-rules.lotus',
22
+ summary: 'Universal zero-freeze, zero-blacklist, zero-tax token transfer rules.',
23
+ walletBadge: 'Standard Token · No Freeze Controls (Verified on-chain)',
24
+ actions: { transfer: 'Transfer token while preserving standard no-freeze transfer rules' },
25
+ universalRoot: UNIVERSAL_STANDARD_TRANSFER_RULES_ROOT,
26
+ },
27
+ {
28
+ id: 'std/tokens/fixed-supply-token',
29
+ contract: 'FixedSupplyToken',
30
+ kind: 'token',
31
+ category: 'tokens',
32
+ file: 'tokens/fixed-supply-token.lotus',
33
+ summary: 'One-shot fixed-supply fungible token bound to a single creator seed outpoint.',
34
+ walletBadge: 'Fixed Supply · One-Shot Genesis Mint',
35
+ actions: { issue: 'Mint the full fixed supply once by spending the genesis seed coin' },
36
+ },
37
+ {
38
+ id: 'std/tokens/supply-controller',
39
+ contract: 'SupplyController',
40
+ kind: 'contract',
41
+ category: 'tokens',
42
+ file: 'tokens/capped-supply-token.lotus',
43
+ summary: 'HAS_STATE capped-supply mint controller with irreversible lock_mint.',
44
+ walletBadge: 'Capped Supply Controller',
45
+ actions: {
46
+ mint: 'Authorize minting up to max_supply and advance stateful issued counter',
47
+ lock_mint: 'Permanently lock future token minting (irreversible)',
48
+ },
49
+ },
50
+ {
51
+ id: 'std/tokens/capped-supply-token',
52
+ contract: 'CappedSupplyToken',
53
+ kind: 'token',
54
+ category: 'tokens',
55
+ file: 'tokens/capped-supply-token.lotus',
56
+ summary: 'Capped-supply fungible token gated by a SupplyController authority coin.',
57
+ walletBadge: 'Capped Supply Token',
58
+ actions: { issue: 'Mint new tokens authorized by the SupplyController' },
59
+ },
60
+ {
61
+ id: 'std/tokens/voucher-mint-token',
62
+ contract: 'VoucherMintToken',
63
+ kind: 'token',
64
+ category: 'tokens',
65
+ file: 'tokens/voucher-mint-token.lotus',
66
+ summary: 'Outpoint-bound signed voucher mint token (parallel single-use mint codes).',
67
+ walletBadge: 'Issuer-Authorized Voucher Token',
68
+ actions: { mint_with_voucher: 'Mint tokens using an issuer-signed outpoint-bound voucher' },
69
+ },
70
+ // NFTs & Collections
71
+ {
72
+ id: 'std/nft/unique-nft',
73
+ contract: 'UniqueNFT',
74
+ kind: 'token',
75
+ category: 'nft',
76
+ file: 'nft/unique-nft.lotus',
77
+ summary: 'Unique 1-of-1 NFT with immutable metadata commitment hash.',
78
+ walletBadge: 'Unique 1-of-1 NFT',
79
+ actions: { mint: 'Mint unique 1-of-1 NFT with committed metadata hash' },
80
+ },
81
+ {
82
+ id: 'std/nft/collection-authority',
83
+ contract: 'NFTCollectionAuthority',
84
+ kind: 'contract',
85
+ category: 'nft',
86
+ file: 'nft/nft-collection.lotus',
87
+ summary: 'HAS_STATE bounded NFT collection authority tracking minted item count.',
88
+ walletBadge: 'NFT Collection Authority',
89
+ actions: { mint_next: 'Authorize minting the next NFT in the collection' },
90
+ },
91
+ {
92
+ id: 'std/nft/collection-mint',
93
+ contract: 'NFTCollectionMint',
94
+ kind: 'token',
95
+ category: 'nft',
96
+ file: 'nft/nft-collection.lotus',
97
+ summary: 'NFT collection token mint enforcing value == 1 per item.',
98
+ walletBadge: 'NFT Collection Item',
99
+ actions: { mint_item: 'Mint a single collection NFT (value = 1)' },
100
+ },
101
+ {
102
+ id: 'std/nft/royalty-transfer-rules',
103
+ contract: 'RoyaltyTransferRules',
104
+ kind: 'contract',
105
+ category: 'nft',
106
+ file: 'nft/royalty-transfer-rules.lotus',
107
+ summary: 'Royalty-bearing transfer rules requiring creator royalty output or exemption sig.',
108
+ walletBadge: 'Royalty Transfer Rules (Non-Standard)',
109
+ actions: {
110
+ transfer_with_royalty: 'Transfer token while paying creator royalty in XPI',
111
+ creator_exempt_transfer: 'Transfer token with creator royalty exemption signature',
112
+ },
113
+ },
114
+ // Core Money, Custody & Escrow
115
+ {
116
+ id: 'std/custody/single-owner-wallet',
117
+ contract: 'SingleOwnerWallet',
118
+ kind: 'contract',
119
+ category: 'custody',
120
+ file: 'custody/single-owner-wallet.lotus',
121
+ summary: 'Standard single-key BIP-340 Schnorr wallet branch.',
122
+ walletBadge: 'Single-Owner Wallet',
123
+ actions: { spend: 'Spend coins with owner signature' },
124
+ },
125
+ {
126
+ id: 'std/custody/multisig-2of3',
127
+ contract: 'Multisig2of3',
128
+ kind: 'contract',
129
+ category: 'custody',
130
+ file: 'custody/multisig-2of3.lotus',
131
+ summary: '2-of-3 threshold Schnorr multisig with BIP-340 abstain support.',
132
+ walletBadge: '2-of-3 Multisig',
133
+ actions: { spend: 'Spend coins with at least 2 of 3 signer signatures' },
134
+ },
135
+ {
136
+ id: 'std/custody/vault-with-recovery',
137
+ contract: 'VaultWithRecovery',
138
+ kind: 'contract',
139
+ category: 'custody',
140
+ file: 'custody/vault-with-recovery.lotus',
141
+ summary: 'Owner spend with time-locked guardian recovery.',
142
+ walletBadge: 'Recovery Vault',
143
+ actions: {
144
+ spend: 'Spend vault coins with owner signature',
145
+ recover: 'Recover vault coins with guardian signature after lock height',
146
+ },
147
+ },
148
+ {
149
+ id: 'std/custody/htlc',
150
+ contract: 'HTLC',
151
+ kind: 'contract',
152
+ category: 'custody',
153
+ file: 'custody/htlc.lotus',
154
+ summary: 'Hash Time-Locked Contract for trustless cross-chain atomic swaps.',
155
+ walletBadge: 'Atomic Swap HTLC',
156
+ actions: {
157
+ claim: 'Claim HTLC coins by revealing SHA-256 preimage with recipient signature',
158
+ refund: 'Refund HTLC coins after timeout height with refund signature',
159
+ },
160
+ },
161
+ {
162
+ id: 'std/custody/arbiter-escrow',
163
+ contract: 'ArbiterEscrow',
164
+ kind: 'contract',
165
+ category: 'custody',
166
+ file: 'custody/arbiter-escrow.lotus',
167
+ summary: '2-of-3 buyer/seller/arbiter escrow with timeout refund.',
168
+ walletBadge: 'Arbiter Escrow',
169
+ actions: {
170
+ release: 'Release escrow with buyer and seller signatures',
171
+ arbitrate: 'Resolve escrow dispute with arbiter and one party signature',
172
+ timeout_refund: 'Refund buyer after escrow timeout height',
173
+ },
174
+ },
175
+ // DeFi Primitives
176
+ {
177
+ id: 'std/defi/indexed-limit-order',
178
+ contract: 'IndexedLimitOrder',
179
+ kind: 'contract',
180
+ category: 'defi',
181
+ file: 'defi/indexed-limit-order.lotus',
182
+ summary: '0x-style partial-fill limit order with indexed injective payouts.',
183
+ walletBadge: 'Partial-Fill Limit Order',
184
+ actions: {
185
+ fill: 'Fill limit order (full or partial) paying maker at output 2*i',
186
+ cancel: 'Cancel open limit order and reclaim remaining funds',
187
+ },
188
+ },
189
+ {
190
+ id: 'std/defi/amm-pool-v2',
191
+ contract: 'AmmPoolV2',
192
+ kind: 'contract',
193
+ category: 'defi',
194
+ file: 'defi/amm-pool-v2.lotus',
195
+ summary: 'Profile B constant-product AMM using HAS_STATE, MUL128_WIDE, and SQRT.',
196
+ walletBadge: 'Constant-Product AMM (Zero Admin Keys)',
197
+ actions: {
198
+ first_deposit: 'Initialize AMM pool reserves and mint initial LP shares',
199
+ swap_0_for_1: 'Swap asset 0 for asset 1 preserving 256-bit constant-product invariant',
200
+ },
201
+ },
202
+ ]);
203
+ export function getStandardContract(id) {
204
+ return STANDARD_CONTRACTS.find(spec => spec.id === id);
205
+ }
206
+ export function readStandardContractSource(id) {
207
+ const spec = getStandardContract(id);
208
+ if (!spec)
209
+ throw new Error(`unknown standard contract ${id}`);
210
+ return readFileSync(join(STD_ROOT, spec.file), 'utf8');
211
+ }
212
+ export function compileStandardContract(id, bindings = {}) {
213
+ const spec = getStandardContract(id);
214
+ if (!spec)
215
+ throw new Error(`unknown standard contract ${id}`);
216
+ const source = readStandardContractSource(id);
217
+ const compileOpts = { contract: spec.contract, bindings: { [spec.contract]: bindings } };
218
+ const artifact = compileContract(source, compileOpts, `std/${spec.file}`);
219
+ const warnings = lintContract(source, compileOpts, `std/${spec.file}`);
220
+ return { spec, artifact, warnings };
221
+ }
222
+ export function identifyStandardTemplate(rootHex) {
223
+ const normalized = rootHex.toLowerCase();
224
+ return STANDARD_CONTRACTS.find(spec => spec.universalRoot === normalized);
225
+ }
@@ -0,0 +1,9 @@
1
+ /** Source target selection. eCash emits a direct script, never a Lotus policy. */
2
+ import { type CompileOptions, type ContractArtifact } from './generic.js';
3
+ import { type EcashArtifact } from './ecash.js';
4
+ export type TargetCompileOptions = Omit<CompileOptions, 'target'> & {
5
+ target?: string;
6
+ method?: string;
7
+ };
8
+ export type TargetArtifact = ContractArtifact | EcashArtifact;
9
+ export declare function compileTargetContract(source: string, options: TargetCompileOptions, file?: string): TargetArtifact;
@@ -0,0 +1,139 @@
1
+ /** Source target selection. eCash emits a direct script, never a Lotus policy. */
2
+ import { compileContract, parseModuleSource } from './generic.js';
3
+ import { DiagnosticBag, SourceManager } from './diagnostics.js';
4
+ import { resolveTarget, checkCapabilities } from './targets.js';
5
+ import { validateSemanticProgram } from './semantic-ir.js';
6
+ import { compileEcash } from './ecash.js';
7
+ export function compileTargetContract(source, options, file = '<source>') {
8
+ const sources = new SourceManager();
9
+ sources.add(file, source);
10
+ const bag = new DiagnosticBag(sources, file);
11
+ function fail(code, message, span) { return bag.raise(code, message, span); }
12
+ if (!options || typeof options.contract !== 'string' || !options.bindings || typeof options.bindings !== 'object' || Array.isArray(options.bindings))
13
+ fail('E0601', 'compile options require contract and bindings');
14
+ const target = (() => {
15
+ try {
16
+ return resolveTarget(options.target === undefined ? 'lotus-v2' : options.target);
17
+ }
18
+ catch (error) {
19
+ return fail('E1200', error.message);
20
+ }
21
+ })();
22
+ if (target.id === 'lotus-v2') {
23
+ if (options.method !== undefined)
24
+ fail('E1202', 'Lotus compilation commits the complete contract policy; method selection is available only for the eCash script target.');
25
+ return compileContract(source, { ...options, target: 'lotus-v2' }, file);
26
+ }
27
+ if (options.optimize === true || (options.optimizerVersion !== undefined && options.optimizerVersion !== 'none'))
28
+ fail('E1203', 'The eCash backend has no optimizer; omit optimize or set optimize:false. Lotus optimizations are not applied to eCash bytecode.');
29
+ const program = parseModuleSource(source, true, file, sources);
30
+ if (program.optimizerVersion !== undefined && program.optimizerVersion !== 'none') {
31
+ fail('E1203', `The eCash backend has no optimizer; source pragma optimizer "${program.optimizerVersion}" is unsupported on eCash.`);
32
+ }
33
+ if (program.imports.length)
34
+ fail('E1203', 'eCash source compilation does not yet link packages or imported helpers.', program.imports[0].span);
35
+ const contract = program.contracts.get(options.contract);
36
+ if (!contract)
37
+ fail('E0605', `unknown contract ${options.contract}`);
38
+ const diagnostic = (error) => fail(error.code.startsWith('semantic-ir-') ? 'E1204' : error.code, error.message, error.span);
39
+ const unsupported = (capability, span) => {
40
+ const [error] = checkCapabilities(target, [{ capability, span }]);
41
+ if (error)
42
+ diagnostic(error);
43
+ fail('E1203', `eCash source lowering for ${capability} is not implemented.`, span);
44
+ };
45
+ if (contract.kind === 'token')
46
+ unsupported('lotus-token', contract.span);
47
+ if (options.method !== undefined && typeof options.method !== 'string')
48
+ fail('E1202', 'selected method must be a string', contract.span);
49
+ if (options.method === undefined && contract.methods.length !== 1)
50
+ fail('E1202', 'eCash requires an explicit selected method when a contract has multiple methods; no dispatcher or combined policy is emitted.', contract.span);
51
+ const method = options.method === undefined ? contract.methods[0] : contract.methods.find(m => m.name === options.method);
52
+ if (!method)
53
+ fail('E1202', `unknown selected method ${contract.name}.${options.method}`, contract.span);
54
+ const type = (value, span) => {
55
+ if (value === 'Bool')
56
+ return { kind: 'bool' };
57
+ if (value === 'Bytes32')
58
+ return { kind: 'bytes', length: 32 };
59
+ const sized = /^Bytes\(([0-9]+)\)$/.exec(value);
60
+ if (sized)
61
+ return fail('E1203', `Source ${value} is a maximum byte bound; the current eCash IR requires exact lengths. Use Bytes32 for an exact 32-byte argument or wait for bounded-byte lowering.`, span);
62
+ if (value === 'Int' || value === 'Amount')
63
+ return unsupported('lotus-int128', span);
64
+ if (value === 'PublicKey' || value === 'Signature')
65
+ return unsupported('transaction-signature', span);
66
+ if (value === 'TokenId')
67
+ return unsupported('lotus-token', span);
68
+ return unsupported('transaction-reflection', span);
69
+ };
70
+ const constants = new Map();
71
+ const bound = options.bindings[contract.name] ?? {};
72
+ if (typeof bound !== 'object' || Array.isArray(bound))
73
+ fail('E0602', `constructor bindings for ${contract.name} must be an object`, contract.span);
74
+ for (const p of contract.params) {
75
+ if (!Object.hasOwn(bound, p.name))
76
+ fail('E0603', `missing constructor binding ${contract.name}.${p.name}`, p.span);
77
+ const t = type(p.type, p.span), value = bound[p.name];
78
+ if (t.kind === 'bool') {
79
+ if (typeof value !== 'boolean')
80
+ fail('E0604', `${contract.name}.${p.name} (Bool) requires a Boolean constructor binding`, p.span);
81
+ constants.set(p.name, { kind: 'bool', value, span: p.span });
82
+ }
83
+ else {
84
+ if (typeof value !== 'string' || !/^(?:[0-9a-fA-F]{2})*$/.test(value) || value.length !== t.length * 2)
85
+ fail('E0604', `${contract.name}.${p.name} (${p.type}) requires exactly ${t.length} bytes of hexadecimal`, p.span);
86
+ constants.set(p.name, { kind: 'bytes', hex: value.toLowerCase(), span: p.span });
87
+ }
88
+ }
89
+ const extra = Object.keys(bound).find(key => !constants.has(key));
90
+ if (extra !== undefined)
91
+ fail('E0602', `unexpected constructor binding ${contract.name}.${extra}`, contract.span);
92
+ const args = method.params.map(p => {
93
+ if (constants.has(p.name))
94
+ fail('E0205', `method parameter shadows constructor parameter ${p.name}`, p.span);
95
+ return { name: p.name, type: type(p.type, p.span), span: p.span };
96
+ });
97
+ const expression = (expr) => {
98
+ const span = expr.span;
99
+ if (expr.kind === 'bool')
100
+ return { kind: 'bool', value: expr.value === 'true', span };
101
+ if (expr.kind === 'name') {
102
+ const constant = constants.get(expr.value);
103
+ return constant ? { ...constant, span } : { kind: 'arg', name: expr.value, span };
104
+ }
105
+ if (expr.kind === 'number')
106
+ return unsupported('lotus-int128', span);
107
+ if (expr.kind === 'binary' && expr.value === '==')
108
+ return { kind: 'equal', left: expression(expr.left), right: expression(expr.right), span };
109
+ if (expr.kind === 'call') {
110
+ if ((expr.value === 'sha256' || expr.value === 'hash256') && expr.args?.length === 1)
111
+ return { kind: expr.value, value: expression(expr.args[0]), span };
112
+ if (expr.value === 'checksig')
113
+ return unsupported('transaction-signature', span);
114
+ if (program.helpers.has(expr.value))
115
+ fail('E1203', `eCash source helper inlining is not implemented; selected call ${expr.value} must be expressed in the method body. Lotus helper compilation remains available.`, span);
116
+ if (/^(input|output|utxo|branch|leaf|contract|check_lock|check_sequence|merkle)/i.test(expr.value))
117
+ return unsupported('transaction-reflection', span);
118
+ fail('E1203', `function ${expr.value} is not implemented by the eCash byte/hash source slice`, span);
119
+ }
120
+ fail('E1203', `operator ${expr.value ?? expr.kind} is not implemented by the eCash byte/hash source slice; no Lotus instruction is substituted`, span);
121
+ };
122
+ const statements = (body) => body.map(stmt => {
123
+ if (stmt.kind === 'require')
124
+ return { kind: 'require', condition: expression(stmt.expr), span: stmt.span };
125
+ if (stmt.kind === 'if')
126
+ return { kind: 'if', condition: expression(stmt.expr), then: statements(stmt.then), otherwise: statements(stmt.otherwise), span: stmt.span };
127
+ if (stmt.kind === 'for')
128
+ return unsupported('lotus-loop', stmt.span);
129
+ fail('E1203', 'eCash source assignments are not implemented in the portable expression slice.', stmt.span);
130
+ });
131
+ const ir = { schema: 'lotus/semantic-ir/1', entrypoint: method.name, args, body: statements(method.body), span: method.span };
132
+ const checked = validateSemanticProgram(ir);
133
+ if (!checked.ok)
134
+ diagnostic(checked.diagnostics[0]);
135
+ const result = compileEcash(ir);
136
+ if (!result.ok)
137
+ return diagnostic(result.diagnostics[0]);
138
+ return result.artifact;
139
+ }