Source: docs/lotus-v2/examples/README.md

Worked contract examples

Status: semantic examples for review. Listings on this page mix implemented source concepts with historical pseudocode and symbolic assembly; they are not a conformance suite. The current compiler gallery contains executable programs, artifacts and reference/native evidence with explicit stage limits. The EVM conversion suite adds runnable threshold, escrow, mint-limit and AMM arithmetic slices, retained negative outcomes, and proposed ERC20/ERC721/stateful designs. No illustrative hash on this page is presented as a computed result.

The separately generated structural fixtures cover framing, hashing, trees and selected integer algorithms. Their generator and scope are explicit: they do not execute these contracts or verify a signed payment.

Language conventions used here

The script ABI distinguishes today's schema-2 compiler grammar from the proposed LC-1 entrypoint, named-policy and state-effect language. The older listings below show how P03 operations can be used; unsupported syntax such as state, paired output, Blocks, and ends must not be pasted into the current compiler as working code. Assembly uses symbolic opcode names, <x> for a push of constant x, and stack comments with the top on the right.

For new language work use LC-1's explicit entry and policy proposal: methods select leaves within a program, while named paths select the AND of required branch slots. Imports have no deployment effect. Mint identity is independent of holder policy branch order. A bound program root does not identify a complete output policy. The work plan gives versioning, implementation owners and acceptance gates.

1. Ordinary payment

contract Payment<owner: PublicKey> {
    function spend(signature: Signature) {
        require(checksig(signature, owner));
    }
}

Symbolic assembly: <owner> CHECKSIG. Arguments bottom-to-top: [signature]; pushing owner leaves signature below the key. CHECKSIG pops key then signature and pushes an int128 Boolean. Selected policy: one branch Leaf(script), paths=[[0]]; path index zero, exactly one witness, empty membership proof.

Pre-state: one mature native coin with value 100000 and the payment policy. Transaction: consume it and create native outputs of 60000 and 39000 to two fully specified recipient policies, with no mint input. Expected native fee: 1000 atoms; the complete transaction must be at most 1000 bytes to meet C14b, and P05's block burn floor must also hold. At most half of net fees enters the coinbase entitlement before its resource deduction (C16). With valid authorization, the final stack is [true], the input is removed and both outputs are inserted. Changing a committed output changes core identity and the signing message.

Cost report must include parsing, coin resolution, root verification, push/CHECKSIG and accounting; it cannot assume a signature-cache hit.

2. Wallet with recovery

contract MyWallet<owner: PublicKey, guardian: PublicKey, delay: Blocks> {

    function normal(signature: Signature) {
        require(checksig(signature, owner));
    }

    function recover(signature: Signature) {
        require(input.age >= delay);          // relative lock
        require(checksig(signature, guardian));
    }
}

policy = { branches: [MyWallet], paths: [[0]] }

Both methods are leaves of one tree, so the coin has one branch and one path, and only the method used is ever revealed. recover compiles its delay to CHECKSEQUENCEVERIFY, which requires the spending input's relative lock to be at least delay. The alternative layout, two branches with paths=[[0],[1]], is also valid; then the whole recovery condition, including its delay, must sit inside the recovery branch, because a path does not inherit a condition from another path.

Expected result: the selected path requires exactly its listed witness. A recovery spend before the delay has elapsed fails the relative lock in consensus, not in the script.

3. Token with a rules contract

A token is two trees. The rules are a contract whose root every output of the token must carry as a branch. The mint policy is a token whose root is the token ID.

contract MyTokenRules {

    function transfer() {
        token = this.coin.token_id;
        for output in tx.outputs {
            if output.token_id == token {
                // The output must carry this root as a branch, on every path.
                require(output.requires_branch(this.root));
            }
        }
    }
}

// A free function, copied into each method that calls it.
function minted_under_rules(token: TokenId) {
    for output in tx.outputs {
        if output.token_id == token {
            require(output.requires_branch(merkle_root(MyTokenRules)));
        }
    }
}

token MyToken<issuer: PublicKey, old_token: TokenId> {

    // The issuer creates new units.
    function issue(amount: Amount, signature: Signature) {
        require(checksig(signature, issuer));
        minted_under_rules(this.root);
    }

    // Anyone replaces old tokens with new ones, one for one.
    function upgrade(amount: Amount) {
        burned = 0;
        for input in tx.inputs {
            if input.is_spend && input.coin.token_id == old_token {
                burned += input.coin.value;
            }
        }
        for output in tx.outputs {
            if output.token_id == old_token {
                burned -= output.value;
            }
        }
        require(burned >= amount);
        minted_under_rules(this.root);
    }
}

