Source: docs/lotus-v2/lotus-language.md
🎯 Why: Specify the Lotus contract language, compiler lowering to Lotus VM bytecode, Artifact v2 provenance, and the TypeScript/Python transaction runtime API.

In Practice: Developers write typed contracts and tokens with version pragmas, locked packages, and generated wallet bindings that handle signing modes and parabolic fees automatically.

Under the Hood: Pratt parser -> Forth-like stack IR -> frozen v1/v2 bounded symbolic optimizer -> sorted-leaf MAST policy roots, CABI-07/08 offline packages, and deterministic artifact recompilation.

Lotus Language Reference

On this page

Status: active development specification, tracking tools/lotus-compiler and targeting the Lotus VM (P03 bytecode) and Script and wallet ABI. Every complete lotus contract and token listing in this document is compile-checked in CI against @lotus/compiler.


1. Overview & Architecture

The Lotus contract language is a statically typed, deterministic smart-contract language that compiles directly to Lotus VM (P03) bytecode and MAST policy trees.

Mental model

Quick example

pragma edition "2026.2";
pragma optimizer "v2";

function digest(x: Bytes32): Bytes32 {
    return sha256(x);
}

contract Vault<owner: PublicKey, target: Bytes32> {
    function spend(sig: Signature) {
        require(checksig(sig, owner));
    }

    function reveal(data: Bytes32) {
        require(digest(data) == target);
    }
}

2. Lexical Structure, Grammar & Operator Precedence

2.1 Lexical rules

Element Syntax & Rules
Source limit Maximum 65,536 UTF-8 bytes (E0002). All Artifact v2 source spans use UTF-8 byte offsets.
Whitespace Spaces, tabs, carriage returns, and newlines separate tokens.
Comments Line comments // ... to end of line; non-nested block comments /* ... */ (E0003 if unterminated).
Identifiers [A-Za-z_][A-Za-z_0-9]*. Must be valid in both TypeScript and Python namespaces; reserved keywords are rejected (E0115). Method names within a contract/token must be unique case-insensitively (E0203).
Integer literals Unsigned decimal digits [0-9]+ (with optional unary - for negative constants) in signed 128-bit range [-2^127, 2^127 - 1] (E0413). Hex literals and _ digit separators are not part of .lotus source; fixed-width byte/hash constants are passed via typed constructor bindings.
Boolean literals true, false (encoded as canonical 16-byte N(1) / N(0)).
String literals "..." without escapes or newlines (E0004). Used only in pragma directives and quoted import module selectors, never as runtime values.

2.2 Top-level module structure

A .lotus module is parsed top-to-bottom in strict order (E0135 / E0113 if out of order):

  1. Optional version pragmas (must precede imports and declarations; duplicates rejected with E0136):
  2. pragma edition "2026.1"; (default) or pragma edition "2026.2"; (strict nominal 32-byte hash typing).
  3. pragma optimizer "v1"; (default, frozen), pragma optimizer "v2";, or pragma optimizer "none";.
  4. Because MAST roots commit to exact script bytes, pinning both pragmas guarantees identical roots across compiler upgrades. Any conflict with CompileOptions or lotus.toml fails closed (E0133 / E0134).
  5. Optional import declarations (package builds via compilePackage only; single-file compileContract rejects import with E0121):
  6. import ALIAS::path::to::module::{name, other as local};
  7. import ALIAS::path::to::module as m; (referenced via m::name(...), m::Contract, or m::Contract.method)
  8. ALIAS is a dependency alias from lotus.toml, the keyword package (same package), or a quoted module selector ("host/owner/[email protected]").
  9. Declarations with optional visibility modifier (private by default; package for same-package access; export for cross-package access; explicit private keyword requires languageVersion: 1):
  10. State schema: state [separate | inline] Name { field1: T1, ... } (1..64 fields; defaults to separate).
  11. Pure helper: function name(p1: T1, ...): ReturnType { ... } (inlined at call sites; never emitted as a VM call).
  12. Contract tree: contract Name<c1: T1, ...> { function method(...) { ... } ... } (constructor list <...> is optional; methods execute in spend invocation context; LC-1 languageVersion: 1 uses entry instead of function).
  13. Token tree: token Name<c1: T1, ...> { function mint(amount: Amount, ...) { ... } ... } (MAST root is the 32-byte TokenId; the first parameter must be Amount (E0118), pushed by the node as the positive mint delta and omitted from witness method.args; LC-1 uses mint instead of function).

2.3 Structural & compiler limits

Limit Cap Diagnostic
Source size 65,536 UTF-8 bytes E0002
Methods per contract or token 16 E0117
State fields per state declaration 1..64 E0107
Statements per block 256 E0107
Expression nesting depth 64 (1,024 Pratt steps) E0105
Control nesting depth (if / for) 16 E0106
for loop nesting depth 2 E0108
Helper expansion count / call depth 256 expansions / depth 16 E0703 / E0503 / E0706
Compiled method script size 8,192 bytes E0701
Compiled method opcode count 4,096 opcodes E0702

2.4 Pratt operator precedence & associativity

Expressions are parsed by a Pratt (nud / led) parser (src/parser.ts). Higher binding power (BP) binds more tightly. Parentheses (...) override precedence.

BP Category Operators Associativity Operand & Result Types
80 Postfix a[i], a.field, a.method(...) Left tx.inputs[Int] → InputIndex; tx.outputs[Int] → OutputIndex; member/method access
70 Unary prefix -x, !x Right -Int → Int; !Bool → Bool
60 Multiplicative *, /, % Left Int/Amount → Amount (if either is Amount) else Int
50 Additive +, - Left Int/Amount → Amount (if either is Amount) else Int
40 Relational <, <=, >, >= Left Int/Amount → Bool
30 Equality ==, != Left Comparable types (see §3.2) → Bool
20 Logical AND && Left Bool, Bool → Bool (short-circuit IF/ELSE/ENDIF; split at top level of require(...))
10 Logical OR || Left Bool, Bool → Bool (short-circuit NOT IF/ELSE/ENDIF)

Note on bitwise operations: Lotus does not have infix bitwise operators (~, &, |, ^, <<). Byte-level bitwise operations are explicit builtin calls: bit_not(x), bit_and(a, b), bit_or(a, b), bit_xor(a, b), and bit_shl(x, shift).


3. Type System & Zero-Cost Conversions

3.1 Value types

Category Type Wire / VM Representation Binding Format & Notes
Scalar Int 16-byte signed LE int128 (-2^127 .. 2^127 - 1) Canonical decimal string or bigint in constructor bindings.
Scalar Amount 16-byte signed LE int128 (consensus MoneyRange 0 .. 2^62 on wire) Coin, output, and mint quantities in atoms. Interoperates with Int in arithmetic and comparisons (result widens to Amount in + - * / %).
Scalar Bool Canonical 16-byte N(0) or N(1) JSON true / false in constructor bindings.
Bytes Bytes32 Exact 32-byte string 64-char lowercase hex. Raw 32-byte values (sha256, hash256, blake3, hashlocks, salts).
Bytes Bytes(N) Byte string of length 0 .. N (1 <= N <= 8192) Even-length lowercase hex up to N bytes.
Crypto PublicKey 32-byte x-only BIP-340 secp256k1 point Validated on curve via lift_x at bind time; 64-char lowercase hex.
Crypto Signature 64-byte (FULL / ABSTAIN) or 65-byte (partial mode) BIP-340 signature Witness argument; runtime supports FULL, OWN_INPUT_ALL_OUTPUTS, OWN_INPUT_ONE_OUTPUT, and ABSTAIN (64 zero bytes).
Handle InputIndex Stack Int index into tx.inputs Produced by for inp in tx.inputs or tx.inputs[k]. Cannot be a parameter type.
Handle OutputIndex Stack Int index into tx.outputs Produced by for out in tx.outputs or tx.outputs[k]. Cannot be a parameter type.
Tagged Hash TxId Exact 32-byte transaction ID Produced by tx.id, this.coin.txid, inp.txid (in "2026.2").
Tagged Hash StateRoot Exact 32-byte canonical state commitment Produced by inp.state_root, out.state_root, state_hash(...), StateName.hash(...) (in "2026.2").
Tagged Hash ChainId Exact 32-byte chain identifier Produced by tx.chain_id (in "2026.2").
Tagged Hash SigHash Exact 32-byte transaction sighash digest Produced by sighash(mode) (in "2026.2").
Tagged Hash TokenId Exact 32-byte token MAST root Produced by this.root (in a token), contract_root(Tok), *.token_id.
Tagged Hash BranchRoot Exact 32-byte MAST branch root Nominal alias of ContractRootHash; produced by contract_root(C) and this.root (in a contract); accepted by requires_branch, exclusive_branch, continues_branch.
Tagged Hash ContractRootHash Exact 32-byte MAST branch root Interchangeable with BranchRoot in all editions.
Tagged Hash MethodLeafHash Exact 32-byte P02 method leaf hash Produced by leaf_hash(Contract.method).

