@givelotus/compiler 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +331 -2
  2. package/artifact-v2.schema.json +58 -0
  3. package/artifact.schema.json +19 -0
  4. package/dist/ast.d.ts +292 -0
  5. package/dist/ast.js +150 -0
  6. package/dist/bindings.d.ts +6 -0
  7. package/dist/bindings.js +134 -0
  8. package/dist/call-runtime.d.ts +84 -0
  9. package/dist/call-runtime.js +249 -0
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.js +22 -0
  12. package/dist/compiler.d.ts +79 -0
  13. package/dist/compiler.js +125 -0
  14. package/dist/diagnostics.d.ts +163 -0
  15. package/dist/diagnostics.js +498 -0
  16. package/dist/ecash.d.ts +41 -0
  17. package/dist/ecash.js +190 -0
  18. package/dist/fees.d.ts +164 -0
  19. package/dist/fees.js +208 -0
  20. package/dist/fixture-cli.d.ts +2 -0
  21. package/dist/fixture-cli.js +41 -0
  22. package/dist/fixtures.d.ts +68 -0
  23. package/dist/fixtures.js +46 -0
  24. package/dist/forth-ir.d.ts +73 -0
  25. package/dist/forth-ir.js +147 -0
  26. package/dist/generic-cli.d.ts +2 -0
  27. package/dist/generic-cli.js +140 -0
  28. package/dist/generic.d.ts +48 -0
  29. package/dist/generic.js +2566 -0
  30. package/dist/lints.d.ts +8 -0
  31. package/dist/lints.js +204 -0
  32. package/dist/names.d.ts +1 -0
  33. package/dist/names.js +7 -0
  34. package/dist/opcodes.d.ts +154 -0
  35. package/dist/opcodes.js +162 -0
  36. package/dist/optimizer.d.ts +58 -0
  37. package/dist/optimizer.js +786 -0
  38. package/dist/package-fetch-cli.d.ts +2 -0
  39. package/dist/package-fetch-cli.js +17 -0
  40. package/dist/package-lock-cli.d.ts +2 -0
  41. package/dist/package-lock-cli.js +28 -0
  42. package/dist/package-sources.d.ts +82 -0
  43. package/dist/package-sources.js +785 -0
  44. package/dist/package-update-cli.d.ts +2 -0
  45. package/dist/package-update-cli.js +20 -0
  46. package/dist/packages.d.ts +231 -0
  47. package/dist/packages.js +1307 -0
  48. package/dist/parser.d.ts +32 -0
  49. package/dist/parser.js +575 -0
  50. package/dist/policy.d.ts +83 -0
  51. package/dist/policy.js +207 -0
  52. package/dist/runtime.d.ts +58 -0
  53. package/dist/runtime.js +126 -0
  54. package/dist/scheduler.d.ts +38 -0
  55. package/dist/scheduler.js +76 -0
  56. package/dist/semantic-ir.d.ts +76 -0
  57. package/dist/semantic-ir.js +231 -0
  58. package/dist/std.d.ts +27 -0
  59. package/dist/std.js +225 -0
  60. package/dist/target-compiler.d.ts +9 -0
  61. package/dist/target-compiler.js +139 -0
  62. package/dist/targets.d.ts +53 -0
  63. package/dist/targets.js +67 -0
  64. package/dist/toml-subset.d.ts +19 -0
  65. package/dist/toml-subset.js +81 -0
  66. package/dist/transaction-runtime.d.ts +182 -0
  67. package/dist/transaction-runtime.js +646 -0
  68. package/dist/version.d.ts +3 -0
  69. package/dist/version.js +3 -0
  70. package/dist/vm-cost.d.ts +11 -0
  71. package/dist/vm-cost.js +541 -0
  72. package/package.json +71 -4
  73. package/policy-artifact.schema.json +20 -0
  74. package/std/custody/arbiter-escrow.lotus +20 -0
  75. package/std/custody/htlc.lotus +15 -0
  76. package/std/custody/multisig-2of3.lotus +13 -0
  77. package/std/custody/single-owner-wallet.lotus +9 -0
  78. package/std/custody/vault-with-recovery.lotus +14 -0
  79. package/std/defi/amm-pool-v2.lotus +97 -0
  80. package/std/defi/indexed-limit-order.lotus +37 -0
  81. package/std/nft/nft-collection.lotus +51 -0
  82. package/std/nft/royalty-transfer-rules.lotus +38 -0
  83. package/std/nft/unique-nft.lotus +30 -0
  84. package/std/tokens/capped-supply-token.lotus +76 -0
  85. package/std/tokens/fixed-supply-token.lotus +29 -0
  86. package/std/tokens/standard-transfer-rules.lotus +15 -0
  87. package/std/tokens/voucher-mint-token.lotus +31 -0