token_id = merkle_root(MyToken<issuer, old_token>)

transfer learns its own tree's root from BRANCHROOT:

ENUMERATE_OUTPUTS                 ; loop; pushes the output index j
    DUP OUTPUTTOKENID             ; j, that output's token ID
    INPUTINDEX UTXOTOKENID EQUAL  ; same token as the coin being spent?
    IF
        BRANCHROOT                ; j, the root of the rules tree
        OUTPUTREQUIRESBRANCH      ; true if every path includes that root
        VERIFY
    ELSE
        DROP                      ; another asset: ignore it
    ENDIF
ENDENUMERATE
ONE                               ; the script's result

minted_under_rules is in a different tree, so the rules root is a compile-time constant there, and BRANCHROOT returns the mint tree's own root, which is the token ID. This is a fragment, copied into issue and upgrade; each of those also consumes the amount the node pushed and ends with a true value:

ENUMERATE_OUTPUTS
    DUP OUTPUTTOKENID
    BRANCHROOT EQUAL              ; is it this token?
    IF
        <merkle_root(MyTokenRules)>
        OUTPUTREQUIRESBRANCH
        VERIFY
    ELSE
        DROP
    ENDIF
ENDENUMERATE

The two mint methods in full. A mint script starts with its witness arguments on the stack and the minted amount on top, pushed by the node; it must consume the amount and finish with one true value. issue allows any amount, so it drops it:

; stack: signature amount
DROP                              ; signature
<issuer> CHECKSIGVERIFY           ; (empty)    the issuer signed this transaction
; ... the minted_under_rules loop above ...
ONE

upgrade takes no witness arguments. It adds up the old token spent, subtracts the old token recreated, and requires the remainder to cover the amount minted. Input flags 01 mark a spend; a mint input has no coin to read:

; stack: amount
<0>                                       ; amount burned
ENUMERATE_INPUTS                          ; amount burned i
    DUP INPUTFLAGS ONE NUMEQUAL           ; amount burned i isSpend?
    IF
        DUP UTXOTOKENID <old_token> EQUAL ; amount burned i isOldToken?
        IF   UTXOVALUE ADD                ; amount burned'
        ELSE DROP
        ENDIF
    ELSE
        DROP
    ENDIF
ENDENUMERATE
ENUMERATE_OUTPUTS                         ; amount burned j
    DUP OUTPUTTOKENID <old_token> EQUAL
    IF   OUTPUTVALUE SUB                  ; amount burned'
    ELSE DROP
    ENDIF
ENDENUMERATE
SWAP GREATERTHANOREQUAL VERIFY            ; burned >= amount
; ... the minted_under_rules loop above ...
ONE

Why two trees: if upgrade sat in the same tree as transfer, a holder could satisfy the rules branch by revealing upgrade with made-up arguments and move units out from under the rules.

The presence check is deliberate. A holder adds a wallet branch of their own beside the rules, so the rules require only that they remain on every path. A typical holder policy is branches=[MyWallet, MyTokenRules], paths=[[0,1]].

Scenario: a mint input authorizes a positive delta of 1000 units into a recipient policy carrying the rules branch; native inputs separately cover fees and the token output burn (C14a). A later transaction consuming 1000 units and producing 700 + 250 burns 50 units and has no mint input. Every consumed token coin executes every branch on its selected path, so transfer runs on each. A mint may appear at most once per token in a transaction, and upgrade reads coin fields only at inputs whose flags mark a spend, since a mint input resolves no coin.

Key rotation: issuer is part of the token ID. An issuer who needs to rotate keys makes the template parameter a cold key that signs certificates for working keys, or identifies an authority coin that every mint must spend and recreate. A certificate cannot expire (C22a).

4. Limit order

// pay_to: the maker's own script tree.  price: XPI per unit.
contract LimitOrder<pay_to: Root, price: Amount> {

    // Anyone may take the order by paying the maker.
    function fill() {
        paired output payment {
            token_id == native;
            value    >= this.coin.value * price;
            // Spendable by the maker's tree alone, and never without it.
            exclusive_branch == pay_to;
        }
    }
}

// The order coin. Either path spends it.
policy = {
    branches: [LimitOrder<root of MakerWallet, 1042>, MakerWallet],
    paths:    [[0],          // anyone, by filling the order
               [1]],         // the maker, to withdraw it
}