3.2 Edition "2026.1" vs "2026.2" & zero-cost conversions

All conversions between tagged hash types and Bytes32 are purely compile-time type checks that emit 0 VM instructions and consume 0 cu:

Nominal hash types are preserved in artifact-v2 ABI metadata and generated TypeScript/Python bindings so wallets and explorers can format TxIds, resolve TokenId symbols, recognize std/ BranchRoots, and verify ChainIds before signing.

pragma edition "2026.2";
pragma optimizer "v2";

state inline VoucherState {
    nonce: Int,
}

function voucher_digest(chain: ChainId, txid: TxId, next_state: StateRoot): Bytes32 {
    return blake3(cat(cat(bytes32(chain), bytes32(txid)), bytes32(next_state)));
}

contract OutpointVoucher<
    issuer: PublicKey,
    expected_chain: ChainId,
    expected_txid: TxId
> {
    function redeem(sig: Signature, next_nonce: Int, expected_state: StateRoot) {
        require(tx.chain_id == expected_chain);
        require(this.coin.txid == expected_txid);
        require(this.coin.state_root == expected_state);

        require(
            checkdatasig(
                sig,
                voucher_digest(tx.chain_id, this.coin.txid, VoucherState.hash(next_nonce)),
                issuer,
                0
            )
        );
        require(VoucherState.matches(tx.outputs[0], next_nonce));
    }
}

4. Statements & Control Flow

4.1 Method statements (contract / token bodies)

Statement Syntax Semantics & Lowering
Requirement require(expr); Evaluates expr: Bool and aborts if false (VERIFY). Top-level require(a && b) is split into sequential requirements so CHECKSIG/EQUAL/NUMEQUAL fuse cleanly into *VERIFY opcodes.
Conditional if expr { ... } [else { ... }] expr must be Bool (E0404). Lowers to IF ... ELSE ... ENDIF. Parentheses around expr are optional.
Bounded loop for inp in tx.inputs { ... } / for out in tx.outputs { ... } Lowers to TXINPUTCOUNT ENUMERATE ... DROP ENDENUMERATE or TXOUTPUTCOUNT ENUMERATE ... DROP ENDENUMERATE. Maximum 2 nested loops (E0108), bounded by consensus C06 (<= 256 inputs/outputs). Loop variable has type InputIndex or OutputIndex and cannot shadow an existing binding (E0206).
Early loop exit break; Allowed only inside a for loop (E0124) as the final statement of its block. Drops block-local stack items and emits N(1) N(1) BREAK.
Multi-return binding let (a, b) = builtin(...); Binds the two stack outputs of mul128_wide, add_carry, sub_carry, split, less_swap, or tx_token_balance (E0125). Cannot shadow an existing binding (E0208).
Numeric local init/update x = expr;, x += expr;, x -= expr; x must be Int or Amount (E0408). A new local must be initialized at method top level with = (E0410) so its stack slot exists across branches and loops; updates inside if/for mutate that slot via PICK/ADD/SUB/ROLL.

4.2 Helper statements (function name(...): T)

Pure helpers inline completely at call sites (parameters use hygienic call-by-name substitution; let evaluates once and binds a stack slot). The VM never executes a function call.


5. Builtins, Introspection & VM Opcode Reference

5.1 Transaction & invocation introspection

Builtin / Member Receiver / Args Return Type(s) Emitted P03 Opcode(s) Notes / Safety Guards
tx.id — TxId (Bytes32 in 2026.1) TXID (0xce) Current transaction ID.
tx.chain_id — ChainId (Bytes32 in 2026.1) CHAINID (0xcf) 32-byte network/chain domain separator; bind in off-chain vouchers to block cross-network replay.
tx.mint_count — Int TXMINTCOUNT (0xcb) Number of mint inputs in the transaction.
tx.inputs[k] k: Int InputIndex (pushes index k) Pratt-indexed input handle; k checked against bounds by downstream opcodes.
tx.outputs[k] k: Int OutputIndex (pushes index k) Pratt-indexed output handle; ideal for injective O(1) payout layouts (tx.outputs[2 * this.input_index]).
tx_token_balance(asset) asset: TokenId (Amount, Amount) TXTOKENBALANCE (0xec) Multi-return let (total_in, total_out) = tx_token_balance(asset);. Net minted delta is total_out - total_in.
tx_token_in(asset) asset: TokenId Amount TXTOKENBALANCE; DROP Sum of input coin values for asset.
tx_token_out(asset) asset: TokenId Amount TXTOKENBALANCE; NIP Sum of output coin values for asset.
this.root — ContractRootHash (contract) / TokenId (token) BRANCHROOT (0xf2) Active branch root (in contract) or active token ID (in token).
this.input_index — Int INPUTINDEX (0xd0) 0-based index of the currently executing input.
this.active_branch_index — Int ACTIVEBRANCHINDEX (0xf5) 0-based index of the active branch within the spending coin's policy.
this.coin.value spend only Amount INPUTINDEX; UTXOVALUE (0xd6) Rejected in token mint methods (E0411).
this.coin.token_id spend only TokenId INPUTINDEX; UTXOTOKENID (0xd7) All-zero 32 bytes for native XPI. Rejected in mints (E0411).
this.coin.txid spend only TxId (Bytes32 in 2026.1) INPUTINDEX; OUTPOINTTXID (0xd2) Outpoint transaction ID of the coin being spent.
this.coin.vout spend only Int INPUTINDEX; OUTPOINTINDEX (0xd3) Outpoint output index of the coin being spent.
this.coin.path_index spend only Int INPUTINDEX; INPUTPATHINDEX (0xd5) Chosen MAST path index for this input.
this.coin.flags spend only Int INPUTINDEX; UTXOFLAGS (0xde) Spent coin output flags (0 native, 1 token, 4 native+state, 5 token+state).
this.coin.state_root spend only StateRoot (Bytes32 in 2026.1) INPUTINDEX; UTXOSTATEROOT (0xee) Inline HAS_STATE 32-byte commitment on the spent coin.
this.coin.branch(k) / branch_count() k: Int / — Bytes32 / Int INPUTINDEX; UTXOBRANCH (0xd9) / UTXOBRANCHCOUNT (0xd8) Reads branch root k or total branch count of the spent coin.
this.coin.path(k) / path_count() k: Int / — Bytes(8192) / Int INPUTINDEX; UTXOPATH (0xdb) / UTXOPATHCOUNT (0xda) Reads path k or total path count of the spent coin.
inp.is_spend inp: InputIndex Bool INPUTFLAGS; N(1); NUMEQUAL Always guard inp.coin.*, inp.txid, inp.vout, inp.requires_branch(...) with inp.is_spend because mint inputs have no spent UTXO.
inp.txid / inp.vout / inp.path_index inp: InputIndex TxId / Int / Int OUTPOINTTXID / OUTPOINTINDEX / INPUTPATHINDEX Also accessible via inp.coin.*. Guard with inp.is_spend.
inp.value / inp.token_id / inp.flags / inp.state_root inp: InputIndex Amount / TokenId / Int / StateRoot UTXOVALUE / UTXOTOKENID / UTXOFLAGS / UTXOSTATEROOT Also accessible via inp.coin.*. Guard with inp.is_spend.
inp.branch(k) / branch_count() / path(k) / path_count() inp: InputIndex Bytes32 / Int / Bytes(8192) / Int UTXOBRANCH / UTXOBRANCHCOUNT / UTXOPATH / UTXOPATHCOUNT Also accessible via inp.coin.*. Guard with inp.is_spend.
inp.requires_branch(root) inp: InputIndex, root: BranchRoot Bool UTXOREQUIRESBRANCH (0xdd) True iff every spending path of inp's coin requires root. Guard with inp.is_spend.
out.value / out.token_id / out.flags / out.state_root out: OutputIndex Amount / TokenId / Int / StateRoot OUTPUTVALUE (0xe1) / OUTPUTTOKENID (0xe2) / OUTPUTFLAGS (0xe0) / OUTPUTSTATEROOT (0xef) Inspects transaction output out.
out.branch(k) / branch_count() / path(k) / path_count() out: OutputIndex Bytes32 / Int / Bytes(8192) / Int OUTPUTBRANCH (0xe4) / OUTPUTBRANCHCOUNT (0xe3) / OUTPUTPATH (0xe6) / OUTPUTPATHCOUNT (0xe5) Inspects output MAST policy structure.
out.requires_branch(root) out: OutputIndex, root: BranchRoot Bool OUTPUTREQUIRESBRANCH (0xe8) True iff every spending path of out requires root (covenant propagation).
out.exclusive_branch(root) out: OutputIndex, root: BranchRoot Bool OUTPUTEXCLUSIVEBRANCH (0xe9) True iff out has root as its sole branch (branches == [root], paths == [[0]]). Prevents ransom-locking payouts with extra unspendable branches.
out.continues_branch(root) out: OutputIndex, root: BranchRoot Bool OUTPUTCONTINUESBRANCH (0xea) True iff out preserves the policy structure of this.coin with the active branch replaced by root (and all other paths/branches intact).

