# ZC Standard contracts

> The SigmaFi ZC Standard contract set for developers, with its design rules, box registers, spend paths, verification recipe and exits.

Source: https://lithosprotocol.org/docs/sigmafi/contracts

**Level:** Expert

*Assumes ErgoScript, box registers, context extensions and the Ergo indexed node API.*

This page is the developer's reference for the contracts behind SigmaFi: what each one holds, how its
spend paths are chosen, and how to prove a bond token is genuine. Each contract's header comment, in the
Sigma-Finance-V2 repository, is the authoritative schema. This page explains how the pieces fit together.
What clients write on top of the contracts is on [The zcs1 off-chain standard](https://lithosprotocol.org/docs/sigmafi/offchain-standard),
and the pricing formulas are on [Pricing](https://lithosprotocol.org/docs/sigmafi/pricing).

## Where the trees come from

The Lithos client pins the compiled ErgoTrees of Sigma-Finance-V2 commit `adce8ac` and never compiles
them itself. `GET /sigmafi/zc/info` returns, for both markets, each contract's tree hash, template hash
and address, each expression's hash, and the zcs1 defaults. Read trees from there or from the pinned
reference rather than compiling the source: a different compiler version can produce different bytes.

All markets of one contract share a template hash, and each market has one address. The Ergo indexed
node looks boxes up by ErgoTree, template hash and token id, but not by register, which is why the
contracts are laid out this way.

## The contract set

The set has the following contracts, grouped by folder:

| Folder | Contract | Role |
|---|---|---|
| `core` | `Bond` | The live loan: holds the collateral, repays or liquidates into the vault |
| `core` | `BondVault` | Holds a settlement until the holder claims it |
| `P2P` | `Order`, `PricedOrder` | A borrower's request. The fill mints the bond token |
| `P2P` | `SaleOrder` | A fixed-price ask for any token |
| `P2P` | `PricedAsk` | An ask priced by an expression the seller picks |
| `P2P` | `LendOffer` | A lender's yield-curve bid that fills orders and buys from asks |
| `P2P` | `LotAuction` | A falling-price sale of a whole basket of tokens and ERG |
| `lender-scripts` | `FractionalMint`, `FractionalVault` | One bond unit into N shares, paid in kind |
| `lender-scripts` | `DutchAuctionMint`, `DutchAuctionVault` | The same, with a Selective or Dutch auction of liquidated collateral |
| `wrappers` | `WrapMint`, `WrapVault` | Custody for a capability token, released only by burning its receipt |

The following are **expressions**, not box scripts:

| Expression | Role |
|---|---|
| `MaturityLiquidation` | Liquidation at or after maturity |
| `ERG_SigUSD_Liquidation` | Liquidation at maturity, or before it below an oracle collateral ratio |
| `ERG_SigUSD_CollateralPolicy` | A lend offer's risk rule |
| `YieldOrder_Pricing`, `CurveOrder_Pricing` | A priced order's principal: two-point yield, or a window order's curve |
| `YieldAsk_Pricing`, `ERG_SigUSD_GuardedYield_Pricing` | A priced ask's price: two-point yield, optionally with a sale guard |
| `ERG_SigUSD_FillGuard` | An order's fill guard |

A host box commits to an expression's hash in a register. The spender supplies the serialized expression
in a context variable, and the host runs it with `executeFromVar`. A new rule is a new expression, and no
host contract changes. The ERG and SigUSD markets have their own compiled copy of each market-specific
contract and expression, `DutchAuctionMint` included. `BondVault`, `FractionalMint`, `FractionalVault`,
`DutchAuctionVault`, `MaturityLiquidation` and the wrap contracts are shared by both markets.

## Design rules

**Core and edge.** The bond and its vault are the core. Every contract that verifies a bond pins their
script hashes, so changing them starts a new generation that existing contracts cannot read. Orders,
offers, asks and mints are edge contracts. They hold funds only while open, and they meet through
conventions rather than each other's hashes, so new ones can be added without migrating anything.

**The three-unit rule.** A fill mints exactly three units of the bond token. Two stay in the bond, then
its vault, and one circulates. The two never split, and the holder of the circulating unit can never
assemble two. So for a genuine token X, the box holding two units of X is the loan's **state box**: the
live bond before settlement, the vault after. That is one lookup by token id, and one data-input check
on chain.

A live bond can also burn all three units on its extinguish path. Burning three units therefore does not
prove the vault was spent. Any contract that holds one unit and has a permissionless pull or sweep path,
such as the share vaults, must pin `BondVault`'s hash explicitly. Both share vaults do.

**One currency per loan.** A loan is lent and repaid in one currency, its market's repayment asset. Every
bond has principal and repayment in one unit, so simple yield to maturity is defined for every bond.

**Constants for markets, registers for terms.** The repayment asset is a compiled constant, so each market
has one address. Per-loan terms are registers, so every order of a market shares that address and other
contracts can read the terms. Comparisons against the asset constant use a runtime value, because a
constant-only test folds at compile time and would split the template.

**Nobody is assumed online.** Every step a third party can run carries a fee the user committed when
posting, at least 0.002 ERG where the contract sets a floor. Every box that waits on a user has an exit a
batcher can run without the user's signature.

## Order and PricedOrder

The borrower funds an order with the collateral and an expiry fee. Its registers are the following:

| Register | Type | Contents |
|---|---|---|
| R4 | `Coll[Long]` | Borrower terms, 7 to 64 values: 0 repayment, 1 principal nanoERG, 2 repayment ERG floor, 3 maturity height (mode 0), duration of at least 30 blocks (mode 1) or least duration (mode 2), 4 expiry height, 5 expiry fee (at least 0.002 ERG), 6 maturity mode, 7 on a payload only the liquidation rule reads |
| R5 | `Coll[(Coll[Byte], Long)]` | Principal tokens: none for ERG, one repayment token for a token loan |
| R6 | `Coll[Byte]` | Blake2b256 of the borrower's ErgoTree |
| R7 | `Coll[Byte]` | Hash of the liquidation expression |
| R8 | `Coll[Byte]`, optional | `Order`: hash of a fill guard expression. `PricedOrder`: `Coll[Coll[Byte]]` of exactly (pricing hash, guard hash or empty) |
| R9 | `Coll[Long]` | `PricedOrder` only: the pricing payload, at most 64 values |

For the oracle rule, R4(7) is the ratio in basis points and R4(8) the oldest oracle accepted, in blocks.
The fill guard's ratio is R4(9). In a `PricedOrder` the principal amounts in R4 and R5 are floors.

**The one-currency rule at a fill.** An ERG order has no principal tokens, a principal above 0, and a floor
no higher than the repayment. A token order has exactly one principal token, the repayment token, and at
most 1,000,000 nanoERG in both R4(1) and R4(2).

**Fill.** The order must be `INPUTS(0)`, so the bond token's id is the order's box id. Exactly three
units are minted. The outputs are fixed:

| Output | Contents |
|---|---|
| `OUTPUTS(0)` | The circulating unit, to any script the lender chooses. R4 to R6 are its EIP-4 name, description and decimals `"0"` |
| `OUTPUTS(1)` | The bond: `(asset, 2)` then the order's tokens. Value is the collateral plus the lender's fee reserve |
| `OUTPUTS(2)` | The principal plus the unused expiry fee, to the borrower, with R4 equal to the order's box id |

Context variable 1 carries the fill guard when one is named, and the guard runs with the order as `SELF`.
A `PricedOrder` also needs variable 2, its pricing expression. The bond records the start height, which
must lie within 8 blocks of the fill's `HEIGHT`, and its creation height must equal that start. Maturity
must leave at least one block to repay. A window order (mode 2) takes the maturity the lender chooses,
from R4(3) up to R9(0) blocks after the start.

**Cancel and expiry.** The borrower cancels at any height by co-spending a box under their script. From
the expiry height, anyone may return the order to the borrower, tagged with its id, and keep the expiry
fee. Variable 0 names the refund output. Neither path reads a pricing or guard expression, so a box
committed to an unknown expression can still exit.

## Bond

The bond's registers are the following:

| Register | Type | Contents |
|---|---|---|
| R4 | `Coll[Byte]` | Originating order id, which is also the token id |
| R5 | `Coll[Byte]` | Borrower script hash |
| R6 | `Coll[Long]` | Borrower terms, copied from the order, with a priced order's actual principal |
| R7 | `Coll[(Coll[Byte], Long)]` | Principal tokens |
| R8 | `Coll[Byte]` | Liquidation expression hash |
| R9 | `Coll[Long]` | (fee reserve, start height, maturity height) |

`tokens(0)` is `(asset, 2)`, and the collateral tokens follow. Collateral ERG is `value` less the fee
reserve. The bond has five spend paths, chosen by context variables:

| Path | Variables | Who | Rule |
|---|---|---|---|
| Repay | 1, 2 | Anyone, before maturity | Variable 1 names the vault output: `(asset, 2)` first, R4 the bond's id, R5 `0`, holding the repayment plus the fee reserve. Variable 2 names the collateral return to the borrower, tagged with the bond's id. With a borrower co-spend the return may hold up to the repayment less of the repayment asset, which is repaying from collateral |
| Liquidate | 0, 1 | Anyone, when the expression allows | Variable 0 is the expression R8 names. It decides eligibility and what the vault receives. The bond pins the vault script, `(asset, 2)`, the R4 tag and R5 `1`. The fee reserve pays the runner |
| Recollateralize | 3 | The borrower, before maturity | Same script, registers and tokens, nothing lower, more of something: ERG, a held token, or a token bond's repayment token. At most once per 60 blocks from the box's creation height, and each successor is stamped within 15 blocks of inclusion |
| Refresh | 9 | Anyone, once the box is over 525,600 blocks old | Re-creates the box unchanged, keeping up to 0.01 ERG as a bounty and never going below the fee reserve plus 0.001 ERG. Stamped 60 to 999 blocks back. Not allowed in the 720 blocks before maturity |
| Extinguish | none of 0, 1, 3, 9 | The borrower and the unit's holder, at any height | A borrower-script co-spend, `tokens(0) == (R4, 2)`, more than two units of the asset among the inputs and none among the outputs. Outputs are unconstrained |

Every settlement explicitly burns the bond's two units into the vault output. A builder that lets them
escape into change violates the bond. Never select a circulating unit as automatic funding for a
settlement: no unit of the asset may survive in the settlement's outputs except the two in the vault.

## BondVault

The vault holds `(asset, 2)` and the settlement. R4 names the bond box that settled, and R5 is `0` for a
repayment or `1` for a liquidation. The holder claims by spending the vault with the circulating unit and
burning all three units, and chooses the outputs freely. One transaction can sweep many vaults, each by
its own unit. Anyone may refresh a vault over two years old with variable 9.

## LendOffer

The offer's registers are the following:

| Register | Type | Contents |
|---|---|---|
| R4 | `Coll[Byte]` | Owner script hash |
| R5 | `Coll[Long]` | Fixed terms, then up to 20 curve points. ERG offers: 0 least yield, 1 and 2 least and most blocks to maturity, 3 batcher fee, 4 new-bond fee reserve, 5 collateral floor, 6 expiry, 7 least price, 8 oracle age, 9 least auction floor, 10 most auction expiry. Token offers add 11 original capital, 12 ERG budget, 13 least fill, 14 reward budget. Then `(yield bps, blocks left)` pairs, blocks strictly increasing |
| R6 | `Coll[Byte]` | The collateral policy's hash, followed on a continuation by the 32-byte id of the offer box it continued from |
| R7 | `Coll[Long]` | Share delivery terms |
| R8 | `Coll[Coll[Byte]]` | Share metadata for deliveries into a mint request |
| R9 | `Coll[Byte]` | The mint request script a delivery goes into, or empty to deliver the unit |

The offer buys from three sources, chosen by context variables: a new bond from an accepted order or
priced order, an existing bond unit from any ask, or Selective or Dutch shares from any ask. For an
existing unit it checks the origin from the order's serialized box and requires the live bond as a data
input. For shares it also checks the mint request's serialized box. Each offer tags its delivery and its
continuation with its own input id, so independent secondary purchases can share one transaction. New
bonds still need one transaction each, because the mint uses `INPUTS(0)`.

## Asks

Every ask follows one convention, so any lend offer can buy from any ask. An ask sells its `tokens(0)`. R4
is the seller's script hash. A purchase pays one payout box at the seller's script with R4 equal to the
ask's box id and R5, a `Long`, equal to the raw units paid for. A buyer reads the payout, not the ask's
price, and requires R5 to equal the units it received.

The two asks' registers are the following:

| Register | `SaleOrder` | `PricedAsk` |
|---|---|---|
| R4 | Seller script hash | Seller script hash |
| R5 | (price numerator, price denominator, least fill, expiry) | (floor numerator, floor denominator, least fill, expiry, N, then the pricing payload) |
| R6 | The ask a partial fill continued from | The pricing expression hash |
| R7 | | The bond token id |
| R8 | | The ask a partial fill continued from |

A `SaleOrder` charges `ceil(units × numerator / denominator)`. The ask box's ERG, 0.001 ERG plus its
refund fee, survives partial fills and is not returned separately on a full fill.

## LotAuction

A lot sells everything in its box, whole, to the first buyer, for one currency. R4 is the seller's script
hash and R5 is (opening, floor, start height, end height, expiry, refund fee). The price is the opening
until the start, falls in a straight line to the floor at the end, and holds until the expiry. On an ERG
lot the box's ERG returns to the seller with the payment. On a token lot the box may not hold the currency
itself. A lot's payout carries R4 and no R5, so no lend offer can match against a lot.

## Shares

`FractionalMint` and `DutchAuctionMint` are request boxes holding one bond unit. R7 is the owner script
hash, R8 is (N, pull fee, mint fee) followed on a Dutch mint by the auction terms, and R9 holds the share
token's EIP-4 metadata, copied into R4 to R6. Any batcher runs the mint with the request as `INPUTS(0)`,
so the share token's id is the request's box id. The mint creates 2N + 1 shares: N to the owner, and
N + 1 locked in the vault with the bond unit. The box holding N + 1 shares is the shares' state box.

A Dutch mint's auction terms are an opening and a floor in basis points of the repayment, a length and
an expiry in blocks, and an in-kind threshold of at least 100 raw units. A threshold of 100 is
**Selective**. A threshold of `Long` maximum is **Dutch**. The mint reads the repayment from the live
bond as a data input, or from the bond's serialized bytes in variable 1 when the bond has already settled.

The vaults' paths are the following:

| Path | Who | What it does |
|---|---|---|
| Pull | Anyone, for the pull fee | Spends the settled `BondVault`, verified by its pinned hash, burns all three bond units, and takes the settlement in |
| Partial claim | A holder | Burns u shares and takes `floor(balance × u / outstanding)` of each asset |
| Final claim | A holder of every share | Burns every outstanding share and the reserve and takes everything. Before the pull it returns the bond unit |
| Auction purchase | Anyone | Dutch vault in state 1 or 4 only |
| Refresh | Anyone | After two years, as for the bond |

A Dutch vault's R6 is its state: 0 repaid, 1 floor auction open, 2 sold or nothing to sell, 3 paid out in
kind, 4 excess auction open. R7 holds the auction terms and R8 the auction's currency. The state is fixed
at the pull, so nothing later can move an auction from one case to the other.

## Wraps

`WrapMint` holds the token, the owner hash in R4, the mint fee in R5 and the receipt's EIP-4 data in R6.
Any batcher mints three receipt units, whose id is the request's: one to the owner, two and the token
into a bare `WrapVault`. The vault must receive at least the request's value less the mint fee and
1,000,000 nanoERG, so the owner's refresh reserve lands in the vault. The request must be its
transaction's **only input**, so nothing the token has authority over can be spent beside it.
`WrapVault` releases the token only when all three receipt units burn, and its refresh must also be the
only input.

## Verifying a bond token

A token X is a genuine standard bond token when both of the following hold:

1. **Origin.** The box whose id is X was spent as an accepted `Order` or `PricedOrder`. Off chain, fetch
   that box by id from the indexed node and compare its full ErgoTree. On chain, a contract takes the
   serialized box in a context variable, checks that its Blake2b256 is X, and checks that the
   deserialized box carries the order script.
2. **State.** The box holding two units of X is the state box. Under the bond script the loan is live and
   its registers are the terms. Under the vault script it has settled.

A hand-made box under the bond script proves nothing by itself. Always check the origin. Shares go one
link further: a share token Y is genuine when the box whose id is Y was spent under a standard mint
script holding a genuine unit X. A wrap receipt is verified the same way against `WrapMint`.

## Exits

Every box that waits on someone has the following way out:

| Box | Owner, any time | Anyone |
|---|---|---|
| Order, PricedOrder | Cancel | From expiry, refund to the borrower for the expiry fee |
| LendOffer | Cancel | From expiry, refund to the owner for the batcher fee |
| SaleOrder, PricedAsk | Cancel | From expiry, refund to the seller for the ERG above 0.001 ERG |
| Share or wrap mint request | Cancel | The mint itself, for the mint fee |
| Bond | Repay, recollateralize, extinguish | Liquidate when the rule allows; refresh after two years |
| BondVault, share vaults | Claim | Pull for the pull fee, auction purchases, refresh after two years |
| WrapVault | Unwrap | Refresh after two years, as the only input |
| LotAuction | Cancel | Purchase at the current price; from expiry, refund for the refund fee |

Refunds are tagged with the box's id, so an owner that is a contract can recognise its funds. Nothing
sweeps lost shares or a lost circulating unit: their claims stay stranded.

## Cost and size

The heaviest standard transaction, two offers buying from two priced asks at once, measured 37,345 cost
units and 12,376 bytes in the offline harness. That is 3.7% of the node's default per-transaction cost
limit. A block fills by size before cost, at about 100 such transactions. A wallet filling an order costs
about 20,198 and 2,806 bytes, and a repayment about 20,021 and 2,183 bytes.

## Limits and assumptions

The contracts rely on the following:

- Each market's constants agree. An order's repayment token must match its bond's, and an offer's hashes
  must be its market's. Scripts cannot check one another's constants, so clients pin the published set.
- Liquidation rules, collateral policies and pricing expressions are commitments, not proofs. Both
  parties inspect them, and a client checks that a bond's rule is the one compiled for its market.
- The ERG and SigUSD rules trust the USD oracle pool's identity NFT and value SigUSD at $1.
- Only live bonds can be bought by an offer or priced by a yield ask.
- A share's value in an offer or a yield ask ignores the share vault's own ERG.
- Storage rent is outside script evaluation. The paid refresh protects boxes only if someone sends it in
  the two years after it opens.
- A capability token put raw into an order, bond or ask lends its authority to whoever spends that box.
  Wrap it first.

## Next steps

- [The zcs1 off-chain standard](https://lithosprotocol.org/docs/sigmafi/offchain-standard): what clients write into these boxes, and how batchers serve them.
- [Pricing](https://lithosprotocol.org/docs/sigmafi/pricing): the yield and curve formulas the expressions check.
- [Building on the Lithos API](https://lithosprotocol.org/docs/sigmafi/api): reading these boxes and building their transactions through a Lithos client.