package/README.md CHANGED
@@ -1,3 +1,332 @@
1
- # Temporary Holding Version
1
+ # Lotus V2 TypeScript compiler
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Start with the [contract gallery](examples/gallery/README.md) for payments, helpers, hash references, token minting, mandatory transfer rules and a burn-to-upgrade method. The schema-2 compiler has a bounded fixed-point optimizer, generated TypeScript/Python bindings, and maintained call runtimes. The [transaction planner](TRANSACTION-RUNTIME.md) builds multi-input spend/mint calls with explicit coins and selected paths. The reference VM, native fixture checks and optional node test exercise different boundaries. The node test submits compiler-built transactions to an isolated regtest chain and checks mempool admission and block inclusion.
4
+
5
+ ## Running tests
6
+
7
+ Run `npm test` from this directory. The JavaScript-only tests and shared
8
+ fee-vector checks need Node. Python-backed tests need the reference dependencies
9
+ from `../lotus-v2-reference/requirements.txt` and `jsonschema` from
10
+ `test/requirements-vm.txt`. Set `LOTUS_V2_PYTHON` to that environment's Python.
11
+ Tests that require unavailable dependencies report a skip or identify the
12
+ omitted Python check. Set `LOTUS_V2_REFERENCE` to use another local reference
13
+ checkout.
14
+
15
+ With a current V2 daemon, run the isolated node test from this directory:
16
+
17
+ ```sh
18
+ npm run build
19
+ LOTUS_V2_REGTEST_BIN=/absolute/path/to/daemon/.build/v2-current/lotusd \
20
+ LOTUS_V2_REGTEST_SCRATCH=/absolute/path/to/existing/private/scratch \
21
+ node --test test/lotusd-regtest.test.mjs
22
+ ```
23
+
24
+ Use a build that includes the token-mint undo correction and returns hashes in
25
+ digest order. The test funds a compiled payment from a matured coinbase, checks
26
+ the script with `testv2transaction` and the fee with `testmempoolaccept`, then
27
+ mines the payment and a token mint. It retains the node log on failure.
28
+
29
+ ## Historical schema-1 payment slice
30
+
31
+ The schema-1 CLI compiles the example `Payment<owner: PublicKey>` contract with one `spend(signature: Signature)` method and `require(checksig(signature, owner));`. Identifiers, whitespace and comments may vary. Other statements, methods, types, opcodes and `OP_SUCCESS_N` are rejected. `owner` is a supplied 32-byte x-only public key, so compilation is deterministic and has no wallet, network, signing or RPC side effect.
32
+
33
+ The CLI emits a versioned JSON artifact with the P03 `PUSH_32 owner CHECKSIG` script, P02 one-leaf branch root and path, source byte spans, static stack report, and thin TypeScript and Python binding sources. The schema-1 Python binding declares an injected runtime protocol; schema 2 has its own maintained Python runtime. Both bindings keep signing separate from call preparation. This legacy TypeScript runtime implements only one native spending input, FULL-mode BIP340 signatures, one branch/path with zero siblings, and native spendable outputs. It requires explicit `chainId`, outpoint, sequence, resolved coin, outputs and profile. Amounts are `bigint`; bytes are `Uint8Array` internally. The fixture-only profile name prevents treating this as production network validation.
34
+
35
+ ```sh
36
+ cd tools/lotus-compiler
37
+ npm ci
38
+ npm test
39
+ node dist/cli.js examples/payment.lotus f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9 /tmp/lotus-payment-abi
40
+ node examples/run-payment.mjs
41
+ ```
42
+
43
+ `run-payment.mjs` signs with the public BIP340 test key 3 and zero auxiliary randomness. It prints actual transaction bytes and machine-readable stage results. Its signed wire, TxID, TxHash and signing digest are checked by the Python reference and the native signing fixture tests. The `stages` fields describe the checks performed by the standalone runtime.
44
+
45
+ ## Offline test fixtures
46
+
47
+ `buildPaymentFixture(input)` in `@givelotus/compiler/fixtures` accepts explicit source, 32-byte x-only owner, deterministic public test secret, ChainID, outpoint, sequence, lock, resolved coin, output list, profile and signing mode `0` (FULL). Its amounts and lock use `bigint`; the JSON CLI accepts canonical decimal strings. The test secret is an input to the offline builder and is **never included in exported fixtures**. The fixture has schema `lotus/payment-fixture/1`, a signature-valid baseline with complete transaction bytes, and three named mutations: changed output value, changed ChainID and changed owner. Each mutation retains the original signature and records `expectedStage: signature` and the rejection reason. These are stage expectations, not full consensus-valid/invalid claims.
48
+
49
+ ```sh
50
+ npm run build
51
+ node examples/generate-fixtures.mjs
52
+ node dist/fixture-cli.js input.json output.json
53
+ ```
54
+
55
+ The CLI input uses schema `lotus/payment-fixture-input/1`. It has the same fields as `PaymentFixtureInput`, except `coin.value` and output values are `valueAtoms` decimal strings and `lock` is a decimal string. Each output has `flags: 0`, `branches: [lowercase-h32]`, and `paths: [[0]]` for this slice. `profile` must be `payment-fixture-p01-v1`, `signingMode` must be `0`, and the first output must be positive so a changed-value mutation is possible. The builder rejects a test secret whose public key differs from `owner`. Its JSON output can be consumed by daemon fixture generators or native tests without importing the TypeScript compiler into consensus code.
56
+
57
+ The checked-in key-3 one-output fixture reproduces the independent hand vector. The key-4 two-output fixture varies the script/policy, input outpoint, amounts and output count. Generated TypeScript and Python wrappers are executed in tests and produce the same signed witness bytes. This legacy Python test supplies a wire adapter through the generated runtime protocol. Schema-2 tests execute the maintained Python call and transaction runtimes.
58
+
59
+ To check those newly generated bytes against the separate native signing candidate:
60
+
61
+ ```sh
62
+ cmake -S test/native-check -B /tmp/lotus-compiler-native -GNinja \
63
+ -DLOTUS_V2_CPP=/path/to/native-candidate/src/lotus_v2 \
64
+ -DLOTUS_SECP_LIBRARY=/path/to/libsecp256k1.a
65
+ cmake --build /tmp/lotus-compiler-native
66
+ node test/run-native-fixtures.mjs /tmp/lotus-compiler-native/compiler_fixture_native_check
67
+ ```
68
+
69
+ This checker runs native framing, identities, signing message and BIP340 verification for both baseline transactions and all six changed-context/signature mutations. It does not run VM execution. The gallery uses the transaction runtime for mint, transfer, state and delayed-recovery examples.
70
+
71
+ The separate token checker runs the native P03/P05 VM. Set `LOTUS_V2_CPP` to the daemon source directory `daemon/lotusd/src/lotus_v2`:
72
+
73
+ ```sh
74
+ cmake -S test/native-token-check -B /tmp/lotus-native-token-vm \
75
+ -DLOTUS_V2_CPP=/path/to/native-source/src/lotus_v2 \
76
+ -DLOTUS_SECP_LIBRARY=/path/to/libsecp256k1.a
77
+ cmake --build /tmp/lotus-native-token-vm
78
+ node test/run-native-token-fixtures.mjs /tmp/lotus-native-token-vm/compiler_token_native_check
79
+ ```
80
+
81
+ This target requires OpenSSL Crypto. It verifies the signed Payment and all ten
82
+ mint/transfer/merge witness invocations under an illustrative cost profile.
83
+ Negative probes reach the VM for an unauthorized issuer, re-signed transfer and
84
+ merge outputs removing the mandatory rules or wallet path, and a mint input's
85
+ nonexistent coin. The regtest test covers transaction admission and mining.
86
+
87
+ The artifact schema is `lotus/payment-artifact/1`; its target is `P01-P02-P03-candidate-2026-10-14`. JSON hashes and bytecode are lowercase hex; user-facing native amounts must be decimal atom strings and parsed to checked `bigint`. The runtime accepts no implicit network and rejects an artifact whose policy root does not match its script. Generated clients must pin this schema and supply a separately reviewed signer; they must not assume that a valid signature alone makes a transaction valid.
88
+
89
+ Schema-1 source mapping retains UTF-16 offsets (JavaScript string offsets); schema 2 uses UTF-8 byte offsets.
90
+
91
+ ## Promise scheduler and executable optimizer demo
92
+
93
+ Run the [compiler pipeline demo](examples/compiler-pipeline/README.md) to see a
94
+ forward-reference dependency diamond, a shared compilation job, before/after
95
+ bytecode, and independent VM execution of valid and malformed inputs.
96
+
97
+ `compileContractAsync(source, options, onEvent?)` parses once and registers the
98
+ retained declarations. Promise jobs compile method leaves and contract roots after
99
+ awaiting their dependencies. Pure helpers are expanded within method jobs. Shared
100
+ jobs are memoized per compilation; unused declarations are not compiled. The
101
+ scheduler checks cycles before starting jobs and reports their declaration spans.
102
+ It bounds jobs, dependency edges, depth, and helper dependency discovery. These are
103
+ single-threaded dependency jobs, not CPU worker threads.
104
+
105
+ `compileContractWithTrace(source, options)` returns `{ artifact, trace }`; events
106
+ include `start`, `await`, `resolve`, and `reject`. The generic CLI now uses the
107
+ scheduler and accepts a final `--trace` flag to write `scheduler-trace.json` next
108
+ to the artifact and generated clients. The synchronous `compileContract` API
109
+ remains available and produces the same artifacts for accepted inputs.
110
+
111
+ ## Bounded template and method frontend (artifact schema 2)
112
+
113
+ `compileContract(source, { contract, bindings })` in `@givelotus/compiler/generic` compiles one selected `contract` or `token` tree from a source that may contain multiple trees and free pure helpers. Every constructor value for every referenced tree must be supplied explicitly. It emits `lotus/contract-artifact/2` with ordered method arguments, each method's script, leaf, bottom-up membership proof, source map and static size/stack report. A contract root is a spending branch; a token root is its token ID. The `kind` and per-method `invocation` fields identify these different uses. Token methods require a first `Amount` parameter in source; that parameter is omitted from `method.args` because the node pushes the positive mint delta above witness arguments. The policy is one P02 branch root with path `[[0]]`. The deterministic method tree sorts distinct method leaves as unsigned little-endian hashes, splits at the greatest power of two below the leaf count, and uses P02's sorted-child node hash. Method names select an ABI entry; consensus sees the revealed script and proof, with no numeric method index.
114
+
115
+ Compilation optimizes `CHECKSIG; VERIFY` into `CHECKSIGVERIFY`, `EQUAL; VERIFY` into `EQUALVERIFY`, and `ZERO; PICK` into `DUP` using a bounded fixed-point pass. It recursively reduces adjacent known literal expressions for checked int128 arithmetic, canonical Boolean operations, equality and hashing. A known true verification can disappear; false verification, overflow and malformed values retain their failing operations. Constructor bindings and cross-contract hashes are opaque to equality folding so policy roots still commit to them. The symbolic stack pass tracks argument identities and canonical Boolean facts established by `IF` and successful `VERIFY`. It recursively analyzes both branch arms, merges compatible identities, and removes redundant pure stack reads and proven checks. Loop bodies are analyzed with fresh incoming identities and no inherited facts; loop exit also discards identities, so mutable locals cannot be mistaken for invariants. The combined literal, peephole and symbolic passes repeat to a bounded fixed point. This is a conservative supported subset, without general expression common-subexpression elimination, arithmetic theorem proving, or loop unrolling. For a straight-line method with exactly one argument and one depth-zero use, it also consumes that argument directly and removes its copy and final drop; loops and all non-allowlisted operations disable that rewrite. For example, `require(checksig(sig, owner))` lowers to `PUSH_32 owner; CHECKSIGVERIFY; ONE` (35 bytes, three opcodes). `optimize: false` emits the original lowering for differential testing. `staticResources` and byte offsets describe the final script; a fused source-map entry records original instructions in `optimizedFrom`. Fewer bytes and opcodes lower cost only under a profile that prices those instructions accordingly. Because the script changes, so do its method leaf, contract root, signature digest and signed transaction fixture. Regenerate any schema 2 fixture from the compiler when switching modes; schema 1 Payment fixtures remain separate.
116
+
117
+ ```text
118
+ function digest(x: Bytes32): Bytes32 { return sha256(x); }
119
+ contract Vault<owner: PublicKey, target: Bytes32> {
120
+ function spend(sig: Signature) { require(checksig(sig, owner)); }
121
+ function reveal(data: Bytes32) { require(digest(data) == target); }
122
+ }
123
+ ```
124
+
125
+ Supported constructor and method types are `PublicKey` (validated BIP340 x-only point), `Signature`, `Bytes32`, `Bytes(N)` (up to N bytes, N in 1..8192), signed 128-bit `Int` and `Amount`, exact 32-byte `TokenId`, `Bool`, and distinct `MethodLeafHash` / `ContractRootHash` values. Constructor byte values are lowercase hex, numeric values canonical decimal strings or `bigint`, and Bool values booleans. Methods take ordered wire arguments. Expressions include `checksig`, `sha256`, `hash256`, `blake3`, equality, limited checked integer arithmetic/comparison, Boolean operators and unary `!`/`-`. The full signed Int range, including `-2^127`, is accepted; values outside it reject. Statements include `require`, bounded `if`, local numeric assignments, and `for input in tx.inputs` / `for output in tx.outputs` with at most two nested loops. Introspection supports input spend flags and resolved coin fields, output token/value fields, `this.root`, and `output.requires_branch(root)`. `check_lock` and `check_sequence` check the absolute and relative locks (see below). Mint methods cannot read `this.coin`; input coin reads in a mint loop must be guarded by `input.is_spend` because mint inputs resolve no coin. A method finishes with exactly one true value after its requirements pass. Free helpers inline at calls with scoped parameters and source origin spans; the VM never sees a call. A helper body is either `return expr;` or statements: `let name: Type = expr;`, `require(expr);`, `if (expr) { ... } else { ... }`, and a final `return expr;`. `let` evaluates once. A parameter is still substituted at each use. `for` inside a helper is rejected, because inlining it could nest past the two-loop consensus cap and there is no second loop implementation. Arbitrary opcodes and external effects remain unsupported.
126
+
127
+ Boolean `&&` and `||` short-circuit through P03 conditionals. This lets `input.is_spend && input.coin.token_id == old_token` avoid reading a coin for a mint input. A top-level `require` of `&&`, including nested `&&`, is split into one `require` per conjunct so each check sits next to `VERIFY` and can fuse; both forms abort on the first false value. `||` is not split. A helper call substitutes its argument expression at each parameter use (call-by-name), so a helper that uses `x` twice evaluates `x` twice in the emitted script. This can repeat `checksig` or hash work. A `let` avoids that repeat. The compiler reports script size, opcode count and a conservative maximum signature-check count after expansion, multiplying loop bodies by their maximum transaction count. It bounds emitted helper expansions and type-inference visits. A direct method expression avoids repeated evaluation of an expensive value.
128
+
129
+ ### Artifact provenance and authentication
130
+
131
+ Every schema 2 artifact records `compiler` (package name, version, edition and optimizer version) and `source`: the source text, file name and constructor values for a single-file build, or for a package build the linked program after import resolution together with the constructor values of every tree. The runtimes do not trust the rest of the artifact. Before planning a call, the TypeScript call runtime and transaction planner recompile `source` with the same compiler and options and reject the artifact unless every top-level field matches (`artifact does not match its source: <field>`). That covers the scripts, the argument order of every method, the displayed constructor bindings, the static resources and the policy root. An artifact without `source`, or from another compiler name or version, is rejected; recompile it. Package artifacts are recompiled from the embedded linked program, so a runtime check does not reread the package files or the lock. Each entry in `links` must name a root and method leaves that the embedded program computes; its `packageDigest` and the `build` graph are build metadata and are not recomputed. The Python runtime cannot recompile and checks only the artifact's structure and its proofs.
132
+
133
+ ### Time locks: `check_lock` and `check_sequence`
134
+
135
+ `check_lock(kind, bound)` requires the transaction's absolute lock (P01) to have
136
+ `lock_kind == kind` and `lock_value >= bound`. Kind `1` is a block height: the
137
+ transaction is valid in a block whose height is at least `bound`, so a lock of
138
+ `N` first confirms in block `N`, built on tip `N - 1`. Kind `2` is a median time
139
+ past: the parent block's MTP must be at least `bound` seconds. The transaction
140
+ must set the matching lock itself; the script only checks it.
141
+
142
+ `check_sequence(kind, bound)` requires the spending input's relative lock (its
143
+ `sequence`, P01) to be enabled with that kind and a delay of at least `bound`:
144
+ kind `1` counts blocks since the coin confirmed, kind `2` counts 512-second
145
+ units. A mint has no consuming input, so `check_sequence` is rejected in a
146
+ `token` method; `check_lock` is allowed there.
147
+
148
+ Both return `true` when the check passes and abort the method otherwise, so they
149
+ are written as `require(check_lock(1, refundHeight));`. A lock that can never be
150
+ met would strand every coin on that path, so the compiler rejects, at compile
151
+ time:
152
+
153
+ - a kind that is not a compile-time constant (a literal, a bound constructor
154
+ value or a helper argument built from them) with `E0415`;
155
+ - any kind other than `1` or `2` with `E0416`;
156
+ - a constant bound that cannot be met with `E0417`: a negative bound, a
157
+ `check_lock` bound above the 56-bit `lock_value`, a height above the u32 block
158
+ height range, or a `check_sequence` bound outside `0..65535`;
159
+ - `check_sequence` in a mint with `E0418`.
160
+
161
+ A bound that is not constant, for example one computed from a witness argument,
162
+ is checked by the VM when the method runs.
163
+
164
+ ```text
165
+ contract Htlc<recipient: PublicKey, sender: PublicKey, digest: Bytes32, refundHeight: Int> {
166
+ function claim(signature: Signature, preimage: Bytes32) {
167
+ require(sha256(preimage) == digest);
168
+ require(checksig(signature, recipient));
169
+ }
170
+ function refund(signature: Signature) {
171
+ require(check_lock(1, refundHeight)); // the refund sets lock = (refundHeight << 8) | 1
172
+ require(checksig(signature, sender));
173
+ }
174
+ }
175
+ ```
176
+
177
+ ### Comparing roots and binding payouts
178
+
179
+ Equality compares values of the same type. A plain `Bytes32`, such as a branch read
180
+ `input.coin.branch(0)` or a constructor value, also compares directly with a
181
+ `ContractRootHash`, `MethodLeafHash` or `TokenId`, so `input.coin.branch(0) == this.root`
182
+ needs no hashing. The distinct hash kinds still do not compare with each other.
183
+ `requires_branch`, `exclusive_branch` and `continues_branch` accept a `ContractRootHash`
184
+ or a `Bytes32` root.
185
+
186
+ Every input under a policy runs the method against its own coin. A covenant that checks
187
+ one payout against `this.coin.value` alone therefore also passes when two such coins are
188
+ spent together into that one payout, and the second coin's value becomes fee. Bind the
189
+ payout to the inputs: count the spend inputs whose coin `requires_branch(this.root)` and
190
+ require exactly one (the gallery `Vault` and `Counter` do this), or compare the payout
191
+ with their summed value.
192
+
193
+ `lintContract(source, options)` compiles the source and returns advisory warnings
194
+ without changing the artifact. The CLI prints them to stderr.
195
+
196
+ - `W0701` reports a method that compares an output value with `this.coin.value`
197
+ while no input loop refers to `this.root`.
198
+ - `W0702` reports an entry the compiler can prove succeeds for well-formed
199
+ arguments, allowing anyone to spend under it or mint its token.
200
+ - `W0703` names each signature argument the method never reads.
201
+
202
+ `leaf_hash(Other.method)` yields a `MethodLeafHash` of a fully bound compiled method. `contract_root(Other)` yields a `ContractRootHash` of a fully bound contract. Their types are distinct from plain `Bytes32`, except that equality accepts a `Bytes32` operand (above). A self or mutual dependency through these builtins is rejected, as are recursive helpers. Source spans in schema 2 are **UTF-8 byte offsets**; schema 1 Payment artifacts retain their historical UTF-16 code-unit offsets. Schema 2 limits source to 65536 UTF-8 bytes, methods to 16, scripts to 8192 bytes, opcodes to 4096, helper expansions to 256, inference visits to 8192, and expression/control nesting to 64/16. Normal compilation emits only assigned P03 opcodes and rejects unsupported syntax, including an `OP_SUCCESS_N` spelling. Source names use a portable TypeScript/Python namespace; reserved names and case-folded method collisions reject before binding generation.
203
+
204
+ The v2 CLI reads source plus an options JSON object, then writes `artifact.json` and generated TypeScript and Python call wrappers:
205
+
206
+ ```sh
207
+ node dist/generic-cli.js vault.lotus options.json /tmp/vault-artifact
208
+ ```
209
+
210
+ For the example, `options.json` is `{"contract":"Vault","bindings":{"Vault":{"owner":"<32-byte lowercase hex>","target":"<32-byte lowercase hex>"}}}`. The schema is [artifact-v2.schema.json](artifact-v2.schema.json). Schema 1 artifacts are not reinterpreted as schema 2; its signed fixture remains an independent historical vector. The generated TypeScript and Python wrappers plan through the [transaction planner](TRANSACTION-RUNTIME.md#generated-bindings), so a contract input can be combined with wallet inputs and the fee policy applies; neither signs or contacts a node. Single-file compilation has no RPC, wallet, filesystem import, or signing side effect; the CLI only reads its declared source/options and writes requested artifact files. Package builds (below) read the lock, declared files and, when the graph names a module path, the local cache or `vendor/` tree.
211
+
212
+ ## Local packages and explicit imports (CABI-07)
213
+
214
+ `compilePackage(dir, { contract, bindings, optimize?, limits? })` in `@givelotus/compiler/packages` builds the root package in `dir` from `lotus.toml`, `lotus.lock` and declared local files. It is build-time only, has no network, registry, clock or environment input, and touches no consensus, VM, runtime or transaction code. `compileContract(source, ...)` is unchanged: it is a wrapper over one in-memory module, rejects `import`, never emits a `build` field, and single-file artifacts and fixtures are byte-identical to the previous compiler. See [examples/packages](examples/packages/README.md) for the diamond fixture. Use `createSpendBundle` and `verifySpendBundleReproducibility` from the same `packages` entry point to capture the inputs needed to reproduce a compiled policy and check its commitments.
215
+
216
+ ```sh
217
+ node dist/package-lock-cli.js DIR # rewrite DIR/lotus.lock from local files only
218
+ node dist/package-lock-cli.js DIR --check # fail if the lock is stale
219
+ node dist/generic-cli.js --package DIR options.json OUT_DIR [--trace]
220
+ ```
221
+
222
+ **Syntax.** Imports precede declarations. `import ALIAS::path::to::module::{name, other as local};` binds selected functions or contracts under local names; `import ALIAS::path::module as m;` binds a module alias used as `m::name(...)` for helpers and as `m::Contract` / `m::Contract.method` inside `contract_root`, `leaf_hash` and `merkle_root`. `ALIAS` is a dependency alias from the importing package's manifest, or the keyword `package` for a module in the same package. Visibility is `function`/`contract`/`token` (private to its module), `package function`/`package contract`/`package token`, or `export` (other packages, but only from modules listed in `exports`). Helpers already require explicit parameter and result types. Local names, imports and module aliases share one namespace per module; duplicates and builtin names (`checksig`, `sha256`, ...) reject. Single-file builds accept the visibility modifiers without effect. Imported helpers inline exactly like same-file helpers (the test compares a package build with an equivalent flattened source). Library contracts are covered under CABI-08 below.
223
+
224
+ **Manifest.** `lotus.toml` uses a strict TOML subset parsed by [toml-subset.ts](src/toml-subset.ts) (tables `[package]`, `[dependencies]`, `[sources]`, `[replace]`; bare keys or quoted basic-string keys; plain strings and one-line string arrays; no escapes, numbers, dotted keys or inline tables; duplicates and unknown keys reject). Every accepted file is valid TOML. `[package]` has `name`, exact `version` (`MAJOR.MINOR.PATCH`), `kind` (`contract` or `library`), `source` (source root subdirectory), `modules` (all module files, `a/b` means `SOURCE/a/b.lotus`), optional `exports`, and `entry` for contract packages. A local package name is a short identifier. A git package name is its module path. `[dependencies]` maps a local alias to an exact `name@MAJOR.MINOR.PATCH` or to a module selector (`module@vX.Y.Z` or `module@` + 40 hex digits). `[sources]` in the root manifest maps a short name to a project-relative path. `[replace]` in the root manifest maps a module path to another relative path or git locator. Dependency `[sources]` and `[replace]` tables are ignored.
225
+
226
+ **Lock.** A path-only graph writes canonical JSON `lotus/package-lock/1`: the root name/version/dependencies and, per dependency, its path locator, resolved package root (project-relative realpath), dependencies, per-file digests (manifest and declared modules) and tree digest. A graph that names a module path, a replace, or a quoted import writes `lotus/package-lock/2` instead. Schema 2 adds the selected commit and git tree when the package came from git, the requesters, and whether a root replace is in effect. A build regenerates the lock text from disk and requires byte equality, so a changed source byte, manifest or dependency set is rejected (`lock-mismatch` names the file) until the lock is rewritten. Compile does not rewrite a schema-1 lock into schema 2.
227
+
228
+ **Module paths.** There is no registry and no name claim. A package is named by where it lives. For `github.com`, `gitlab.com`, `bitbucket.org` and `codeberg.org`, `host/owner/repo` is the git repository `https://host/owner/repo.git`. Any remaining path is a subdirectory of that repository. A final `/vN` with N ≥ 2 is a major-version suffix, as in Go: `github.com/acme/lotus-std/v2` is still `https://github.com/acme/lotus-std.git`. If `v2/lotus.toml` exists, that directory is the package root; otherwise the repository root is the package root when its manifest major is 2. Tags `v0` and `v1` have no suffix. A `v2+` tag on an unsuffixed path is rejected. `/v2` is a different module from v1, so minimal version selection does not merge them. Any other host is not guessed. The root manifest must name it in `[sources]` as an `https://` or absolute `file://` URL, with an optional `#dir` subdirectory. Vanity-domain HTML discovery and a proxy mirror are not implemented.
229
+
230
+ The same package can be named by an alias or by a quoted path. Both are requirements, and the compiler parses the selected module once:
231
+
232
+ ```text
233
+ std = "github.com/acme/lotus-std@v1.2.0" # root lotus.toml
234
+ import std::amounts::{checkedAdd as safeAdd};
235
+ import "github.com/acme/lotus-std@v1.2.0"::amounts::{checkedAdd as alsoAdd};
236
+ ```
237
+
238
+ Selectors on compile and fetch are exact tags or full commit ids. Two tags of one module path use minimal version selection (the higher tag required by the root or by a selected version). Requirements of a version that lost that comparison are ignored. Two different commit pins are an error. A tag and a commit are accepted only when the tag resolves to that commit. Branch names and `^` / `~` ranges are rejected until `lotus-package-update`, which rewrites the root manifest to an exact tag or commit and then fetches.
239
+
240
+ ```sh
241
+ node dist/package-fetch-cli.js DIR # clone into DIR/.lotus/deps and write lotus.lock
242
+ node dist/package-fetch-cli.js DIR --vendor # clone into DIR/vendor instead
243
+ node dist/package-update-cli.js DIR std@^1.2.0 # pin the highest matching tag, then fetch
244
+ node dist/package-update-cli.js DIR std@main # pin the branch's commit, then fetch
245
+ ```
246
+
247
+ Fetch is the only networked package command. It runs git with hooks, templates, smudge filters and prompts disabled, deletes `.git` before the tree is scanned, and does not run repository code. Compile, `lotus-package-lock` and a fetch that is not repeated read only the lock, `.lotus/deps` or `vendor`, and declared files. They verify every locked digest and do not spawn git. Exactly one of the cache and `vendor` may hold a selector. A root `[replace]` wins over the derived URL and is recorded in the lock; replacements are never read from dependencies.
248
+
249
+ **Digests.** All digests use the existing domain-separated `tagged(name, payload) = BLAKE3("Lotus/v2/" || name || 0x00 || payload)` with CompactSize-prefixed fields: `package/file` over the file bytes; `package/tree` over name, version and sorted `(path, file digest)` pairs; `package/declaration` over an exported helper's name, parameter names/types and result type; `package/contract` over an exported contract or token's kind, name, parameters and method parameters; `package/interface` over package name, module path and those exported declaration digests (bodies change `sourceDigest`, not `interfaceDigest`; a helper-only module's interface bytes stay the helper formula); `package/lock` over the lock bytes; `build-graph` over the UTF-8 JSON of the build graph without its `digest`.
250
+
251
+ **Resolution rules.** Module identity is `(name@version, normalized module path)`, written `core@1.0.0/amounts`. Absolute paths, `..`, backslashes and non-normalized segments reject; package roots must realpath inside the root project, source roots inside their package, and any symlink inside a source root must resolve to a file inside the package. Source roots are walked with exact on-disk names: undeclared files, declared modules without an exact-case file, and case/Unicode (NFKC + case-fold) collisions reject. Each module identity is parsed once and has one `module:<id>` scheduler job that links it after its imports, so diamond imports are deduplicated (`parses` and the trace prove it). Defaults: 64 packages, 256 modules, import depth 32, 4096 import bindings, 4 MiB total source, 4096 walk entries; `limits` lowers them.
252
+
253
+ **Diagnostics.** `PackageError` has a `code` (`path-escape`, `symlink-escape`, `path-collision`, `undeclared-file`, `missing-module`, `missing-symbol`, `unknown-alias`, `not-exported`, `visibility`, `duplicate-name`, `import-cycle`, `lock-missing`, `lock-mismatch`, `lock-stale`, `limit`, ...), a project-relative `file` and, for source errors, a UTF-8 byte `span`, formatted `file:start..end: message [code]`. Import cycles list every hop with file and span.
254
+
255
+ **Artifacts.** Package artifacts stay `lotus/contract-artifact/2` with an optional `build` object (`lotus/build-graph/1`): compiler name/version/profile, target, root package and entry module, lock digest, every package's tree digest and dependency aliases, and every reachable module's file, source digest, interface digest, exported signatures and imports. Source-map spans in package artifacts carry a `module` identity. Paths are project-relative, so identical inputs give byte-identical artifacts in any checkout. The contract root still commits only to bytecode: a comment-only dependency change alters the build graph but not the root; a semantic change alters both. A package build that commits to a compiled contract from another package also carries `links` (see CABI-08). The field is omitted when empty, so the diamond artifact and single-file artifacts carry no `links`.
256
+
257
+ **Diagnostics while inlining.** Type errors detected while expanding an imported helper name the canonical helper (`lib_a@1.0.0/limits::withinBudget`), point at the offending expression in that helper's file, and note each call site (`in expansion of helper NAME called here`).
258
+
259
+ ## Shared contract libraries (CABI-08)
260
+
261
+ `examples/packages/linked` is two root contracts, `Payer` and `Receiver`, consuming one locked library, `policy@1.0.0`. The library exports `Escrow` plus the helper `authorized`. A private contract, a private helper and a package-scoped contract in that module are not importable from `pay`. `import policy::escrow::{Escrow, authorized}` and `import policy::escrow as escrow` both resolve. `contract_root`, `leaf_hash` and `merkle_root` are rewritten to the contract's declared name, and the existing compiler bakes that bytecode root or method leaf into the caller. `authorized` is inlined; the Payer script matches an equivalent single-file program. There is no `OP_DEFINE`, `OP_INVOKE` or other VM call. Recursive helpers still reject.
262
+
263
+ `links`, when present, sits on the schema-2 artifact ahead of `build`. Each entry is a compiled library contract other than the selected contract: name, kind (`contract` or `token`), package id, module id, package tree digest, consensus root, and method name/leaf pairs. Same-package contracts stay out of `links`. Selecting `Escrow` itself records no self-link. Declared names are flat and must be unique across the program, so the artifact `contract` field stays a portable identifier.
264
+
265
+ A one-byte comment edit in the library, once `lotus.lock` is regenerated, changes that file's source digest, the package tree digest, the lock digest and the build digest. It does not change `Escrow`'s root or the consumer's `policy.root`. Replacing `require(1 == 1)` with `require(2 == 1)` changes the library bytecode, `links[].root` and the consumer root. Updating the source without regenerating the lock fails with `lock-mismatch` and names the file. An exported library token links the same way; `contract_root` of that token is a `TokenId`.
266
+
267
+ The existing binding generators append one deterministic dump when `links` is non-empty. TypeScript exports `linkedContracts` (`name`, `packageDigest`, `root`, method names). Python assigns `LINKED_CONTRACTS` with the same fields (`package_digest`). Artifacts with no links keep the previous binding text. `lotus-contract-compile --package` writes both files beside `artifact.json`.
268
+
269
+ `test/linked-libraries.test.mjs` sends the signed `Escrow`, `Payer` and `Receiver` spends to the Python reference VM when `LOTUS_V2_PYTHON` can import `blake3`, `coincurve` and `lotus_v2_reference`. The CABI-08 run did that: a valid signature was accepted, a mutated signature was rejected, and a Payer bound to a different escrow root was rejected. `LOTUS_V2_NATIVE_VM`, pointed at the current `lotus_v2_vm_runner` argv CLI, returned `U` for that CHECKSIG script. That runner has no signing context, so signed native execution was not performed. An unset variable records the same limit and does not fail the compiler tests.
270
+
271
+ A proxy mirror, vanity-domain discovery, registries, trust policy and published-package compatibility are still unimplemented. Branch names and semver ranges resolve only through `lotus-package-update`.
272
+
273
+ ## Explicit compiler targets
274
+
275
+ The existing `compileContract` and package APIs emit Lotus V2 policies. Their
276
+ output remains unchanged when `target` is omitted or set to `"lotus-v2"`.
277
+ They reject other target values. Use `compileTargetContract` from
278
+ `@givelotus/compiler/target-compiler` for explicit source target selection:
279
+
280
+ ```ts
281
+ import { compileTargetContract } from '@givelotus/compiler/target-compiler';
282
+ const artifact = compileTargetContract(
283
+ `contract Hashlock<expected: Bytes32> {
284
+ function main(preimage: Bytes32) {
285
+ require(sha256(preimage) == expected);
286
+ }
287
+ }`,
288
+ { target: 'ecash', contract: 'Hashlock',
289
+ bindings: { Hashlock: { expected: 'ab'.repeat(32) } } },
290
+ );
291
+ ```
292
+
293
+ The eCash result is `ecash/script-artifact/1`: a direct locking script with an
294
+ ordered byte/Boolean argument ABI, source map and static resource bounds. It has
295
+ no Lotus policy, branch root, transaction or signing wrapper. Its profile is
296
+ pinned to ABC `1fb7db17c176cdea8a2c60d887891589382ee4e3`, using that pin's standard
297
+ script verification flags plus the explicit research restriction MINIMALIF.
298
+ Compilation does not establish standard relay admission, transaction validity or
299
+ current network activation. The native test gate executes the direct script.
300
+
301
+ Set `target` in the existing CLI options JSON. An eCash invocation writes only
302
+ `artifact.json` and `script.hex`; use a fresh output directory. Default Lotus
303
+ invocations still produce their existing artifact and TypeScript/Python clients.
304
+ Unknown targets reject. eCash package mode and `--trace` reject explicitly.
305
+
306
+ The initial source slice supports exact `Bytes32`, canonical `Bool`, constructor
307
+ bindings of those types, `sha256`, `hash256`, same-type `==`, `require`, and `if`
308
+ with `else`. Runtime byte widths and Boolean encodings are checked by the script.
309
+ Source `Bytes(n)` means a maximum bound in Lotus, while the initial portable IR
310
+ has exact lengths; eCash source compilation rejects `Bytes(n)` rather than narrow
311
+ its accepted domain. The lower-level semantic IR API accepts explicit exact byte
312
+ lengths and is exported separately as `/semantic-ir` with `/ecash` and `/targets`.
313
+
314
+ A single-method contract selects that method automatically. For a contract with
315
+ multiple methods, `method: 'main'` selects one explicitly; the artifact commits
316
+ only that method's script and creates no combined dispatcher. Unselected method
317
+ syntax still parses, but its capabilities are not lowered. Constructor types and
318
+ bindings for the selected contract remain checked. Lotus method selection stays
319
+ at its existing invocation layer; source compilation commits the complete policy.
320
+
321
+ Selected helper calls, package imports, assignments, other Boolean operators,
322
+ Lotus int128/Amount arithmetic, transaction signatures, reflection, enumeration
323
+ and token contracts reject in this eCash source slice. Lotus helper/package
324
+ inlining continues through the existing compiler. The eCash backend has no
325
+ optimizer: omit `optimize` or use `false`; `optimize: true` rejects instead of
326
+ applying Lotus rewrites to eCash bytes. No DEFINE/INVOKE lowering is introduced.
327
+
328
+ Run the source integration tests against the independently built pinned ABC
329
+ adapter by setting `LOTUS_ECASH_NATIVE` to its executable, then running
330
+ `node --test test/target-integration.test.mjs` after `npm run build`. Without that
331
+ variable the native execution test is explicitly skipped. Other tests cover
332
+ source/CLI selection, rejection diagnostics and spans, and unchanged Lotus output.
@@ -0,0 +1,58 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://givelotus.org/schemas/lotus/contract-artifact/2",
4
+ "title": "Lotus V2 bounded contract artifact candidate",
5
+ "type": "object",
6
+ "required": ["schema", "target", "contract", "constructor", "bindings", "methods", "policy", "compiler", "source"],
7
+ "additionalProperties": false,
8
+ "properties": {
9
+ "languageVersion": { "const": 1 },
10
+ "schema": { "const": "lotus/contract-artifact/2" },
11
+ "target": { "const": "P01-P02-P03-candidate-2026-10-14" },
12
+ "contract": { "$ref": "#/$defs/name" },
13
+ "kind": { "enum": ["contract", "token"] },
14
+ "constructor": { "type": "array", "items": { "$ref": "#/$defs/typedName" } },
15
+ "bindings": { "type": "array", "items": { "type": "object", "required": ["name", "type", "value"], "additionalProperties": false, "properties": { "name": { "$ref": "#/$defs/name" }, "type": { "$ref": "#/$defs/valueType" }, "value": { "type": ["string", "boolean"] } } } },
16
+ "methods": { "type": "array", "minItems": 1, "maxItems": 16, "items": { "type": "object", "required": ["name", "args", "scriptHex", "leaf", "proof", "root", "sourceMap", "staticResources"], "additionalProperties": false, "properties": { "name": { "$ref": "#/$defs/name" }, "invocation": { "enum": ["spend", "mint"] }, "mintAmountParam": { "$ref": "#/$defs/name" }, "args": { "type": "array", "items": { "$ref": "#/$defs/typedName" } }, "scriptHex": { "type": "string", "pattern": "^(?:[0-9a-f]{2})+$", "maxLength": 16384 }, "leaf": { "$ref": "#/$defs/h32" }, "proof": { "type": "array", "maxItems": 64, "items": { "$ref": "#/$defs/h32" } }, "root": { "$ref": "#/$defs/h32" }, "sourceMap": { "type": "array", "items": { "type": "object", "required": ["source", "byteStart", "byteEnd", "op"], "properties": { "source": { "type": "object", "required": ["start", "end"], "properties": { "start": { "type": "integer", "minimum": 0 }, "end": { "type": "integer", "minimum": 0 } } }, "expandedFrom": { "type": "object", "required": ["start", "end"], "properties": { "start": { "type": "integer", "minimum": 0 }, "end": { "type": "integer", "minimum": 0 } } }, "optimizedFrom": { "type": "array", "minItems": 2, "maxItems": 4096, "items": { "type": "object", "required": ["op", "source"], "properties": { "op": { "type": "string" }, "source": { "$ref": "#/$defs/span" }, "expandedFrom": { "$ref": "#/$defs/span" } } } }, "byteStart": { "type": "integer", "minimum": 0 }, "byteEnd": { "type": "integer", "minimum": 1 }, "op": { "type": "string" } } } }, "staticResources": { "type": "object", "required": ["scriptBytes", "opcodes", "maxStackItems", "helperExpansions", "dynamicSignatureChecks"], "properties": { "scriptBytes": { "type": "integer", "minimum": 1, "maximum": 8192 }, "opcodes": { "type": "integer", "minimum": 1, "maximum": 4096 }, "maxStackItems": { "type": "integer", "minimum": 0 }, "helperExpansions": { "type": "integer", "minimum": 0, "maximum": 256 }, "dynamicSignatureChecks": { "type": "integer", "minimum": 0 } } } } } },
17
+ "policy": { "type": "object", "required": ["branches", "paths", "root", "treeRecipe"], "additionalProperties": false, "properties": { "branches": { "type": "array", "minItems": 1, "maxItems": 1, "items": { "$ref": "#/$defs/h32" } }, "paths": { "const": [[0]] }, "root": { "$ref": "#/$defs/h32" }, "treeRecipe": { "const": "sorted-leaves-largest-power-split-v1" } } },
18
+ "build": { "$ref": "#/$defs/buildGraph" },
19
+ "links": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/linkedContract" } },
20
+ "compiler": { "description": "The compiler that produced the artifact; a runtime rejects an artifact from another compiler or version.", "type": "object", "required": ["name", "version", "edition", "optimizerVersion"], "additionalProperties": false, "properties": { "name": { "type": "string", "minLength": 1 }, "version": { "type": "string", "minLength": 1 }, "edition": { "enum": ["2026.1", "2026.2"] }, "optimizerVersion": { "enum": ["none", "v1", "v2"] } } },
21
+ "source": { "description": "What the artifact was compiled from: one source file, or for package builds the linked program after import resolution; with the constructor values of every tree. A runtime recompiles it and rejects the artifact unless every field matches.", "oneOf": [
22
+ { "type": "object", "required": ["text", "file", "bindings"], "additionalProperties": false, "properties": { "text": { "type": "string" }, "file": { "type": "string" }, "bindings": { "$ref": "#/$defs/sourceBindings" } } },
23
+ { "type": "object", "required": ["program", "bindings"], "additionalProperties": false, "properties": { "program": { "type": "object", "required": ["helpers", "contracts"], "additionalProperties": false, "properties": { "languageVersion": { "const": 1 }, "edition": { "enum": ["2026.1", "2026.2"] }, "optimizerVersion": { "enum": ["none", "v1", "v2"] }, "states": { "type": "array", "items": { "type": "object" } }, "helpers": { "type": "array", "items": { "type": "object" } }, "contracts": { "type": "array", "minItems": 1, "items": { "type": "object" } } } }, "bindings": { "$ref": "#/$defs/sourceBindings" } } }
24
+ ] }
25
+ },
26
+ "allOf": [
27
+ { "if": { "required": ["languageVersion"] }, "then": { "properties": { "methods": { "items": { "required": ["invocation"] } } } } },
28
+ { "if": { "properties": { "kind": { "const": "token" } }, "required": ["kind"] },
29
+ "then": { "properties": { "methods": { "items": { "required": ["invocation", "mintAmountParam"], "properties": { "invocation": { "const": "mint" } } } } } } },
30
+ { "if": { "properties": { "kind": { "const": "contract" } }, "required": ["kind"] },
31
+ "then": { "properties": { "methods": { "items": { "properties": { "invocation": { "const": "spend" } }, "not": { "required": ["mintAmountParam"] } } } } } }
32
+ ],
33
+ "$defs": {
34
+ "sourceBindings": { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { "type": ["string", "boolean"] } } },
35
+ "name": { "type": "string", "pattern": "^[A-Za-z_][A-Za-z_0-9]*$" },
36
+ "h32": { "type": "string", "pattern": "^[0-9a-f]{64}$" },
37
+ "valueType": { "type": "string", "pattern": "^(PublicKey|Signature|Bytes32|Bytes\\([1-9][0-9]*\\)|Int|Amount|TokenId|TxId|StateRoot|ChainId|SigHash|BranchRoot|Bool|MethodLeafHash|ContractRootHash)$" },
38
+ "typedName": { "type": "object", "required": ["name", "type"], "additionalProperties": false, "properties": { "name": { "$ref": "#/$defs/name" }, "type": { "$ref": "#/$defs/valueType" } } },
39
+ "span": { "type": "object", "required": ["start", "end"], "additionalProperties": false, "properties": { "start": { "type": "integer", "minimum": 0 }, "end": { "type": "integer", "minimum": 0 }, "module": { "$ref": "#/$defs/moduleId" } } },
40
+ "moduleId": { "type": "string", "pattern": "^(?:[a-z_][a-z0-9_]{0,63}@[0-9]+\\.[0-9]+\\.[0-9]+|[A-Za-z0-9][A-Za-z0-9.-]*(?:/[A-Za-z0-9][A-Za-z0-9._-]*)+@(?:v[0-9]+\\.[0-9]+\\.[0-9]+|[0-9a-f]{40}))/[A-Za-z_][A-Za-z0-9_]*(?:/[A-Za-z_][A-Za-z0-9_]*)*$" },
41
+ "packageId": { "type": "string", "pattern": "^(?:[a-z_][a-z0-9_]{0,63}@[0-9]+\\.[0-9]+\\.[0-9]+|[A-Za-z0-9][A-Za-z0-9.-]*(?:/[A-Za-z0-9][A-Za-z0-9._-]*)+@(?:v[0-9]+\\.[0-9]+\\.[0-9]+|[0-9a-f]{40}))$" },
42
+ "buildGraph": { "type": "object", "required": ["schema", "compiler", "target", "root", "lockDigest", "packages", "modules", "digest"], "additionalProperties": false, "properties": {
43
+ "interfaceVersion": {"const": "lotus/module-interface/lc1"},
44
+ "instances": {"type": "array", "items": {"type": "object", "required": ["name", "template", "bindings", "root"], "additionalProperties": false, "properties": {"name": {"$ref": "#/$defs/name"}, "template": {"type": "string"}, "bindings": {"type": "array", "items": {"type": "object", "required": ["name", "type", "value"], "additionalProperties": false, "properties": {"name": {"$ref": "#/$defs/name"}, "type": {"$ref": "#/$defs/valueType"}, "value": {"type": ["string", "boolean"]}}}}, "root": {"$ref": "#/$defs/h32"}}}},
45
+ "schema": { "const": "lotus/build-graph/1" },
46
+ "compiler": { "type": "object", "required": ["name", "version", "profile"], "additionalProperties": false, "properties": { "name": { "type": "string" }, "version": { "type": "string" }, "profile": { "enum": ["optimized", "unoptimized"] } } },
47
+ "target": { "const": "P01-P02-P03-candidate-2026-10-14" },
48
+ "root": { "type": "object", "required": ["package", "module"], "additionalProperties": false, "properties": { "package": { "$ref": "#/$defs/packageId" }, "module": { "$ref": "#/$defs/moduleId" } } },
49
+ "lockDigest": { "$ref": "#/$defs/h32" },
50
+ "packages": { "type": "array", "minItems": 1, "items": { "type": "object", "required": ["id", "name", "version", "root", "treeDigest", "dependencies"], "additionalProperties": false, "properties": { "id": { "$ref": "#/$defs/packageId" }, "name": { "type": "string" }, "version": { "type": "string" }, "root": { "type": "string" }, "treeDigest": { "$ref": "#/$defs/h32" }, "dependencies": { "type": "object", "additionalProperties": { "$ref": "#/$defs/packageId" } } } } },
51
+ "modules": { "type": "array", "minItems": 1, "items": { "type": "object", "required": ["id", "package", "path", "file", "sourceDigest", "interfaceDigest", "exports", "imports"], "additionalProperties": false, "properties": { "id": { "$ref": "#/$defs/moduleId" }, "package": { "$ref": "#/$defs/packageId" }, "path": { "type": "string" }, "file": { "type": "string" }, "sourceDigest": { "$ref": "#/$defs/h32" }, "interfaceDigest": { "$ref": "#/$defs/h32" }, "exports": { "type": "array", "items": { "type": "object", "required": ["name", "signature", "digest"], "additionalProperties": false, "properties": { "name": { "$ref": "#/$defs/name" }, "signature": { "type": "string" }, "digest": { "$ref": "#/$defs/h32" } } } }, "imports": { "type": "array", "items": { "$ref": "#/$defs/moduleId" } } } } },
52
+ "digest": { "$ref": "#/$defs/h32" } } },
53
+ "linkedContract": { "type": "object", "required": ["name", "kind", "package", "module", "packageDigest", "root", "methods"], "additionalProperties": false, "properties": {
54
+ "name": { "$ref": "#/$defs/name" }, "kind": { "enum": ["contract", "token"] }, "package": { "$ref": "#/$defs/packageId" }, "module": { "$ref": "#/$defs/moduleId" },
55
+ "packageDigest": { "$ref": "#/$defs/h32" }, "root": { "$ref": "#/$defs/h32" },
56
+ "methods": { "type": "array", "minItems": 1, "maxItems": 16, "items": { "type": "object", "required": ["name", "leaf"], "additionalProperties": false, "properties": { "name": { "$ref": "#/$defs/name" }, "leaf": { "$ref": "#/$defs/h32" } } } } } }
57
+ }
58
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://givelotus.org/schemas/lotus/payment-artifact/1",
4
+ "title": "Lotus V2 Payment compiler artifact candidate",
5
+ "type": "object",
6
+ "required": ["schema", "target", "contract", "constructor", "methods", "scriptHex", "policy", "sourceMap", "staticResources"],
7
+ "additionalProperties": false,
8
+ "properties": {
9
+ "schema": { "const": "lotus/payment-artifact/1" },
10
+ "target": { "const": "P01-P02-P03-candidate-2026-10-14" },
11
+ "contract": { "type": "string", "pattern": "^[A-Za-z_][A-Za-z_0-9]*$" },
12
+ "constructor": { "type": "array", "minItems": 1, "maxItems": 1, "items": { "type": "object", "required": ["name", "type", "bytes"], "additionalProperties": false, "properties": { "name": { "type": "string" }, "type": { "const": "PublicKey" }, "bytes": { "const": 32 } } } },
13
+ "methods": { "type": "array", "minItems": 1, "maxItems": 1, "items": { "type": "object", "required": ["name", "args", "path"], "additionalProperties": false, "properties": { "name": { "const": "spend" }, "args": { "type": "array", "minItems": 1, "maxItems": 1, "items": { "type": "object", "required": ["name", "type", "bytes"], "additionalProperties": false, "properties": { "name": { "type": "string" }, "type": { "const": "Signature" }, "bytes": { "const": [64, 64] } } } }, "path": { "const": [0] } } } },
14
+ "scriptHex": { "type": "string", "pattern": "^20[0-9a-f]{64}bb$" },
15
+ "policy": { "type": "object", "required": ["branches", "paths", "leaf"], "additionalProperties": false, "properties": { "branches": { "type": "array", "minItems": 1, "maxItems": 1, "items": { "type": "string", "pattern": "^[0-9a-f]{64}$" } }, "paths": { "const": [[0]] }, "leaf": { "type": "string", "pattern": "^[0-9a-f]{64}$" } } },
16
+ "sourceMap": { "type": "array", "minItems": 2, "maxItems": 2, "items": { "type": "object", "required": ["source", "byteStart", "byteEnd", "op"], "additionalProperties": false, "properties": { "source": { "type": "object", "required": ["start", "end"], "additionalProperties": false, "properties": { "start": { "type": "integer", "minimum": 0 }, "end": { "type": "integer", "minimum": 0 } } }, "byteStart": { "type": "integer", "minimum": 0 }, "byteEnd": { "type": "integer", "minimum": 1 }, "op": { "enum": ["PUSH_32", "CHECKSIG"] } } } },
17
+ "staticResources": { "type": "object", "required": ["scriptBytes", "opcodes", "maxStackItems", "dynamicSignatureCheck"], "additionalProperties": false, "properties": { "scriptBytes": { "const": 34 }, "opcodes": { "const": 2 }, "maxStackItems": { "const": 2 }, "dynamicSignatureCheck": { "const": true } } }
18
+ }
19
+ }