Lowered transaction opcodes: TXINPUTCOUNT (0xc9) and TXOUTPUTCOUNT (0xca) are emitted automatically by for inp in tx.inputs and for out in tx.outputs. Lock-time bounds are enforced via check_lock (CHECKLOCKTIMEVERIFY) and check_sequence (CHECKSEQUENCEVERIFY).

5.2 Arithmetic, comparisons & wide math

Builtin / Operator Signature Return Type(s) Emitted P03 Opcode(s) Notes / Safety Guards
+, -, *, /, % (Num, Num) Amount or Int ADD (0x9e), SUB (0x9f), MUL (0xa0), DIV (0xa1), MOD (0xa2) Checked int128 arithmetic (overflow/div-by-zero aborts). Guard dynamic / and % divisors to avoid W0704.
Unary - (Int) Int NEGATE (0x9a) Checked negation (-INT_MIN aborts).
==, != (T, T) Bool EQUAL (0x91), EQUAL; NOT EQUAL; VERIFY fuses to EQUALVERIFY (0x92).
<, >, <=, >= (Num, Num) Bool LESSTHAN (0xa9), GREATERTHAN (0xaa), LESSTHANOREQUAL (0xab), GREATERTHANOREQUAL (0xac) Signed int128 comparisons.
!, &&, || (Bool) / (Bool, Bool) Bool NOT (0x9c), short-circuit IF/ELSE/ENDIF Short-circuiting prevents executing right-hand side on failure (e.g., inp.is_spend && inp.requires_branch(...)).
abs(x) (T: Int | Amount) T ABS (0x9b) Checked absolute value.
min(a, b) / max(a, b) (Num, Num) Amount or Int MIN (0xad) / MAX (0xae) Signed minimum / maximum.
within(x, lo, hi) (Num, Num, Num) Bool WITHIN (0xaf) Half-open range check lo <= x && x < hi.
sqrt(x) (Num) Int SQRT (0xb4) Exact integer floor square root (x >= 0; negative aborts).
log(x) (Num) Int LOG (0xb3) Integer floor base-2 logarithm (x > 0; non-positive aborts).
mulpow2(x, k) (T: Num, k: Int) T MULPOW2 (0xa3) Checked x * 2^k (arithmetic right shift for negative k).
mul128_wide(a, b) (Num | Bytes, Num | Bytes) (Bytes(8192), Bytes(8192)) MUL128_WIDE (0xb2) 2-tuple: let (hi, lo) = mul128_wide(a, b);. Exact 256-bit product as two 16-byte limbs—eliminates overflow in AMM constant-product math.
add_carry(a, b, cin) (Num | Bytes, Num | Bytes, Int) (Bytes(8192), Int) ADDCARRY (0xb0) 2-tuple: let (sum, carry_out) = add_carry(a, b, cin);. Multi-limb addition.
sub_carry(a, b, bin) (Num | Bytes, Num | Bytes, Int) (Bytes(8192), Int) SUBCARRY (0xb1) 2-tuple: let (diff, borrow_out) = sub_carry(a, b, bin);. Multi-limb subtraction.
less_swap(a, b) (Bytes, Bytes) (Bytes, Bytes) LESSSWAP (0x93) 2-tuple: let (smaller, larger) = less_swap(a, b);. Unsigned lexicographic byte ordering (used for 256-bit limb comparison & sorted Merkle pairs).

5.3 Bytes, bitwise & conversions

Builtin Signature Return Type(s) Emitted P03 Opcode(s) Notes
cat(a, b) (Bytes, Bytes) Bytes(8192) CAT (0x88) Concatenates two byte strings (aborts if result exceeds 8,192 bytes).
split(raw, offset) (Bytes, Int) (Bytes(8192), Bytes(8192)) SPLIT (0x89) 2-tuple: let (left, right) = split(raw, offset);. Splits at byte index offset.
size(b) (Bytes) Int SIZE; NIP (0x8c, 0x7b) Byte length of b.
num2bin(x, width) (Num, Int) Bytes(8192) NUM2BIN (0x8a) Encodes signed integer x into width little-endian bytes (e.g., 16 for canonical int128).
bin2num(b) (Bytes) Int BIN2NUM (0x8b) Decodes little-endian signed integer bytes to Int.
num_bytes(x) (Int) Bytes(16) ZERO; ADD Validates x as canonical 16-byte P03 integer and exposes it as Bytes(16).
bit_not(b) (Bytes) Bytes(8192) INVERT (0x8d) Bitwise NOT over every byte.
bit_and(a, b) / bit_or(a, b) / bit_xor(a, b) (Bytes, Bytes) Bytes(8192) AND (0x8e) / OR (0x8f) / XOR (0x90) Bitwise AND / OR / XOR on equal-length byte strings.
bit_shl(b, shift) (Bytes, Int) Bytes(8192) RAWLEFTBITSHIFT (0x94) Logical left bit shift on raw bytes.
bytes32(x) (Bytes32 | TaggedHash) Bytes32 (none — 0 bytes, 0 cu) Zero-cost downcast from any 32-byte tagged hash to raw Bytes32.
TxId(b), StateRoot(b), ChainId(b), SigHash(b), TokenId(b), BranchRoot(b) (Bytes32) Corresponding tagged hash (none — 0 bytes, 0 cu) Zero-cost promotion from Bytes32 at explicit trust boundaries.

5.4 Cryptography, commitments & signatures

Builtin Signature Return Type Emitted P03 Opcode(s) Notes
checksig(sig, pk) (Signature, PublicKey) Bool CHECKSIG (0xbb) BIP-340 Schnorr transaction signature verification. Fuses with VERIFY → CHECKSIGVERIFY (0xbc). 64 zero bytes (ABSTAIN) returns false without aborting.
checkdatasig(sig, msg, pk, alg) (Bytes, Bytes, Bytes, Int) Bool CHECKDATASIG (0xbd) Verifies signature over arbitrary data (alg = 0 for BIP-340 Schnorr). Used for oracle attestations and off-chain mint vouchers.
sighash(mode) (Int) SigHash (Bytes32 in 2026.1) SIGHASH (0xc2) Computes the active input's transaction sighash digest for mode (0 = FULL, 1 = OWN_INPUT_ALL_OUTPUTS, 2 = OWN_INPUT_ONE_OUTPUT).
sha256(b) / hash256(b) / blake3(b) (Bytes) Bytes32 SHA256 (0xb8) / HASH256 (0xb9) / BLAKE3 (0xba) Standard cryptographic digests (hash256 = double SHA-256).
leaf_hash(Contract.method) Compile-time symbol MethodLeafHash PUSH_32 <hash> Compile-time P02 method leaf hash of Contract.method; schedules dependency compilation.
leaf_hash_bytes(script) (Bytes) Bytes32 LEAFHASH (0xbe) Runtime P02 tagged branch leaf hash over arbitrary script bytes.
node_hash(a, b) (Bytes32, Bytes32) Bytes32 NODEHASH (0xbf) Runtime P02 tagged sorted Merkle interior node hash.
merkle_root_sorted(leaf, proof, sel) (Bytes32, Bytes, Int) Bytes32 MERKLEROOT_SORTED (0xc0) Computes sorted Merkle root from leaf, concatenated 32-byte sibling proof, and domain sel.
merkle_root_indexed(leaf, key, proof, sel) (Bytes32, Bytes, Bytes, Int) Bytes32 MERKLEROOT_INDEXED (0xc1) Computes indexed/keyed Merkle root from leaf, key, proof, and domain sel.
contract_root(Tree) / merkle_root(Tree) Compile-time symbol ContractRootHash / TokenId PUSH_32 <root> Compile-time MAST root of contract or token Tree.

5.5 Time locks