The order coin holds the tokens for sale, so this.coin.value is the number of units. The order lasts until it is filled or the maker spends it through the second path. Both spend the coin, so nothing has to expire. If the token has a rules contract, its branch is added to both paths.

exclusive_branch compiles to INPUTINDEX <pay_to> OUTPUTEXCLUSIVEBRANCH. It is true when the payment output has a path that is pay_to alone and every other path includes pay_to. A presence check would not do here: a taker could add a branch of their own to the payment and leave the maker unable to spend it without them.

The terms are template parameters, so each order has its own root and an order coin is not recognizable by scanning the chain. The maker announces the coin and its terms; anyone can rebuild the script from them and confirm its root is a branch of that coin.

Pairing: with two order coins from one maker at inputs 0 and 1, each requires its own payment at outputs 0 and 1. Without pairing both could be satisfied by one payment.

Partial fills, Dutch auctions and expiring offers (preserving C22a):

5. Contract state

Outputs have no state field. A contract with state is laid out as one data leaf beside the subtree of its methods (P02):

            root
           /    \
  data leaf      M     (root of the methods subtree; never changes)
contract Counter<owner: PublicKey> {

    state {
        n: Amount,
    }

    // Assigns a field, so the successor must hold the new value.
    function increment() {
        n = n + 1;
    }

    // Ends the contract. No successor is required.
    function close(signature: Signature) ends {
        require(checksig(signature, owner));
    }
}

This historical state-lowering sketch proposes that the wallet supply the current value and M as two hidden leading arguments. A complete implementation must also prove that the active method belongs to M, authenticate the instance where history matters, and check successor asset/value. The root calculation alone below is not that complete implementation. increment:

; witness args: n (a 16-byte number), M (32 bytes)

; 1. Check the state the wallet supplied.
OVER <10> SWAP CAT <66> CAT          ; n M ds    ds = data script: push n, RETURN
LEAFHASH                             ; n M D     D  = data leaf holding n
OVER NODEHASH                        ; n M R     R  = Node(D, M)
BRANCHROOT EQUALVERIFY               ; n M       n and M are genuine

; 2. Compute the new state.
SWAP 1ADD                            ; M n'      n' = n + 1