Builtin Signature Return Type Emitted P03 Opcode(s) Compile-Time Validation
check_lock(kind, bound) (Int, Int) Bool CHECKLOCKTIMEVERIFY; N(1) (0xf3) Absolute lock: kind must be compile-time constant (E0415) 1 (block height, 0 .. 2^32-1) or 2 (median time past seconds, 0 .. 2^56-1) (E0416/E0417).
check_sequence(kind, bound) (Int, Int) Bool CHECKSEQUENCEVERIFY; N(1) (0xf4) Relative lock (spend methods only, E0418 in mints): kind must be constant 1 (blocks) or 2 (512-second units), constant bound in 0 .. 65535 (E0415–E0417).

5.6 State & output enforcement

Builtin / Sugar Signature Return Type Emitted P03 Opcode(s) Notes
state_hash(b1, ..., bk) 0..64 Bytes args StateRoot (Bytes32 in 2026.1) N(k); STATEHASH (0xc3) Canonical tagged BLAKE3 state commitment over k byte items.
state_verify(root) (StateRoot) (spend only) Bool STATEVERIFY; N(1) (0xed) Verifies this.coin's inline HAS_STATE root equals root (aborts on mismatch; E0411 in mints).
enforce_output(tpl, claim) (Bytes, Int) Bool ENFORCEOUTPUT; N(1) (0xeb) Enforces an output matching serialized template tpl with claim mode claim (aborts if unsatisfied).
S.hash(v1, ..., vk) Typed fields of state S StateRoot (Bytes32 in 2026.1) NUM2BIN 16 (for Int/Amount/Bool) + N(k); STATEHASH Declarative state sugar: automatically encodes scalar fields as 16-byte canonical LE integers.
S.verify(v1, ..., vk) Typed fields of state S (spend only) Bool inline: STATEHASH; STATEVERIFY; N(1)<br>separate: INPUTINDEX; UTXOBRANCHCOUNT; N(2); NUMEQUAL; IF INPUTINDEX; N(1); UTXOBRANCH; ...; EQUAL ELSE ZERO ENDIF Verifies this.coin's current state matches (v1, ..., vk).
S.matches(io, v1, ..., vk) io: InputIndex | OutputIndex + fields Bool inline: OUTPUTSTATEROOT/UTXOSTATEROOT + STATEHASH; EQUAL<br>separate: short-circuit branch_count() == 2 && branch(1) == S.hash(...) Verifies an input or output (including Pratt-indexed tx.outputs[k]) carries state (v1, ..., vk).

Declarative state syntax:

state separate SupplyState {
    issued: Amount,
    locked: Bool,
}

state inline VaultState {
    nonce: Int,
    owner_tag: Bytes32,
}

6. Compilation Pipeline, Packages, Artifact v2, CLI & Runtime

6.1 Compilation pipeline & optimizer editions

  1. Parse (src/parser.ts, src/ast.ts): Lexer + Pratt parser enforcing source/nesting limits and portable identifier rules.
  2. Dependency scheduling (src/scheduler.ts): compileContractAsync schedules method leaves and cross-contract contract_root / leaf_hash dependencies via memoized jobs, rejecting self/mutual cycles (E0801) with declaration spans.
  3. Forth-like stack IR (src/forth-ir.ts): AST lowering emits structured ForthNode instructions (op, number, push, control) tracking stack height, UTF-8 source spans, and inline helper frames.
  4. Versioned bounded symbolic optimizer (src/optimizer.ts):
  5. Peephole fusion: CHECKSIG; VERIFY → CHECKSIGVERIFY, EQUAL; VERIFY → EQUALVERIFY, NUMEQUAL; VERIFY → NUMEQUALVERIFY (v2), ZERO; PICK → DUP, and single-argument straight-line direct consumption (e.g., require(checksig(sig, owner)) → PUSH_32 owner; CHECKSIGVERIFY; N(1), 35 bytes).
  6. Constant folding: Checked int128 arithmetic, canonical Booleans, equality, and hashing over adjacent known literals (constructor bindings and cross-contract hashes stay opaque so MAST roots remain bound).
  7. Symbolic stack & branch facts: Tracks argument identities and proven IF / VERIFY facts across branches while resetting mutable state at loop boundaries.
  8. Version freezing: "v1" (default) is frozen for backwards-compatible MAST roots; "v2" adds constant folding for DIV, MOD (guarding INT_MIN % -1 and / 0), ABS, SQRT, MIN, MAX, CAT (emitting 0x4c PUSHDATA for > 75 or 0 bytes), NUMEQUALVERIFY fusion, and symbolic stack modeling over the full P03 opcode table. "none" (or optimize: false) disables optimization for differential testing.
  9. MAST construction & serialization: Each method script is hashed with P02 Leaf(script). Distinct method leaves (E0207 on collision) are sorted as unsigned little-endian 32-byte hashes and combined via largest-power-of-two splitting (sorted-leaves-largest-power-split-v1) into a single branch root (policy.paths = [[0]]).

6.2 Packages, locks & shared libraries (CABI-07 / CABI-08)

Multi-file projects use lotus.toml (strict TOML subset with [package], [dependencies], [sources], [replace]) and a canonical JSON lockfile lotus.lock (lotus/package-lock/1 for path-only graphs, lotus/package-lock/2 when module paths or [replace] are used).

6.3 Artifact v2 schema & provenance

Compiled contracts emit JSON conforming to lotus/contract-artifact/2 (tools/lotus-compiler/artifact-v2.schema.json):

Top-level field Purpose
schema, target "lotus/contract-artifact/2" and target id ("P01-P02-P03-candidate-2026-10-14").
contract, kind Selected tree name and "contract" or "token".
constructor, bindings Ordered constructor parameter schema and bound values.
methods[] Ordered args, invocation, optional mintAmountParam, scriptHex, leaf, proof, root, UTF-8 sourceMap (with expandedFrom / optimizedFrom), and staticResources (scriptBytes, opcodes, maxStackItems, helperExpansions, dynamicSignatureChecks).
policy { branches: [root], paths: [[0]], root, treeRecipe }.
compiler { name, version, edition, optimizerVersion }.
source Exact source text + bindings (single-file) or linked program AST + bindings (package) so runtimes can recompile and verify every field (verifyArtifactSource) before planning a call.
links, build Optional CABI-08 linked library contracts and CABI-07 lotus/build-graph/1 metadata.

6.4 Compiler CLI & JavaScript / TypeScript API

Package: @lotus/compiler (tools/lotus-compiler/).

CLI Command Purpose
lotus-contract-compile <file.lotus> <options.json> <outDir> [--trace] Compile a single-file contract and emit artifact.json, TypeScript/Python bindings, and optional scheduler-trace.json.
lotus-contract-compile --check <file.lotus> <options.json> Compile + run advisory lints without writing output files.
lotus-contract-compile --emit-ir <file.lotus> <options.json> Print Forth-IR disassembly with optimizedFrom provenance.
lotus-contract-compile --cost <file.lotus> <options.json> Print static script bytes, opcodes, max stack items, signature checks, and staticInvocationCu.
lotus-contract-compile --explain <CODE> Print detailed explanation for a diagnostic code (e.g., W0701, E0415).
lotus-contract-compile --package <dir> <options.json> <outDir> [--trace] Compile a locked package workspace.
lotus-package-lock <dir> [--check] Regenerate or verify lotus.lock from local files only.
lotus-package-fetch <dir> [--vendor] Fetch pinned git dependencies into .lotus/deps or vendor/ and update lotus.lock.
lotus-package-update <dir> <alias>@<selector> Resolve a semver range or branch to an exact tag/commit in lotus.toml and fetch.
Module Entrypoint Key Exports
@lotus/compiler/generic compileContract, compileContractAsync, compileContractWithTrace, verifyArtifactSource, lintContract, generateContractTypeScript, generateContractPython
@lotus/compiler/std STANDARD_CONTRACTS, UNIVERSAL_STANDARD_TRANSFER_RULES_ROOT, compileStandardContract, identifyStandardTemplate, readStandardContractSource
@lotus/compiler/packages compilePackage, generateLock, updateLock, resolveWorkspace, createSpendBundle, verifySpendBundleReproducibility
@lotus/compiler/transaction-runtime prepareTransactionCall, finalizeTransactionCall, estimateTransactionCuAndFee, simulateFeeAndAdjustChange, contractSpendIntent, contractMintIntent, planInvokes, encodeAssetOutput
@lotus/compiler/target-compiler compileTargetContract (explicit target selection beyond default "lotus-v2")

6.5 Transaction runtime, signing modes & fees

@lotus/compiler/transaction-runtime (and its Python peer python/lotus_v2_transaction_runtime.py) plans multi-input spend and mint transactions without performing RPC, signing, or VM execution:

  1. prepareTransactionCall(intent) verifies artifact provenance (recompiling source), validates canonical framing, proof roots, asset accounting (MoneyRange 0 .. 2^62), stateful outputs (flags 4 native+state or 5 token+state with 32-byte stateRoot), and fee floors, returning a TransactionPlan with signatureRequests keyed by inputIndex:witnessIndex:argumentName.
  2. Signing modes: Each Signature argument specifies null/"FULL" (mode 00, 64B), "OWN_INPUT_ALL_OUTPUTS" (mode 01, 65B, spend-only), "OWN_INPUT_ONE_OUTPUT" (mode 02, 65B, spend-only), or "ABSTAIN" (64 zero bytes, no signature request, for $k$-of-$n$ counting).
  3. Fee calculation & change: Enforces C14b byte fees, C14a token-output burn (2 * DUST_LIMIT), and P05 cu-share (default) or consensus rules using FeeParameters. Passing intent.change = { output, index? } sizes change automatically and drops sub-dust change into fees.
  4. finalizeTransactionCall(plan, signatures) attaches 64-byte BIP-340 signatures (appending mode bytes for 01/02) and emits final serialized transaction bytes, txid, and txhash.

7. Diagnostics & Advisory Lints Catalog

7.1 Diagnostic code ranges

Every compiler error (E) and advisory lint warning (W) has a stable 5-character code (src/diagnostics.ts). Up to 20 diagnostics are collected per compile before recovery halts.

Range Phase / Subsystem Representative Codes
E0000–E0004 CLI & Lexer E0001 unsupported character, E0002 source > 64 KiB, E0003 unterminated block comment, E0004 unterminated string
E0101–E0136 Parser, Pragmas & Structural Rules E0101 unexpected token, E0103 unsupported type, E0105–E0108 nesting/budget limits, E0115 invalid binding name, E0117 > 16 methods, E0118 token first param must be Amount, E0121 import requires package build, E0122 for in helper, E0124 break outside loop, E0125 invalid tuple destructuring, E0130–E0136 language version, edition, optimizer, and pragma errors
E0201–E0209 Duplicates & Shadowing E0201–E0204 duplicate param/helper/method/contract, E0205–E0208 shadowing (constructor, loop var, let), E0207 duplicate method leaf (identical scripts), E0209 duplicate state
E0301–E0305 Name Resolution E0301 unbound name, E0302 unknown function, E0303 unknown contract, E0304 unknown method, E0305 unbound/invalid record
E0401–E0418 Typechecking, Semantics & Time Locks E0401–E0407 operand/condition/call/return type mismatches, E0408–E0410 numeric local rules, E0411 mint has no coin, E0412 introspection misuse, E0413 Int out of 128-bit range, E0415–E0418 compile-time check_lock/check_sequence kind/bound/context checks
E0501–E0503 Arity & Recursion E0501 helper arity mismatch, E0502 builtin arity/form mismatch, E0503 recursive helper
E0601–E0605 Compile Options & Bindings E0601 missing contract/bindings, E0602–E0604 missing/unexpected/invalid constructor binding, E0605 unknown selected contract
E0701–E0708 Static Resource & Optimizer Budgets E0701 MAX_SCRIPT_BYTES (> 8192), E0702 opcode budget (> 4096), E0703 helper expansions (> 256), E0704–E0706 inference/dependency budgets, E0707 MAX_ELEMENT_BYTES, E0708 optimizer fuel exhausted
E0801–E0802 Dependency Scheduler E0801 leaf_hash / contract_root dependency cycle, E0802 scheduler limit exceeded
E0901–E0931 Packages, Locks & Program Instances E0901 manifest error, E0907–E0909 lotus.lock missing/mismatch/stale, E0911/E0918 dependency/import cycles, E0914–E0916 visibility errors, E0922 offline cache miss, E0930–E0931 instance binding/cycle errors
E1200–E1210 Multi-Target Compilation E1200 unknown target, E1201–E1204 unsupported target capability/feature, E1210 target resource limit
E9001 Internal Invariant E9001 internal compiler/stack invariant failed (compiler bug)
W0701–W0704 Advisory Lints Security and correctness warnings (lintContract); never alter compiled bytecode

7.2 Advisory lints (lintContract)

W0701 — Multi-input payout merge hazard (payoutMerge)

Triggers when a method compares an output value (out.value or tx.outputs[k].value) against this.coin.value without an input loop that references this.root. Because each input under the same policy runs independently against its own this.coin.value, two such inputs can share a single payout output and leak the second coin's value to miner fees.

// BAD (triggers W0701): two order UTXOs can both satisfy the same output!
function fill() {
    paid = 0;
    for out in tx.outputs {
        if out.exclusive_branch(maker) && out.value >= this.coin.value {
            paid += 1;
        }
    }
    require(paid == 1);
}

// GOOD: count inputs carrying this.root and require exactly one (or sum their values).
function fill() {
    same_in = 0;
    for inp in tx.inputs {
        if inp.is_spend && inp.requires_branch(this.root) { same_in += 1; }
    }
    require(same_in == 1);
    // ... verify payout against this.coin.value ...
}

W0702 — Always-succeeds method (alwaysSucceeds)

Triggers when a method's requirements are provably tautological (e.g., require(true);) or optimize down to DROP* N(1), allowing anyone to spend the coin or mint the token unconditionally.

// BAD (triggers W0702): anyone can spend this coin.
function spend(sig: Signature) {
    require(true);
}

// GOOD: enforce a signature, preimage, or covenant condition.
function spend(sig: Signature) {
    require(checksig(sig, owner));
}

W0703 — Unused Signature argument (unusedSignatures)

Triggers when a method declares a Signature parameter that is never read in the body—the spender must still supply 64 bytes, but nothing verifies it.

// BAD (triggers W0703): `admin_sig` is never checked.
function cancel(owner_sig: Signature, admin_sig: Signature) {
    require(checksig(owner_sig, owner));
}

// GOOD: verify every declared signature or remove the unused parameter.
function cancel(owner_sig: Signature) {
    require(checksig(owner_sig, owner));
}

W0704 — Unguarded dynamic divisor (unguardedDivisors)

Triggers when / or % divides by a dynamic identifier without a dominating branch-scoped non-zero guard (require(d > 0);, require(d >= 1);, require(d != 0);, or if d > 0 { ... }). Division or modulo by zero aborts VM execution at runtime.

// BAD (triggers W0704): `den` could be 0 at runtime.
function payout(num: Amount, den: Int) {
    require(tx.outputs[0].value >= num / den);
}

// GOOD: dominate the division with a non-zero check.
function payout(num: Amount, den: Int) {
    require(den > 0);
    require(tx.outputs[0].value >= num / den);
}

8. Standard Contracts

The Lotus Standard Library (tools/lotus-compiler/std/, exported via @lotus/compiler/std) provides audited, pragma-pinned templates for common custody, token, NFT, and DeFi patterns. Because wallets recognize their canonical BranchRoots and TokenIds, users see human-readable signing intent and verification badges instead of opaque hex.

Every listing below is complete, annotated with the rationale behind each security invariant, and compile-verified in CI.

8.1 Core Custody & Escrow

1. SingleOwnerWallet

Standard single-key BIP-340 Schnorr payment policy. Optimizer v2 folds require(checksig(sig, owner)); into a 35-byte script (PUSH_32 <owner>; CHECKSIGVERIFY; N(1)).

pragma edition "2026.2";
pragma optimizer "v2";

// Single-Owner BIP-340 Schnorr Wallet.
contract SingleOwnerWallet<owner: PublicKey> {
    function spend(sig: Signature) {
        // Direct BIP-340 Schnorr verification against the bound x-only public key.
        require(checksig(sig, owner));
    }
}

2. Multisig2of3

2-of-3 threshold custody using BIP-340 abstain semantics: a non-signing key holder supplies 64 zero bytes (ABSTAIN), causing checksig to return false cleanly instead of aborting.

pragma edition "2026.2";
pragma optimizer "v2";

// 2-of-3 Threshold Multisig (supports BIP-340 abstain via 64 zero-byte signature slots).
contract Multisig2of3<pk1: PublicKey, pk2: PublicKey, pk3: PublicKey> {
    function spend(sig1: Signature, sig2: Signature, sig3: Signature) {
        // Initialize numeric accumulator at method top level so it is visible across all branches.
        valid = 0;
        // Each slot either verifies a valid BIP-340 signature (+1) or abstains with 64 zero bytes (+0).
        if checksig(sig1, pk1) { valid += 1; }
        if checksig(sig2, pk2) { valid += 1; }
        if checksig(sig3, pk3) { valid += 1; }
        // At least 2 distinct bound keys must sign.
        require(valid >= 2);
    }
}