; 3. Compute the root the successor must have.
<10> SWAP CAT <66> CAT LEAFHASH      ; M D'
NODEHASH                             ; R'        R' = Node(D', M)

; 4. Require the output at this input's position to continue with R'.
INPUTINDEX SWAP                      ; i R'
OUTPUTCONTINUESBRANCH                ; preserves all paths and companion branches, replacing BRANCHROOT with R'

A method's membership proof ends with the data leaf's hash, so the wallet rebuilds the proof from the current values on every spend. The data script ends in RETURN so that it can never be run as a method. Numbers in state are kept at the VM's 16-byte width, so no conversion is needed.

These checks cover every step but not the start: no script runs when a coin is created, so anyone can make a coin whose root is a Counter holding any n. Where the history matters, a mint script requires the first coin to carry the contract's root for the starting values, and the contract's methods require the token to move to the successor.

Why OUTPUTCONTINUESBRANCH is used for continuation (OUTPUTEXCLUSIVEBRANCH for fresh payouts): OUTPUTCONTINUESBRANCH verifies in one $O(1)$ check that output j has the exact same paths array and the exact same branches array as the spent coin (INPUTINDEX), except that the active invocation's BRANCHROOT at its branch index k is replaced by R'. Consequently, Counter.increment() works identically whether the coin is a single-branch native XPI coin (branches=[Counter], paths=[[0]]) or a multi-branch token coin carrying a mandatory token rules contract (branches=[Counter, MyTokenRules], paths=[[0, 1]]). By contrast, OUTPUTEXCLUSIVEBRANCH is used when a contract creates a fresh payout output to another party's single-branch root (pay_to in LimitOrder.fill()), where the spent coin's own branches are intentionally not continued.

Key-value maps and sets in contract state (MERKLEROOT_INDEXED, MERKLEROOT_SORTED): When a contract stores a large key-value map or allowlist inside its state leaf (a 32-byte map_root instead of a single scalar n), a method verifies the old entry old_leaf at key and computes the updated map_root' for new_leaf using the same proof witness argument and hash_alg = 0 (Lotus Tagged BLAKE3; 1 = Raw BLAKE3, 2 = SHA256, 3 = HASH256):

; verify old_leaf at key against current map_root (hash_alg = 0)
<old_leaf> <key> <proof> <0> MERKLEROOT_INDEXED <map_root> EQUALVERIFY
; compute updated map_root' for new_leaf at the same key and proof
<new_leaf> <key> <proof> <0> MERKLEROOT_INDEXED
; wrap map_root' in the data leaf and enforce continuation with OUTPUTCONTINUESBRANCH

Three ways to store data or Merkle roots in branches (P02):

  1. Data leaf inside the executing branch tree (BranchNode(DataLeaf, M)): Shown in Counter above; keeps a single-branch coin (branches=[Counter], paths=[[0]]) while updating state via OUTPUTCONTINUESBRANCH.
  2. Dedicated unexecuted data branch on a spendable coin (branches=[CodeRoot, StateMerkleRoot], paths=[[0]]): Branch 0 holds the immutable method tree (CodeRoot) and is the only branch referenced by paths; branch 1 holds a 32-byte state hash or Merkle root directly. The script in branch 0 reads its current state via INPUTINDEX <1> UTXOBRANCH (0xd9), folds a witness proof via MERKLEROOT_INDEXED or MERKLEROOT_SORTED, and checks OUTPUTBRANCH(j, 1) == new_state_root alongside OUTPUTBRANCH(j, 0) == BRANCHROOT.
  3. Pruneable burn / OP_RETURN commitment output (Output.flags bit 1 IS_BURN, 0x02 native / 0x03 token): Has paths = [] (path_count == 0) and 1..16 32-byte commitment words or Merkle roots in branches (up to 512 bytes), is never inserted into UtxoRoot (C17), permanently burns its value, and is introspected in the same transaction via OUTPUTFLAGS, OUTPUTBRANCHCOUNT, and OUTPUTBRANCH.

Proving inputs or outputs of a parent / injected transaction (OUTPOINTTXID)

Because TxID = H_txid(ChainID || TxHeaderCore || InputsRoot || OutputsRoot) commits to the bottom-up indexed binary Merkle roots (IndexedTreeRoot in P02) of InputCoreLeaf(m) = H_inputcore(InputCore(m)) and OutputLeaf(k) = H_output(Bytes(Output[k])), and because every H_name(x) domain tag (C08) is ordinary unkeyed BLAKE3 over the ASCII prefix tag || 0x00 || x, a script can prove any input InputCore(m) or output Output[k] of a parent transaction (INPUTINDEX OUTPOINTTXID) in $O(\log N)$ space without pushing the entire parent transaction onto the stack:

; Witness arguments:
;   parent_header_16B  (version:u32 || lock:u64 || input_count:u16 || output_count:u16)
;   parent_outputs_root (32B, or proven from a sibling output via MERKLEROOT_INDEXED)
;   input_core_bytes   (serialized InputCore(m) of the parent transaction)
;   input_idx_u16      (2-byte little-endian index m, checked < input_count)
;   input_merkle_proof (32 * ceil(log2(input_count)) sibling bytes)

; 1. Compute InputCoreLeaf(m) = H_inputcore(InputCore(m)) via C08 prefix + BLAKE3 (0xba):
<"Lotus/v2/inputcore\x00"> <input_core_bytes> CAT BLAKE3

; 2. Reconstruct InputsRoot in one instruction via MERKLEROOT_INDEXED (0xc1, hash_alg = 0):
<input_idx_u16> <input_merkle_proof> <0> MERKLEROOT_INDEXED

; 3. Reconstruct parent TxID = H_txid(ChainID || TxHeaderCore || InputsRoot || OutputsRoot):
<"Lotus/v2/txid\x00"> CHAINID CAT <parent_header_16B> CAT
SWAP CAT <parent_outputs_root> CAT BLAKE3

; 4. Verify against the spent coin's creating transaction ID:
INPUTINDEX OUTPOINTTXID EQUALVERIFY

The exact same pattern proves any sibling output Output[k] of the parent transaction via OutputLeaf(k) = <"Lotus/v2/output\x00"> <Bytes(Output[k])> CAT BLAKE3 and <OutputLeaf(k)> <u16(k)> <output_merkle_proof> <0> MERKLEROOT_INDEXED.

Merging two coins

By default two coins of one contract cannot become one: each demands a successor at its own position. A merge is a method the author writes.

function merge(other: input Counter) {
    n = n + other.n;
}

Both coins are spent, so both run a script. This historical proposal uses two manually specified methods: merge for the coin that survives and absorbed for the one that does not. The current compiler does not generate these from the sketch, and LC-1 does not silently add an absorbed entry. Neither can see which method the other ran, so each must make its own checks. In this particular layout the survivor is at input i, the absorbed coin at input i+1, and the merged coin is output i, which must be the last output. This demonstration assumes a sole-branch policy; a general merge must explicitly define how companion rules and paths survive.

A transaction merging coin A (n = 5) and coin B (n = 7), with an XPI input for the fee:

inputs                          outputs
0: XPI coin (fee)               0: XPI change
1: Counter A, n = 5   merge     1: Counter, n = 12
2: Counter B, n = 7   absorbed

A runs merge with arguments 5, M, 7:

  1. Its own state is genuine: Node(Leaf(data 5), M) equals BRANCHROOT.
  2. The other coin is a Counter holding 7: Node(Leaf(data 7), M) is on every path of the coin at input 2 (UTXOREQUIRESBRANCH). The same M serves, because it is the same contract.
  3. The transaction has exactly 2 outputs, its own position plus one. There is then no output at position 2, so B cannot have continued as a separate coin: every continuing method of B demands a successor there.
  4. Output 1 carries Node(Leaf(data 12), M) exclusively.

B runs absorbed with arguments 7, M, 5:

  1. Its own state is genuine.
  2. The coin at input 1 is a Counter holding 5.
  3. Output 1, the position before its own, carries Node(Leaf(data 12), M) exclusively.

What each check prevents:

Other outputs, such as change, sit at positions before the survivor's, opposite inputs that make no demand on them.

Two limits. The merge is only as trustworthy as the coins fed to it: anyone can create a coin whose root is a Counter with any n, so a contract that must not accept forged state has to check that the other coin carries its token, as described above. And a quantity that must never be duplicated is better held as a token amount, which consensus conserves, than as state.

LC-1 proposes explicit distinct successor/payout roles (for example 2*i and 2*i+1) for a method that continues and pays someone. Those checks are not implemented by this older paired-output sketch. The compiler must enforce nonoverlap in script; a builder allocation alone cannot prevent two inputs from counting the same output.

6. Cost of loops

A script that scans I inputs against O outputs does I×O body work per invocation. Repeating it on K inputs charges K×I×O, plus other costs. Execution is independent: no input is excused because another coin carries the same branch root. Static bounds ignore early exit and cache reuse (P05). The token rules above scan outputs once per token input, so a transaction moving K coins of one token to O outputs charges K×O for the rules.

7. Shared data

There are no read-only inputs. A transaction that needs data held in a shared coin, such as an oracle value, spends that coin and recreates it in the same transaction; the coin's own policy decides who may do so and under what conditions. Two transactions that use the same shared coin conflict, so they must be chained one after the other or the data must be supplied another way, such as a signed record passed as a witness argument. A signed record cannot carry an expiry (C22a).

Completion contract

Deliver these examples in order. Each becomes executable only when it includes source, assembly, bytecode, canonical arguments, initial coin records, complete transaction bytes, commitments, signing data, final stack, static cost and post-state/undo result, produced by pinned tools. Pair each with focused local conformance cases for its requirements. The schema for those records and the outstanding evidence are in validation.


References

  1. [Wuille, Nick, & Towns 2020a] Pieter Wuille, Jonas Nick, and Anthony Towns, "BIP 341: Taproot: SegWit version 1 spending rules", Bitcoin Improvement Proposals, January 2020.
  2. [Wuille, Nick, & Towns 2020b] Pieter Wuille, Jonas Nick, and Anthony Towns, "BIP 342: Validation of Taproot Scripts", Bitcoin Improvement Proposals, January 2020.
  3. [Möser, Eyal, & Sirer 2016] Malte Möser, Ittay Eyal, and Emin Gün Sirer, "Bitcoin Covenants", in Financial Cryptography and Data Security (FC 2016), LNCS vol. 9604, pp. 126–141, 2016.
  4. [O'Connor & Piekarska 2017] Russell O'Connor and Marta Piekarska, "Enhancing Bitcoin Transactions with Covenants", in Financial Cryptography and Data Security (FC 2017), LNCS vol. 10323, pp. 191–198, 2017.
  5. [Vogelsteller & Buterin 2015] Fabian Vogelsteller and Vitalik Buterin, "EIP-20: Token Standard", Ethereum Improvement Proposals, November 2015.
  6. [Entriken, Shirley, Evans, & Sachs 2018] William Entriken, Dieter Shirley, Jacob Evans, and Nastassia Sachs, "EIP-721: Non-Fungible Token Standard", Ethereum Improvement Proposals, January 2018.
  7. [Adams, Zinsmeister, & Robinson 2020] Hayden Adams, Noah Zinsmeister, and Dan Robinson, "Uniswap v2 Core", March 2020.