3. VaultWithRecovery

Two-leaf MAST vault: the owner spends immediately with zero time-lock overhead (revealing only the spend leaf), while a guardian can recover funds after recovery_height using check_lock(1, recovery_height).

pragma edition "2026.2";
pragma optimizer "v2";

// Vault with Guardian Recovery: owner spends immediately; guardian recovers after absolute lock height.
contract VaultWithRecovery<owner: PublicKey, guardian: PublicKey, recovery_height: Int> {
    function spend(owner_sig: Signature) {
        // Fast path: owner spends at any time without revealing the guardian recovery leaf.
        require(checksig(owner_sig, owner));
    }

    function recover(guardian_sig: Signature) {
        // Lock kind 1 = absolute block height (validated at compile time: E0415-E0417).
        require(check_lock(1, recovery_height));
        require(checksig(guardian_sig, guardian));
    }
}

4. HTLC (Hash Time-Locked Contract)

Canonical atomic swap primitive: recipient claims with a SHA-256 preimage, or refund_key reclaims after refund_height.

pragma edition "2026.2";
pragma optimizer "v2";

// Hash Time-Locked Contract (HTLC) for non-custodial cross-chain atomic swaps.
contract HTLC<recipient: PublicKey, refund_key: PublicKey, secret_hash: Bytes32, refund_height: Int> {
    function claim(sig: Signature, preimage: Bytes(64)) {
        // Bound preimage width (<= 64 bytes) prevents oversized witness griefing.
        require(sha256(preimage) == secret_hash);
        // Signature binds the claim to the intended recipient (prevents front-running in mempool).
        require(checksig(sig, recipient));
    }

    function refund(sig: Signature) {
        // Absolute block-height lock ensures refund cannot race before swap timeout.
        require(check_lock(1, refund_height));
        require(checksig(sig, refund_key));
    }
}

5. ArbiterEscrow

Three-leaf MAST escrow: cooperative buyer+seller release, arbiter+either-party dispute resolution, or buyer timeout refund.

pragma edition "2026.2";
pragma optimizer "v2";

// 2-of-3 Arbiter Escrow with timeout refund to buyer.
contract ArbiterEscrow<buyer: PublicKey, seller: PublicKey, arbiter: PublicKey, timeout_height: Int> {
    function release(buyer_sig: Signature, seller_sig: Signature) {
        // Happy path: buyer and seller agree; arbiter is never involved or revealed.
        require(checksig(buyer_sig, buyer));
        require(checksig(seller_sig, seller));
    }

    function arbitrate(arbiter_sig: Signature, party_sig: Signature) {
        // Dispute path: arbiter cannot unilaterally steal funds—must co-sign with buyer OR seller.
        require(checksig(arbiter_sig, arbiter));
        require(checksig(party_sig, buyer) || checksig(party_sig, seller));
    }

    function timeout_refund(buyer_sig: Signature) {
        // Liveness backstop: buyer recovers funds if seller and arbiter both disappear.
        require(check_lock(1, timeout_height));
        require(checksig(buyer_sig, buyer));
    }
}

8.2 Fungible Tokens

Lotus separates a token's mint contract (token ..., whose MAST root is the 32-byte TokenId, executed on flags = 0x03 mint inputs) from its transfer-rules contract (contract ..., attached as a mandatory branch on every token UTXO to govern subsequent spends). Every mint contract pairs with a transfer-rules BranchRoot (typically StandardTransferRules) and enforces that each newly minted output carries that branch alongside an owner/custody branch.

6. StandardTransferRules

Zero-parameter, zero-freeze, zero-tax canonical transfer covenant. Every token carrying this branch shares the universal BranchRoot 985e7562c70c1577cd7acdd208c0dfa36683860e0ed1931ed77574866389dbdc (pinned to optimizer "v1"), allowing wallets and DEXs to recognize standard fungible tokens in $O(1)$.

pragma edition "2026.2";
pragma optimizer "v1";

// Lotus Canonical Standard Transfer Rules (zero-parameter, zero-freeze, zero-tax).
// Universal BranchRoot: 985e7562c70c1577cd7acdd208c0dfa36683860e0ed1931ed77574866389dbdc
contract StandardTransferRules {
    function transfer() {
        for output in tx.outputs {
            if output.token_id == this.coin.token_id {
                // Every output of this token must continue to enforce this exact transfer branch.
                require(output.requires_branch(this.root));
                // Must NOT be exclusive: the output must also carry an owner/custody branch,
                // otherwise the tokens would be permanently anyone-can-spend / unowned.
                require(!output.exclusive_branch(this.root));
            }
        }
    }
}

7. IssuerMintToken

Minimal issuer-signed mint contract paired directly with StandardTransferRules (or any custom transfer-rules BranchRoot). Demonstrates the canonical mint + transfer-rules pairing before the specialized supply models below.

pragma edition "2026.2";
pragma optimizer "v2";

// Minimal Issuer-Signed Mint Contract: pairs with `StandardTransferRules` (or any transfer-rules
// BranchRoot) so the issuer can authorize new supply with a BIP-340 Schnorr signature.
token IssuerMintToken<issuer: PublicKey, transfer_rules: BranchRoot> {
    function mint(amount: Amount, issuer_sig: Signature) {
        // First parameter `amount` is the consensus mint delta pushed by the node.
        require(amount > 0);
        require(checksig(issuer_sig, issuer));

        // Every newly minted output of this token (`this.root` == TokenId) must carry
        // `transfer_rules` plus an owner/custody branch (`!exclusive_branch`).
        for out in tx.outputs {
            if out.token_id == this.root {
                require(out.requires_branch(transfer_rules));
                require(!out.exclusive_branch(transfer_rules));
            }
        }
    }
}

8. FixedSupplyToken

One-shot genesis mint bound to a unique creator seed outpoint (seed_txid, seed_vout). Because UTXO consensus allows an outpoint to be spent at most once, future minting is mathematically impossible with zero ongoing state or admin keys.

pragma edition "2026.2";
pragma optimizer "v2";

// Fixed-Supply Fungible Token: one-shot genesis mint bound to a unique creator seed outpoint.
token FixedSupplyToken<
    seed_txid: TxId,
    seed_vout: Int,
    total_supply: Amount,
    transfer_rules: BranchRoot
> {
    function issue(amount: Amount) {
        // First param `amount` is the consensus mint delta pushed by the node.
        require(amount == total_supply);

        // Prove the unique genesis seed UTXO is consumed in this exact transaction.
        seed_spent = 0;
        for inp in tx.inputs {
            // Always guard `inp.txid` / `inp.vout` with `inp.is_spend` (mint inputs have no outpoint).
            if inp.is_spend && inp.txid == seed_txid && inp.vout == seed_vout {
                seed_spent += 1;
            }
        }
        require(seed_spent == 1);

        // Every newly minted token output must carry the canonical transfer rules + an owner branch.
        for out in tx.outputs {
            if out.token_id == this.root {
                require(out.requires_branch(transfer_rules));
                require(!out.exclusive_branch(transfer_rules));
            }
        }
    }
}

9. SupplyController + CappedSupplyToken

Two-contract pattern for capped, multi-tranche issuance with an irreversible lock_mint kill switch. State (issued, locked) lives in branch 1 via declarative state separate SupplyState, and tx_token_balance(token_id) binds the exact consensus mint delta so the issuer cannot mint more than delta or mint during lock_mint.

pragma edition "2026.2";
pragma optimizer "v2";

// Separate-branch STATEHASH schema (branch 1) tracking cumulative issued supply and lock flag.
state separate SupplyState {
    issued: Amount,
    locked: Int,
}

// Capped-Supply Fungible Token controller with irreversible lock_mint.
contract SupplyController<issuer: PublicKey, token_id: TokenId, max_supply: Amount> {
    function mint(sig: Signature, prev_issued: Amount, delta: Amount) {
        require(checksig(sig, issuer));
        require(delta > 0);
        require(prev_issued >= 0);
        next_issued = prev_issued + delta;
        require(next_issued <= max_supply);

        // Verify current state committed in branch 1: (prev_issued, locked = 0).
        require(SupplyState.verify(prev_issued, 0));

        // Bind consensus net token mint delta (tout - tin) to the authorized `delta`.
        let (tin, tout) = tx_token_balance(token_id);
        require(tout - tin == delta);

        // Singleton input guard: prevent two controller coins from being merged or double-counted.
        seen_in = 0;
        for inp in tx.inputs {
            if inp.is_spend && inp.requires_branch(this.root) { seen_in += 1; }
        }
        require(seen_in == 1);

        // Continue the exact controller coin with updated state (next_issued, locked = 0).
        continued = 0;
        for out in tx.outputs {
            if out.flags == this.coin.flags &&
               out.value == this.coin.value &&
               out.continues_branch(this.root) &&
               SupplyState.matches(out, next_issued, 0) {
                continued += 1;
            }
        }
        require(continued == 1);
    }

    function lock_mint(sig: Signature, prev_issued: Amount) {
        require(checksig(sig, issuer));
        require(SupplyState.verify(prev_issued, 0));

        // Disallow any net new minting in the lock transaction itself.
        let (tin, tout) = tx_token_balance(token_id);
        require(tout <= tin);

        seen_in = 0;
        for inp in tx.inputs {
            if inp.is_spend && inp.requires_branch(this.root) { seen_in += 1; }
        }
        require(seen_in == 1);

        // Transition locked flag 0 -> 1; no method accepts locked == 1, so minting is permanently sealed.
        continued = 0;
        for out in tx.outputs {
            if out.flags == this.coin.flags &&
               out.value == this.coin.value &&
               out.continues_branch(this.root) &&
               SupplyState.matches(out, prev_issued, 1) {
                continued += 1;
            }
        }
        require(continued == 1);
    }
}

token CappedSupplyToken<controller: BranchRoot, transfer_rules: BranchRoot> {
    function issue(amount: Amount) {
        require(amount > 0);
        // Minting is authorized iff exactly one spend input carries the SupplyController branch.
        auth = 0;
        for inp in tx.inputs {
            if inp.is_spend && inp.requires_branch(controller) { auth += 1; }
        }
        require(auth == 1);

        // Propagate transfer rules to all minted outputs.
        for out in tx.outputs {
            if out.token_id == this.root {
                require(out.requires_branch(transfer_rules));
                require(!out.exclusive_branch(transfer_rules));
            }
        }
    }
}

10. VoucherMintToken

Stateless, zero-contention voucher minting: the issuer signs (tx.chain_id, token_id, bound_txid, bound_vout, amount) off-chain, and users redeem vouchers in parallel without contending on a single global controller UTXO. Replay is impossible because (bound_txid, bound_vout) can only be spent once, and tx.chain_id blocks cross-network replay.

pragma edition "2026.2";
pragma optimizer "v2";

// Outpoint-Bound Signed Voucher Mint Token:
// Issuer signs (chain_id, token_id, bound_txid, bound_vout, amount) off-chain; user mints
// directly without global state contention.
token VoucherMintToken<issuer: PublicKey, transfer_rules: BranchRoot> {
    function mint_with_voucher(
        amount: Amount,
        voucher_sig: Signature,
        bound_txid: TxId,
        bound_vout: Int
    ) {
        require(amount > 0);

        // Single-use replay protection: the user's bound UTXO must be spent in this transaction.
        found = 0;
        for inp in tx.inputs {
            if inp.is_spend && inp.txid == bound_txid && inp.vout == bound_vout {
                found += 1;
            }
        }
        require(found == 1);

        // Verify issuer's off-chain BIP-340 signature (alg = 0) over the domain-separated voucher digest.
        // Zero-cost `bytes32(...)` converts nominal tagged hashes for byte concatenation.
        require(checkdatasig(
            voucher_sig,
            blake3(cat(
                cat(bytes32(tx.chain_id), bytes32(this.root)),
                cat(bytes32(bound_txid), cat(num2bin(bound_vout, 16), num2bin(amount, 16)))
            )),
            issuer,
            0
        ));

        for out in tx.outputs {
            if out.token_id == this.root {
                require(out.requires_branch(transfer_rules));
                require(!out.exclusive_branch(transfer_rules));
            }
        }
    }
}

8.3 NFTs & Collections

11. UniqueNFT

1-of-1 non-fungible token: enforces amount == 1, a single-use creator seed outpoint, an immutable metadata_hash commitment, and out.value == 1.

pragma edition "2026.2";
pragma optimizer "v2";

// Unique 1-of-1 NFT: singleton value == 1 genesis mint bound to a unique creator seed outpoint
// and an immutable metadata commitment hash.
token UniqueNFT<
    seed_txid: TxId,
    seed_vout: Int,
    metadata_hash: Bytes32,
    transfer_rules: BranchRoot
> {
    function mint(amount: Amount, commitment: Bytes32) {
        // Singleton supply: exactly 1 indivisible atom can ever be minted.
        require(amount >= 1 && amount <= 1);
        require(commitment == metadata_hash);

        seed_spent = 0;
        for inp in tx.inputs {
            if inp.is_spend && inp.txid == seed_txid && inp.vout == seed_vout {
                seed_spent += 1;
            }
        }
        require(seed_spent == 1);

        for out in tx.outputs {
            if out.token_id == this.root {
                require(out.value >= 1 && out.value <= 1);
                require(out.requires_branch(transfer_rules));
                require(!out.exclusive_branch(transfer_rules));
            }
        }
    }
}

12. NFTCollectionAuthority + NFTCollectionMint

Bounded NFT collection (e.g., 1,000 items) tracking the minted counter in separate-branch state (branch 1) via state separate CollectionState and enforcing 1-item-per-mint via tx_token_balance.

pragma edition "2026.2";
pragma optimizer "v2";

// Separate-branch STATEHASH schema (branch 1) tracking the number of minted collection items.
state separate CollectionState {
    minted: Int,
}

// NFT Collection: bounded collection authority paired with a collection token mint enforcing value == 1.
contract NFTCollectionAuthority<creator: PublicKey, collection_token: TokenId, max_items: Int> {
    function mint_next(sig: Signature, prev_count: Int) {
        require(checksig(sig, creator));
        require(prev_count >= 0);
        next_count = prev_count + 1;
        require(next_count <= max_items);

        // Verify current minted count in branch 1.
        require(CollectionState.verify(prev_count));

        // Exactly 1 collection item may be minted in this transaction.
        let (tin, tout) = tx_token_balance(collection_token);
        require(tout - tin >= 1 && tout - tin <= 1);

        seen_in = 0;
        for inp in tx.inputs {
            if inp.is_spend && inp.requires_branch(this.root) { seen_in += 1; }
        }
        require(seen_in == 1);

        // Advance the authority coin to next_count = prev_count + 1.
        continued = 0;
        for out in tx.outputs {
            if out.flags == this.coin.flags &&
               out.value == this.coin.value &&
               out.continues_branch(this.root) &&
               CollectionState.matches(out, next_count) {
                continued += 1;
            }
        }
        require(continued == 1);
    }
}

token NFTCollectionMint<authority: BranchRoot, transfer_rules: BranchRoot> {
    function mint_item(amount: Amount) {
        require(amount >= 1 && amount <= 1);
        auth = 0;
        for inp in tx.inputs {
            if inp.is_spend && inp.requires_branch(authority) { auth += 1; }
        }
        require(auth == 1);

        for out in tx.outputs {
            if out.token_id == this.root {
                require(out.value >= 1 && out.value <= 1);
                require(out.requires_branch(transfer_rules));
                require(!out.exclusive_branch(transfer_rules));
            }
        }
    }
}

13. RoyaltyTransferRules

Creator-royalty transfer covenant (distinct BranchRoot from StandardTransferRules so wallets display the royalty obligation transparently). Scales the required native XPI royalty by same_in (the number of royalty-bearing inputs in the transaction) to prevent multi-input batching bypasses, and requires out.exclusive_branch(creator_wallet) so the royalty output cannot be ransom-locked with an extra branch.

pragma edition "2026.2";
pragma optimizer "v2";

// Royalty-Bearing Transfer Rules (distinct from StandardTransferRules so wallets badge it accurately).
contract RoyaltyTransferRules<
    creator: PublicKey,
    creator_wallet: BranchRoot,
    min_royalty_xpi: Amount
> {
    function transfer_with_royalty() {
        // Count every spend input carrying this token & royalty branch so batching N items
        // cannot bypass paying N * min_royalty_xpi (also satisfies lint W0701).
        same_in = 0;
        for inp in tx.inputs {
            if inp.is_spend && inp.coin.token_id == this.coin.token_id && inp.requires_branch(this.root) {
                same_in += 1;
            }
        }
        require(same_in >= 1);

        royalty_paid = 0;
        for out in tx.outputs {
            if out.token_id == this.coin.token_id {
                require(out.requires_branch(this.root));
                require(!out.exclusive_branch(this.root));
            }
            // Native XPI (flags == 0) paid exclusively to creator_wallet (no ransom-lock branches).
            if out.flags == 0 && out.exclusive_branch(creator_wallet) {
                royalty_paid += out.value;
            }
        }
        require(royalty_paid >= same_in * min_royalty_xpi);
    }

    function creator_exempt_transfer(creator_sig: Signature) {
        // Optional creator-signed exemption (e.g., primary distribution or migration).
        require(checksig(creator_sig, creator));
        for out in tx.outputs {
            if out.token_id == this.coin.token_id {
                require(out.requires_branch(this.root));
                require(!out.exclusive_branch(this.root));
            }
        }
    }
}

8.4 DeFi Primitives

14. IndexedLimitOrder

0x-style partial-fill limit order using Pratt-indexed injective payouts: input i = this.input_index reads tx.outputs[2 * i] (maker payout) and tx.outputs[2 * i + 1] (order remainder). Because the mapping $i \mapsto (2i, 2i+1)$ is strictly injective, multiple orders can be filled atomically in a single transaction with $O(1)$ per-order script cost and zero payout-merge vulnerability.

pragma edition "2026.2";
pragma optimizer "v2";

// 0x-Style Partial-Fill Limit Order with Pratt-indexed injective payouts:
// For order input at index i: outputs[2*i] = maker payout (exclusive_branch),
// outputs[2*i+1] = order remainder (continues_branch).
contract IndexedLimitOrder<
    maker: PublicKey,
    maker_payout: BranchRoot,
    quote_token: TokenId,
    price_num: Int,
    price_den: Int,
    min_fill: Amount
> {
    function fill(fill_amount: Amount, payout_idx: Int, remainder_idx: Int) {
        require(price_num > 0 && price_den > 0);
        // Anti-dust atomic remainder rule: partial fills must meet min_fill and either
        // exhaust the order completely (rem == 0) or leave at least min_fill remaining.
        require(fill_amount > 0 && fill_amount >= min_fill);
        require(fill_amount <= this.coin.value);
        rem = this.coin.value - fill_amount;
        require(rem <= 0 || rem >= min_fill);

        // Injective output slot binding eliminates multi-order payout collisions in O(1).
        require(payout_idx == 2 * this.input_index);
        require(remainder_idx == 2 * this.input_index + 1);

        // Verify maker receives at least fill_amount * (price_num / price_den) in quote_token,
        // locked exclusively to maker_payout so takers cannot attach hostile branches.
        require(tx.outputs[payout_idx].token_id == quote_token);
        require(tx.outputs[payout_idx].exclusive_branch(maker_payout));
        require(tx.outputs[payout_idx].value * price_den >= fill_amount * price_num);

        // If partially filled, recreate the exact order covenant for the remaining base tokens.
        if rem > 0 {
            require(tx.outputs[remainder_idx].token_id == this.coin.token_id);
            require(tx.outputs[remainder_idx].value == rem);
            require(tx.outputs[remainder_idx].continues_branch(this.root));
        }
    }

    function cancel(maker_sig: Signature) {
        // Maker can cancel and reclaim remaining tokens at any time.
        require(checksig(maker_sig, maker));
    }
}

15. AmmPoolV2

Constant-product AMM controller (3-coin Profile B architecture: 1 controller coin + 2 reserve coins) with zero admin keys. Uses declarative state separate PoolState (branch 1) for (reserve0, reserve1, total_lp), sqrt for geometric-mean LP share minting, and mul128_wide + less_swap for exact 256-bit constant-product invariant verification—removing any < 2^50 reserve overflow ceiling.

pragma edition "2026.2";
pragma optimizer "v2";

// Separate-branch STATEHASH schema (branch 1) for AMM pool reserves and total LP supply.
state separate PoolState {
    reserve0: Amount,
    reserve1: Amount,
    total_lp: Amount,
}

// Constant-Product AMM Controller using declarative separate-branch state,
// MUL128_WIDE (full 256-bit constant-product invariant), and SQRT for LP share minting.
contract AmmPoolV2<
    token0: TokenId,
    token1: TokenId,
    reserve_branch: BranchRoot,
    fee_bps: Int,
    min_liquidity: Amount
> {
    function first_deposit(x: Amount, y: Amount) {
        require(fee_bps >= 0 && fee_bps < 10000);
        require(x > 0 && y > 0);

        // Pool must start in the uninitialized (0, 0, 0) state committed in branch 1.
        require(PoolState.verify(0, 0, 0));

        // Uniswap V2 geometric-mean initial LP shares minus permanently locked min_liquidity.
        lp = sqrt(x * y) - min_liquidity;
        require(lp > 0);

        // Singleton controller input guard.
        seen_in = 0;
        for inp in tx.inputs {
            if inp.is_spend && inp.requires_branch(this.root) { seen_in += 1; }
        }
        require(seen_in == 1);

        // Recreate controller with (x, y, lp + min_liquidity) and lock both initial reserves
        // exclusively under `reserve_branch`.
        continued = 0;
        r0_out = 0;
        r1_out = 0;
        for out in tx.outputs {
            if out.flags == this.coin.flags &&
               out.value == this.coin.value &&
               out.continues_branch(this.root) &&
               PoolState.matches(out, x, y, lp + min_liquidity) {
                continued += 1;
            }
            if out.token_id == token0 && out.exclusive_branch(reserve_branch) && out.value == x {
                r0_out += 1;
            }
            if out.token_id == token1 && out.exclusive_branch(reserve_branch) && out.value == y {
                r1_out += 1;
            }
        }
        require(continued == 1 && r0_out == 1 && r1_out == 1);
    }

    function swap_0_for_1(
        old_x: Amount,
        old_y: Amount,
        total_lp: Amount,
        dx: Amount,
        dy: Amount,
        min_out: Amount
    ) {
        require(fee_bps >= 0 && fee_bps < 10000);
        require(old_x > 0 && old_y > 0 && total_lp > 0);
        require(dx > 0 && dy > 0 && dy >= min_out && dy < old_y);

        // Authenticate pre-swap reserves and LP supply against branch 1 STATEHASH.
        require(PoolState.verify(old_x, old_y, total_lp));

        next_x = old_x + dx;
        next_y = old_y - dy;

        // Exact 256-bit constant-product invariant with fee:
        //   (next_x * 10000 - dx * fee_bps) * (next_y * 10000) >= (old_x * 10000) * (old_y * 10000)
        // Computed via MUL128_WIDE (128x128 -> 256-bit) and compared limb-by-limb via LESSSWAP.
        let (lhs_hi, lhs_lo) = mul128_wide(next_x * 10000 - dx * fee_bps, next_y * 10000);
        let (rhs_hi, rhs_lo) = mul128_wide(old_x * 10000, old_y * 10000);
        let (min_hi, max_hi) = less_swap(lhs_hi, rhs_hi);
        let (min_lo, max_lo) = less_swap(lhs_lo, rhs_lo);
        require(
            (lhs_hi != rhs_hi && max_hi == lhs_hi) ||
            (lhs_hi == rhs_hi && (lhs_lo == rhs_lo || max_lo == lhs_lo))
        );
        require(size(min_hi) == 16 && size(min_lo) == 16);

        // Verify all 3 pool coins (controller + token0 reserve + token1 reserve) are consumed once.
        seen_in = 0;
        r0_in = 0;
        r1_in = 0;
        for inp in tx.inputs {
            if inp.is_spend && inp.requires_branch(this.root) { seen_in += 1; }
            if inp.is_spend && inp.coin.token_id == token0 && inp.requires_branch(reserve_branch) && inp.coin.value == old_x {
                r0_in += 1;
            }
            if inp.is_spend && inp.coin.token_id == token1 && inp.requires_branch(reserve_branch) && inp.coin.value == old_y {
                r1_in += 1;
            }
        }
        require(seen_in == 1 && r0_in == 1 && r1_in == 1);

        // Verify all 3 pool coins are recreated with updated reserves and state commitment.
        continued = 0;
        r0_out = 0;
        r1_out = 0;
        for out in tx.outputs {
            if out.flags == this.coin.flags &&
               out.value == this.coin.value &&
               out.continues_branch(this.root) &&
               PoolState.matches(out, next_x, next_y, total_lp) {
                continued += 1;
            }
            if out.token_id == token0 && out.exclusive_branch(reserve_branch) && out.value == next_x {
                r0_out += 1;
            }
            if out.token_id == token1 && out.exclusive_branch(reserve_branch) && out.value == next_y {
                r1_out += 1;
            }
        }
        require(continued == 1 && r0_out == 1 && r1_out == 1);
    }
}