On this page
  1. §0 The area in one paragraph
  2. 1. Assets, prices and the tables
  3. 2. CreateSwapOffer (18)
  4. 3. AcceptSwapOffer (19)
  5. 4. CancelSwapOffer (20)
  6. 5. CreateMarket (21)
  7. 6. PlaceOrder (22): hold, match, rest
  8. 7. CancelOrder (23)
  9. 8. Order expiry and market rent
  10. 9. Ledger rows, views and the consensus/local split

15 — The exchange: swap offers and the order book

Edition 0.6.1 · verified against the reference implementation, version 0.6.1

Out of scope the fee floor and refund (04); the step rule (14 §1); account groups and the same-account test (18); the transact-policy bounce (08); the apps that stake tokens (16); the bridge coins' origin (06)

§0 The area in one paragraph

Two primitives trade assets, and both treat every asset alike: ZBC is asset id 0, any token row is an asset by its id, and nothing is ever reserved at admission for either, only checked. A swap offer is a fixed, all-or-nothing exchange: the maker's give side leaves its balance at creation and sits in the offer until one taker pays the want side in full, or the maker cancels; offers have an optional expiry (judged on the block's own clock, never on the taker's stamp) and an optional designated counterparty, and the chain never sweeps them. A market is a pair (base, quote) that costs a fixed creation fee held as rent; orders on it hold the base (sell) or the quote at the limit price (buy) and are matched at placement against the resting opposite side in price order, then ascending order id, each fill at the resting order's price, with a taker fee in basis points paid to the block's blocksmith in the asset the taker receives (when the blocksmith does not earn at that block, a ZBC fee goes to the lottery carry and a token fee is not taken); the remainder rests, or is refunded for an immediate-or-cancel ("market") order; resting orders expire by the previous block's timestamp at the start of each block and can be cancelled. The market's creation fee is twelve periods of rent, every order transaction tops it up with a fifth of its own fee, and a market that cannot pay a period (or whose token is gone) is pruned: its resting orders refunded, the rest to the longevity pool. An order's notional must be at least 0.025 ZBC and a taker never fills its own resting order. An offer's designated counterparty is a typed account of any kind that can sign. Prices are quote atomic units per base atomic unit scaled by 10⁸; every product is floored in 128-bit arithmetic, except the market's rent and its fee share, which round up. ZBC is never burned: the rounding unit a resting bid would have kept is returned to it at the fill.

1. Assets, prices and the tables

Purpose. What every mechanism below moves and records.

Inputs. Block 0 and the transactions below.

Output and effect. An asset is token_id 0 (the ZBC balance, 07) or a token (14); a move of asset 0 is a balance change with a ledger row, a move of a token is a token balance change with no row. price = quote atomic units per base atomic unit × PRICE_SCALE 100,000,000; quote(amount, price) = floor(amount × price / 10⁸) in 128-bit, saturating at ±(2⁶³−1); bps(x, b) = floor(x × b / 10,000) likewise. Tables, each keyed (id, block_height) and versioned (07 §2) except trade:

Table Columns id
swap_offer maker_address, give_token_id, give_amount, want_token_id, want_amount, counterparty_address (empty = anyone), expiry (unix s, 0 = never), status 0 Open / 1 Filled / 2 Cancelled / 3 Expired (never written) the CreateSwapOffer's tx.id
market base_token_id, quote_token_id, creator_address, deposit (the rent balance), paid_through_height, status 0 Active / 1 Pruned (written when a market is pruned, §8) the CreateMarket's tx.id
order_book market_id, maker_address, side 0 Buy / 1 Sell, price, amount, remaining, status 0 Open / 1 Filled / 2 Cancelled / 3 Expired, expiry (unix s, 0 = good till cancelled) the PlaceOrder's tx.id
trade market_id, taker_order_id, maker_order_id, price, amount, taker_fee, timestamp, block_height; key (taker, maker); append-only —

Parameters (consensus, governable by 17, each moving at most +20 % / half per snapshot cycle): market_creation_cost (clamped to 1 … 1,000,000,000,000; compiled 5,000,000,000; TestNet and DevNet 5,000,000,000) and exchange_taker_fee_bps (clamped to 1 … 100; compiled 10; TestNet and DevNet 10).

Column types: ids, token ids, amounts, prices, remaining, deposit, taker_fee signed 64-bit; addresses typed account bytes (01), counterparty_address empty for an open offer; expiry and timestamp signed 64-bit unix seconds; side, status small integers; heights unsigned 32-bit; latest 0/1. A change writes a new version at the block's height (07 §2); a rollback to H deletes the rows above H (the trade rows above H included). Reads the logic depends on: an offer, market or order by id (its latest row); the Open orders of one market on one side, sorted as §6 step 4 says; the Active market with a given (base, quote); the Open orders with expiry ≠ 0 in ascending id (§8); the number of trade rows of a market, read only by the deposit refund of market_deposit_refund below market_rent (§6), so never on a chain where market_rent is at 0 (every live chain). trade is rolled back like every height-stamped table.

How to compute it. As stated.

Rule activation. None.

Rejections and errors. None.

Vector. computed.

  • Input: quote(50,851,885,007, 96,027,100); bps(1,000,000,000, 10).
  • Expected output: floor(50,851,885,007 × 96,027,100 / 10⁸) = 48,831,590,467; 1,000,000.
  • Input: GET /api/v1/exchange/markets on a chain with one Active market M (base 13, quote 0, deposit 5,010,000,000) and no trade. Expected: {"markets":[{"id":"<M as a signed decimal string>","base_token_id":13,"quote_token_id":0,"deposit":5010000000}]}; /exchange/trades?market=<M> → {"trades":[]}.

Test cases · §1

2 cases · 2 valid · 1 reference

The quote of 50,851,885,007 at 0.960271 and ten basis points of 10 ZBC15-1-quotevalid

Loading the test widget…

The markets view of a chain with one Active market M and no trade15-1-marketsvalidreference

A stated value: there is nothing to compute. A compatible node shows the same value.

markets
{"markets":[{"id":"<M as a signed decimal string>","base_token_id":13,"quote_token_id":0,"deposit":5010000000}]}
trades
{"trades":[]}

Defects to match. (1) The hint document's type numbers and bodies are stale; the code's are below.

2. CreateSwapOffer (18)

Purpose. Lock the give side and publish a fixed exchange.

Inputs. Body: exactly 40 bytes (an open offer), or exactly 44 + n bytes (an offer to one counterparty):

Offset Length Field Encoding
0 8 give_token_id i64 LE (0 = ZBC)
8 8 give_amount i64 LE > 0, multiple of the give token's step
16 8 want_token_id i64 LE
24 8 want_amount i64 LE > 0, multiple of the want token's step
32 8 expiry i64 LE unix seconds; 0 = never
40 4 (optional) n u32 LE, the counterparty's length; present only in the 44 + n form, n ≥ 4
44 n (optional) counterparty the counterparty's typed account (01: its 4-byte LE type, then its key or hash), e.g. 36 bytes for a ZooBC account, 24 for an Ethereum one, 32 for a Cardano one

Output and effect. Order: a leg finer than its token's step → paid no-op; the fee (charged as in 04 §5; unaffordable → block invalid); the give side leaves the sender (asset 0: row event 54 −give; a token: no row); a refusal there (spent earlier in the same block) → nothing more, fee kept; the row: id = tx.id, maker = the sender as presented (08), the five fields, the counterparty bytes exactly as given (empty for an open offer), status Open. Then 04 §5.

How to compute it. The body shape: size 40 → open offer; size < 44 otherwise → not a body; else n = u32 LE at offset 40, and the body is valid only when n ≥ 4 and size = 44 + n exactly. A counterparty must be a well-formed address (01 §4) whose type can sign: types 0 ZBC, 1 BTC, 4 ETH, 5 P2PKH, 6 P2SH, 7 P2WPKH, 9 Taproot, 11 Solana, 12 Polkadot, 13 Cardano, 14 Ripple, 15 Tron, 16 Tezos (the escrow approver's list); types 2 (Empty), 3 (Estonia eID), 8 (P2WSH), 10 (DataSet, ZBS_) and every unknown type cannot. A counterparty in a full-key form (an Ethereum or Tron type followed by a 64-byte key, a Bitcoin legacy, P2PKH or P2WPKH type followed by a 33- or 65-byte key, 01) is refused: no transaction can be sent from it, so nobody could take the offer.

Stateless checks, in this order (admission, and block validation: a block carrying a failure is invalid): when the body is ≥ 32 bytes, "Swap amounts must be positive" (a leg ≤ 0); the shape, "CreateSwapOffer: the body is 40 bytes, or 40 then a u32 length and the counterparty's typed account"; then, with a counterparty, "CreateSwapOffer: counterparty: <the address-shape error of 01 §4>", "CreateSwapOffer: counterparty: a full-key account form (an Ethereum or Tron key, a Bitcoin key) is not an account: no transaction can be sent from it; name the 20-byte address (rule canonical_account_forms)" and "CreateSwapOffer: the counterparty's address kind cannot sign, so nobody could take the offer". Admission (state): "CreateSwapOffer: amounts must be positive", "CreateSwapOffer: amount is finer than the token's decimals allow (token ID moves multiples of STEP)" (an unknown token has step 1), "CreateSwapOffer: insufficient balance for the give amount" (spendable ZBC or token balance ≥ give). Execution (block invalid): "Invalid CreateSwapOffer body" (not a body), "Swap amounts must be positive", "Fee cannot be negative".

Rule activation. state_answer_noop, canonical_account_forms (the full-key counterparty), active from height 0 on every chain.

Rejections and errors. As listed. An unknown want token is accepted (nothing checks it). A body of 41–43 bytes, or of 44 + n bytes with a different n, or with n < 4, is not a body: in particular a 76-byte body whose bytes 40…75 are a bare 36-byte account is read as n = the account's type (0 for ZooBC → n < 4) and refused.

Vector. computed.

  • Input: CreateSwapOffer (type 18) by 00000000B6675786BEDF28B3E7DCD8BAC9BF99758B3A64604570BFFD12FD10CBF20B39EA, fee 5,000,000, body (40 bytes) 0500000000000000 00E1F50500000000 0000000000000000 004647FB17000000 0000000000000000 = give 100,000,000 of token 5 (ZETH) for 103,000,000,000 ZBC, no expiry, open; call its id O (the LE i64 of the first 8 bytes of the transaction's hash; e.g. a hash beginning 6C697017F269E7BB gives O = −4,906,836,780,500,620,948).
  • Expected output: the maker's ZETH −100,000,000 (no ledger row: a token leg); the row (O, the maker, 5, 100,000,000, 0, 103,000,000,000, counterparty empty, expiry 0, status Open); the fee's overpay above the floor refunded (04). /api/v1/exchange/offers lists {"id":"<O>","maker":"00000000b667…39ea","give_token_id":5,"give_amount":100000000,"want_token_id":0,"want_amount":103000000000,"counterparty":"","expiry":0,"status":0}.
  • Input: the same 40 bytes followed by 24000000 and the 36-byte ZooBC account 00000000120EE4CA9D258D75656901EC4837373E07763369AD75ED8D63FA31C7E0B7E807 (80 bytes). Expected: the same offer with counterparty = those 36 bytes; only that account (or its group) can accept. An Ethereum counterparty: the 40 bytes ‖ 18000000 ‖ 04000000 ‖ the 20-byte address (68 bytes).
  • Invalid input: the 40 bytes followed directly by the 36-byte account (76 bytes; n reads 0) → "CreateSwapOffer: the body is 40 bytes, or 40 then a u32 length and the counterparty's typed account" (a block carrying it is invalid). A counterparty 0A000000 ‖ 32 bytes (a ZBS_ address, 80 bytes) → "CreateSwapOffer: the counterparty's address kind cannot sign, so nobody could take the offer". The 40 bytes followed by 44000000 ‖ 04000000 ‖ 79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8 (112 bytes: an Ethereum counterparty in its full-key form, the 64-byte key of the secp256k1 private key 1) → "CreateSwapOffer: counterparty: a full-key account form (an Ethereum or Tron key, a Bitcoin key) is not an account: no transaction can be sent from it; name the 20-byte address (rule canonical_account_forms)"; the same counterparty in its 20-byte form, the 40 bytes ‖ 18000000 ‖ 04000000 ‖ 7E5F4552091A69125D5DFCB7B8C2659029395BDF (68 bytes), is accepted. A body with give_amount 0 → "Swap amounts must be positive".

Test cases · §2

8 cases · 4 valid · 4 invalid

An open offer of 1 ZETH for 1,030 ZBC, its id O from a hash beginning 6C697017F269E7BB15-2-openvalid

Loading the test widget…

The same offer to one ZooBC account15-2-counterpartyvalid

Loading the test widget…

The same offer to one Ethereum account15-2-counterparty-ethvalid

Loading the test widget…

An account appended without its length15-2-bare-accountinvalid

Loading the test widget…

A ZBS_ address cannot take an offer15-2-zbs-counterpartyinvalid

Loading the test widget…

An Ethereum counterparty in its full-key form (112-byte body)15-2-full-key-counterpartyinvalid

Loading the test widget…

The same counterparty in its 20-byte form (68-byte body) is accepted15-2-twenty-byte-counterpartyvalid

Loading the test widget…

A give amount of 015-2-zero-giveinvalid

Loading the test widget…

Defects to match. (1) The give is not reserved at admission: a second spend admitted in the same block makes the offer a paid no-op with no row. (2) expiry is not checked against the time at creation: an offer born expired is accepted and can only be cancelled.

3. AcceptSwapOffer (19)

Purpose. A taker fills an offer in full.

Inputs. Body: offer_id (8, i64 LE); bytes beyond 8 ignored.

Output and effect. Unknown offer → block invalid; the fee (unaffordable → block invalid); then each of these is a paid no-op: status ≠ Open; expiry ≠ 0 and the block's timestamp (the timestamp of the block the accept is in, rule liquid_chain_clock) ≥ expiry; the taker is the maker (the same-account test of 18 §1); a counterparty is set and the taker is not it (the same test, so a member of the counterparty's group may take it); the taker cannot pay the want amount. Otherwise, atomically: the taker −want (row event 56 for asset 0), the maker +want (event 56), the taker +give (event 56); the offer becomes Filled (new version). Then 04 §5.

How to compute it. Admission mirrors: "AcceptSwapOffer body too short", "AcceptSwapOffer: unknown offer", "… offer not open", "… offer expired" (at submit: the transaction's own timestamp ≥ expiry, the only clock admission has), "… cannot accept own offer", "… not the designated counterparty", "… insufficient balance for the want amount"; at block assembly the candidate block's timestamp is the clock: "AcceptSwapOffer: offer expired at the block's clock" leaves the accept out of a block whose timestamp ≥ expiry. Execution (block invalid): "Invalid AcceptSwapOffer body", "Fee cannot be negative", "Unknown swap offer".

Rule activation. liquid_chain_clock (the block's clock; active from height 0 on every chain).

Rejections and errors. As listed.

Vector. computed on the offer O of §2.

  • Input: AcceptSwapOffer (type 19) by a taker T (not the maker) holding ≥ 103,000,000,000 spendable ZBC plus the fee, body = LE64(O) (e.g. 6C697017F269E7BB for O = −4,906,836,780,500,620,948).
  • Expected output: T −103,000,000,000 ZBC (row event 56), the maker +103,000,000,000 ZBC (row event 56), T +100,000,000 ZETH (no row); the offer Filled (status 1).
  • Input (the clock): the same offer with expiry 1,793,715,000; an accept stamped 1,793,714,990 in a block whose timestamp is 1,793,715,005. Expected: admitted (its own stamp is before the expiry), not selected for that block ("AcceptSwapOffer: offer expired at the block's clock"), and a paid no-op if a block with that timestamp carries it; an accept stamped 1,793,715,001 is refused at admission "AcceptSwapOffer: offer expired".
  • Invalid input: the same accept sent by the maker → refused at admission "AcceptSwapOffer: cannot accept own offer"; mined, a paid no-op. A second accept after the fill → "AcceptSwapOffer: offer not open". Body 0000000000000000 → "AcceptSwapOffer: unknown offer"; mined, the block is invalid ("Unknown swap offer").

Test cases · §3

10 cases · 4 valid · 6 invalid

A taker accepts the offer15-3-acceptvalid

Loading the test widget…

An accept stamped before the expiry is admitted but not selected for a block whose clock has passed it15-3-clock-selectioninvalid

Loading the test widget…

Carried in a block whose timestamp is past the expiry, the accept is a paid no-op15-3-clock-minedvalid

Loading the test widget…

An accept stamped after the expiry is refused at admission15-3-clock-stampinvalid

Loading the test widget…

An accept stamped before the expiry in a block before the expiry fills the offer15-3-clock-in-timevalid

Loading the test widget…

The maker cannot accept its own offer15-3-owninvalid

Loading the test widget…

Mined, the maker's own accept is a paid no-op15-3-own-minedvalid

Loading the test widget…

An accept after the fill15-3-filledinvalid

Loading the test widget…

An accept of offer 015-3-unknowninvalid

Loading the test widget…

Mined, an accept of offer 0 makes the block invalid15-3-unknown-minedinvalid

Loading the test widget…

Defects to match. (1) Two accepts of one offer in a block: the first fills, the second pays its fee for nothing. (2) Admission judges the expiry on the taker's own stamp, which the taker chooses inside the envelope's timestamp bound (03), so an accept of an offer that expires within that bound can be admitted and then be a paid no-op; the block's verdict is the chain clock's alone.

4. CancelSwapOffer (20)

Purpose. The maker takes the give side back.

Inputs. Body: offer_id (8, i64 LE).

Output and effect. Unknown offer → block invalid; the fee; sender ≠ maker (byte equality) → paid no-op; status ≠ Open → paid no-op; else the maker +give (asset 0: row event 55) and the offer becomes Cancelled. Then 04 §5. There is no other way an offer ends: expiry only blocks acceptance.

How to compute it. Admission: "CancelSwapOffer body too short", "CancelSwapOffer: unknown offer", "… only the maker can cancel", "… offer not open". Execution (block invalid): "Invalid CancelSwapOffer body", "Unknown swap offer", "Fee cannot be negative".

Rule activation. None.

Rejections and errors. As listed.

Vector. computed on the offer O of §2.

  • Input: CancelSwapOffer (type 20) by the maker, body = LE64(O).
  • Expected output: the fee; the maker +100,000,000 ZETH (no row: a token leg); the offer Cancelled (status 2) in /accounts/<maker>/offers.
  • Invalid input: the same cancel from another account → refused at admission "CancelSwapOffer: only the maker can cancel"; mined, a paid no-op.

Test cases · §4

2 cases · 1 valid · 1 invalid

The maker cancels the offer15-4-cancelvalid

Loading the test widget…

Another account cannot cancel it15-4-not-makerinvalid

Loading the test widget…

Defects to match. A member of a group cannot cancel an offer the group made unless the dispatcher presents the group's address (08, 18); the executor compares bytes.

5. CreateMarket (21)

Purpose. Open a trading pair.

Inputs. Body (24 bytes; bytes beyond ignored):

Offset Length Field Encoding
0 8 base_token_id i64 LE
8 8 quote_token_id i64 LE
16 8 deposit i64 LE ≥ 0; ignored except for its sign

Output and effect. Order: base = quote → block invalid; either token with a step > 1 (fewer than 8 decimals) → block invalid; a negative deposit field or fee → block invalid; an unknown token (id ≠ 0 with no row) → paid no-op; an Active market with the same (base, quote), in that orientation → paid no-op; the fee; the creation cost (market_creation_cost) leaves the sender (row event 57 −cost; unaffordable → nothing more, fee kept); the row: id = tx.id, creator = sender, deposit = the cost paid, status Active, paid_through_height = this height. The deposit is the market's rent balance (twelve periods pre-funded, ceil(market_creation_cost / 12) per period), drawn per period by §8. Then 04 §5.

How to compute it. Stateless (≥ 16 bytes): "Market base and quote token must differ". Admission: "CreateMarket body too short" (< 24), "CreateMarket: base and quote must differ", "CreateMarket: a token with fewer than 8 decimals cannot be traded on the order book", "CreateMarket: unknown token ID (0 = ZBC)", "CreateMarket: insufficient balance for the creation fee + tx fee" (spendable ≥ cost + fee), "CreateMarket: market already exists for this pair". Execution (block invalid): "Invalid CreateMarket body", "base and quote tokens must differ", the decimals text above, "negative deposit/fee".

Rule activation. market_known_tokens, market_rent (height 0).

Rejections and errors. As listed.

Vector. computed.

  • Input: CreateMarket (type 21) at height 513, fee 5,000,000, body (24 bytes) 0E00000000000000 0100000000000000 0000000000000000 = base 14 (ZUSDT), quote 1 (ZUSD), deposit field 0; call its id M (the LE i64 of the first 8 bytes of the transaction's hash; e.g. a hash beginning 2799E29A8DC13AFA gives M = −415,807,201,645,258,457).
  • Expected output: the creator −5,000,000,000 (row event 57); the row (M, 14, 1, the creator, deposit 5,000,000,000 (the parameter, not the body's 0), paid_through_height 513, Active); /exchange/markets shows "deposit":5000000000 until an order feeds it.
  • Invalid input: base = quote (0E00… twice) → "Market base and quote token must differ" (stateless; makes a block invalid). The same pair again while that market is Active → "CreateMarket: market already exists for this pair" (admission; mined, a paid no-op).

Test cases · §5

3 cases · 1 valid · 2 invalid

The ZUSDT/ZUSD market created at block 513, its id M from a hash beginning 2799E29A8DC13AFA15-5-createvalid

Loading the test widget…

A market of a token against itself15-5-same-tokeninvalid

Loading the test widget…

The same pair while that market is Active15-5-existsinvalid

Loading the test widget…

Defects to match. (1) The body's deposit field is dead: the deposit is always the parameter. (2) (base, quote) and (quote, base) are two distinct markets. (3) The creation cost is not reserved at admission.

6. PlaceOrder (22): hold, match, rest

Purpose. Buy or sell base against the book.

Inputs. Body (34 bytes; bytes beyond ignored):

Offset Length Field Encoding
0 8 market_id i64 LE
8 1 side 0 buy, 1 sell
9 8 price i64 LE > 0, quote per base × 10⁸
17 8 amount i64 LE > 0, base atomic
25 1 flags bit 0 market (immediate-or-cancel at price), bit 1 post-only; both set is refused at admission
26 8 expiry i64 LE unix seconds; 0 = good till cancelled

Output and effect. Order of operations:

  1. Block-invalid faults: unparseable body, amount or price ≤ 0, side not 0/1, fee < 0, unknown market, market not Active.
  2. quote(amount, price) = 0 (rule market_min_notional) or quote(amount, price) < ORDER_MIN_NOTIONAL_UNITS (= 100,000,000 / 40 = 2,500,000, 0.025 ZBC; rule permanent_state_priced) → a paid no-op here; the stateless check below refuses both first, so such an order never reaches a block that is valid. Then (rule market_rent) the order feeds the market: the sender pays MARKET_FEE_SHARE_BPS = 20 % of its declared fee tx.fee, ceil(fee × 2,000 / 10,000), on top of the fee into the market's deposit (row event 72 −contribution on the sender; the fee itself is untouched), capped so the deposit never exceeds 24 periods of rent (24 × the rounded-up rate, saturating); a sender that cannot cover it feeds nothing and the order stands.
  3. The fee (unaffordable → block invalid).
  4. The opposite side of the book: asks (for a buy) in ascending price then ascending id, bids (for a sell) in descending price then ascending id; only Open orders of this market.
  5. Post-only: if the order is also market, or the best opposite price crosses (best ask ≤ price for a buy, best bid ≥ price for a sell) → nothing more: no hold, no row, fee kept.
  6. The hold: buy → hold = quote(amount, price) of the quote asset (row event 58 for asset 0); sell → amount of the base (event 58). A refusal → nothing more, fee kept, no row.
  7. Matching, in book order, while remaining > 0 and the resting price does not pass the limit (buy: maker price ≤ price; sell: maker price ≥ price); a resting order whose maker_address equals the taker's sender byte for byte is skipped (rule permanent_state_priced: a taker never fills its own order): fill = min(remaining, maker.remaining), tp = maker.price, q = quote(fill, tp), fee_bps read once per order. The fee's recipient per asset: the blocksmith's account when the blocksmith earns at this block (the income view as of the block: not missing, not suspended, mature; 09 §12); otherwise, for ZBC (asset 0), the lottery carry 00000000 ‖ "ZBCCARRY" ‖ 24 × 0x00, which this block's coinbase lottery pays out with the block fees (21 §2); for a token, no fee (the taker keeps it: the lottery pays ZBC only); with no blocksmith account (genesis, off-chain) no fee. Buy: taker +(fill − fee) base (event 56) with fee = bps(fill, fee_bps) when the base has a recipient, else 0; the recipient +fee base (event 60); maker +q quote (event 56). Sell: taker +(q − fee) quote (event 56) with fee = bps(q, fee_bps) when the quote has a recipient; the recipient +fee quote (event 60); maker +fill base (event 56); and the maker (a buyer) gets back its rounding unit: residue = quote(maker.remaining, tp) − q − quote(maker.remaining − fill, tp), credited when > 0 (event 59), so a resting bid always holds exactly quote(remaining, price). The maker's row: remaining −fill, Filled when 0 (new version); a trade row (market, taker = this tx.id, maker id, tp, fill, taker fee, this transaction's timestamp, height). The blocksmith is the registry account of the block's blocksmith key as of the block; a failed read of who earns fails the block.
  8. The remainder: rests = remaining > 0 and not market. Buy: keep = rests ? quote(remaining, price) : 0, refund = hold − Σq − keep, credited when > 0 (event 59). Sell, market, remaining > 0: the remaining base back (event 59).
  9. The order row: id = tx.id, maker = sender, side, price, amount, remaining, status Open when it rests else Filled, expiry.

Then 04 §5.

How to compute it. Stateless (≥ 25 bytes): "Order price must be positive", "Order amount must be positive", "Order too small: the quote amount rounds to zero (raise the amount or the price)", "PlaceOrder: the order's quote notional is below the minimum of 0.025 units of the quote token" (quote < 2,500,000). Admission: "PlaceOrder body too short" (< 34), "PlaceOrder: bad amount/price/side", "PlaceOrder: market and post-only are mutually exclusive", "PlaceOrder: unknown market", "PlaceOrder: market inactive", "PlaceOrder: token ID of this market no longer exists" (an expired token), "PlaceOrder: insufficient balance to hold the order" (the hold of step 6 against the spendable ZBC or the token balance). Execution (block invalid): "Invalid PlaceOrder body", "amount must be positive", "price must be positive", "bad side", "Fee cannot be negative", "Unknown market", "Market is not active".

Rule activation. market_min_notional, market_deposit_refund, permanent_state_priced, market_rent and payout_instant (the one instant of who earns), height 0. Under market_rent the deposit is rent and no fill ever returns it to the creator (market_deposit_refund alone would return the creation cost to the creator at the market's 100th fill; with both at 0, market_rent decides and that refund never happens). The taker-fee recipient and the maker's rounding unit have no rule.

Rejections and errors. As listed.

Vector. computed (a market M = −1,822,012,396,596,789,138, base 13 ZUSDC, quote 0 ZBC, created with deposit 5,000,000,000).

  • Input: PlaceOrder (type 22) by A = 00000000B6675786…39EA, fee 5,000,000, body (34 bytes) 6E807DF460E9B6E6 00 DC41B90500000000 CF2F02D70B000000 02 0000000000000000 = LE64(M), buy, price 96,027,100, amount 50,851,885,007, post-only, no expiry; no ask rests at or below 96,027,100.
  • Expected output: no crossing ask; hold = quote(50,851,885,007, 96,027,100) = 48,831,590,467 ZBC (row event 58); the order rests Open with remaining = amount; the market's deposit +1,000,000 = ceil(5,000,000 × 2,000 / 10,000) (row event 72 on A).
  • Input: ten such orders by A (each feeding 1,000,000, so deposit 5,010,000,000), at the prices and amounts below. Expected: /exchange/orderbook?market=-1822012396596789138 answers bids [[99743200,38070622999],[98650000,9820168999],[97427000,42513945330],[96646200,156027154086],[96027100,50851885007]], asks [[100754200,158612849098],[101357900,36948508905],[102637000,16553662538],[103746195,90769078148],[104180495,49162968450]] (one order per level, all by A).

computed on that book, taker T ≠ A, exchange_taker_fee_bps 10, the blocksmith earns:

  • Input: a market buy (flags 1) of 200,000,000,000 at price 101,357,900. Expected: hold 202,715,800,000 ZBC; fill 158,612,849,098 at 100,754,200 → q 159,809,107,205 ZBC to the maker, T +158,454,236,249 ZUSDC, the blocksmith +158,612,849 ZUSDC (event 60), that ask Filled; fill 36,948,508,905 at 101,357,900 → q 37,450,232,707 to the maker, T +36,911,560,397, the blocksmith +36,948,508, that ask Filled; the next ask (102,637,000) passes the limit; refund 202,715,800,000 − 197,259,339,912 = 5,456,460,088 ZBC (event 59); the order row Filled with remaining 4,438,641,997; two trade rows.
  • Input: a market sell of 50,000,000,000 at price 99,000,000. Expected: fill 38,070,622,999 at 99,743,200 → q 37,972,857,639; T +37,934,884,782 ZBC, the blocksmith +37,972,857 ZBC, the maker +38,070,622,999 ZUSDC; the next bid (98,650,000) is below the limit; the remaining 11,929,377,001 ZUSDC back to T (event 59).
  • Input: the same market sell when the blocksmith does not earn at the block. Expected: the 37,972,857 ZBC fee goes to the lottery carry ZBCCARRY (event 60). The market buy above, same case: the fee is in ZUSDC and is not taken, T gets 158,612,849,098 + 36,948,508,905.
  • Input: a limit buy of 1,000,000,000 at 99,500,000. Expected: hold 995,000,000, no ask at or below, rests Open, nothing refunded.
  • Input (the maker's unit): a resting bid of 3 at price 150,000,000 (holds 4), three sell fills of 1. Expected: each fill pays 1; the second fill returns the residue quote(2, 1.5) − 1 − quote(1, 1.5) = 3 − 1 − 1 = 1 to the maker (event 59).
  • Invalid input: amount 99,999,999 at price 1 → "Order too small: the quote amount rounds to zero (raise the amount or the price)" (stateless); amount 2,499,999 at price 100,000,000 (quote 2,499,999 < 2,500,000) → "PlaceOrder: the order's quote notional is below the minimum of 0.025 units of the quote token" (stateless: a block carrying it is invalid); flags 3 → "PlaceOrder: market and post-only are mutually exclusive" (admission).

Test cases · §6

13 cases · 10 valid · 3 invalid · 1 reference

A post-only bid of 50,851,885,007 ZUSDC at 0.960271 with no crossing ask rests15-6-post-only-bidvalid

Loading the test widget…

The order book after ten such orders by A15-6-bookvalidreference

A stated value: there is nothing to compute. A compatible node shows the same value.

bids
[[99743200,38070622999],[98650000,9820168999],[97427000,42513945330],[96646200,156027154086],[96027100,50851885007]]
asks
[[100754200,158612849098],[101357900,36948508905],[102637000,16553662538],[103746195,90769078148],[104180495,49162968450]]
deposit
5010000000
A market buy of 2,000 ZUSDC up to 1.01357915-6-market-buyvalid

Loading the test widget…

A market sell of 500 ZUSDC down to 0.9915-6-market-sellvalid

Loading the test widget…

The same sell when the blocksmith does not earn: the ZBC fee goes to the lottery carry15-6-sell-carryvalid

Loading the test widget…

The same buy when the blocksmith does not earn: no fee is taken in ZUSDC15-6-buy-no-feevalid

Loading the test widget…

A limit buy of 10 ZUSDC at 0.995 rests15-6-limit-buyvalid

Loading the test widget…

A resting bid of 3 at 1.5, filled one unit at a time: the first fill15-6-unit-firstvalid

Loading the test widget…

A resting bid of 3 at 1.5, filled one unit at a time: the second fill15-6-unit-secondvalid

Loading the test widget…

A resting bid of 3 at 1.5, filled one unit at a time: the third fill15-6-unit-thirdvalid

Loading the test widget…

An order whose quote rounds to zero15-6-rounds-to-zeroinvalid

Loading the test widget…

An order of 0.02499999 ZBC notional15-6-below-notionalinvalid

Loading the test widget…

Market and post-only together15-6-market-post-onlyinvalid

Loading the test widget…

Defects to match. (1) Time priority is id order: among equal prices the lower signed transaction id fills first, whatever the placement order. (2) A market order that fills nothing is recorded Filled with remaining = amount (and one that fills part, with what was left). (3) A post-only order that would cross leaves no row. (4) The hold is not reserved at admission (the same asset can be committed twice in one block; the second order is a paid no-op). (5) The taker fee rate is read per order, not per fill.

7. CancelOrder (23)

Purpose. The maker takes a resting order off the book.

Inputs. Body: order_id (8, i64 LE).

Output and effect. Unknown order → block invalid; sender ≠ maker (byte equality) → block invalid; the fee; status ≠ Open → paid no-op; unknown market → block invalid; the maker gets remaining base (sell) or quote(remaining, price) quote (buy) back (event 59 for asset 0); the order becomes Cancelled. A CancelOrder also feeds the market 20 % of its fee (rule market_rent, event 72), like a PlaceOrder. The fee counts as collected although the refund credits the maker in the same transaction (fee_collected_explicit, 04 §5): it reaches the reward pool and its overpay is refunded. Then 04 §5.

How to compute it. Admission: "CancelOrder body too short", "CancelOrder: unknown order", "CancelOrder: order is not open", "CancelOrder: only the order owner can cancel". Execution: "Invalid CancelOrder body", "Unknown order", "Only the order owner can cancel", "Fee cannot be negative", "Unknown market".

Rule activation. market_rent, fee_collected_explicit (active from height 0 on every chain).

Rejections and errors. As listed.

Vector. computed on the first order of §6's vector (its id Q, the LE i64 of the first 8 bytes of that PlaceOrder's hash).

  • Input: CancelOrder (type 23) by its maker A, fee 5,000,000, body = LE64(Q).
  • Expected output: A +48,831,590,467 ZBC = quote(50,851,885,007, 96,027,100) (row event 59); the order Cancelled; the market's deposit +1,000,000 (event 72 on A); the fee's floor reaches the reward pool and its overpay comes back (event 22).
  • Invalid input: the same body from another account → refused at admission "CancelOrder: only the order owner can cancel"; mined, the block is invalid ("Only the order owner can cancel").

Test cases · §7

3 cases · 1 valid · 2 invalid

The maker cancels the first bid of the book (its id Q)15-7-cancelvalid

Loading the test widget…

Another account cannot cancel it15-7-not-ownerinvalid

Loading the test widget…

Mined, that cancel makes the block invalid15-7-not-owner-minedinvalid

Loading the test widget…

Defects to match. Unlike CancelSwapOffer, a stranger's cancel that reaches a block makes the block invalid.

8. Order expiry and market rent

Purpose. What happens to the book and to markets without a transaction of their own.

Inputs. The block's timestamp; the Open orders with an expiry; the active markets.

Output and effect. At the start of every block (22): every Open order with expiry ≠ 0 and expiry ≤ expiry_clock, in ascending id, gets its remainder back exactly as a cancel (event 59, transaction_id = the order id, the block's own timestamp) and becomes Expired. expiry_clock is the previous block's timestamp, not the blocksmith's own (rule expiry_previous_stamp; the one clock shared with the escrow, liquid, schedule and fee-vote sweeps, 12/13): a blocksmith cannot stamp its block ahead to expire an order early.

Market rent (rule market_rent), a per-block step. Guarantee: a market keeps trading only while it pays its rent. Inputs: the active markets, market_creation_cost, the billing period of 13 §2, the block. Effect (after the block's steps, 22): markets in id order (ascending id); rate = ceil(market_creation_cost / 12) (= 416,666,667 at the 5,000,000,000 cost); due = (block.height − paid_through_height) div period; if a token of the pair is gone, or any due period cannot be paid (deposit < rate), the market is pruned — every resting order refunded (remaining base to a seller, quote(remaining, price) quote to a buyer, event 59 for ZBC with transaction_id = the order id; each order a Cancelled version; the sell orders first, then the buy orders, each side in the book order of §6 step 4), the remaining deposit credited to the longevity pool (event 19), status Pruned (no other row); else for each due period deposit −= rate, paid_through_height += period, the pool +rate (event 19). period = the snapshot cycle (main_snapshot_interval), rate = ceil(market_creation_cost / 12) (at a one-unit cost the rent is one unit, never free). The deposit cap of §6 step 2 is 24 × rate (saturating). A pruned pair can be opened again by a new CreateMarket.

How to compute it. As stated.

Rule activation. expiry_previous_stamp, market_rent (height 0).

Rejections and errors. None.

Vector. computed (TestNet: cost 5,000,000,000, period 172,800).

  • Input: the market M of §5 (created at 513, deposit 5,000,000,000, paid_through_height 513), no order ever placed; blocks 172,800 … .
  • Expected output: rate = ceil(5,000,000,000 / 12) = 416,666,667; at height 173,313 (= 513 + 172,800) one period is due: deposit 4,583,333,333, paid_through_height 173,313, the pool +416,666,667 (event 19); after 11 billed periods deposit = 5,000,000,000 − 11 × 416,666,667 = 416,666,663 < rate, so at the 12th due height, 513 + 12 × 172,800 = 2,074,113, the market is pruned: its resting orders refunded, 416,666,663 to the pool (event 19), status Pruned.
  • Input: the market of §6's vector (deposit 5,010,000,000 after ten orders). Expected: the cap is 24 × 416,666,667 = 10,000,000,008; each further order adds 1,000,000 until the cap.
  • Input (expiry): an Open order with expiry 1,793,715,000 and a block whose previous block's timestamp is 1,793,715,097. Expected: the order is Expired at the start of that block and its remainder refunded (event 59, transaction_id = the order id).

Test cases · §8

5 cases · 5 valid

The first rent period of the market created at 51315-8-first-periodvalid

Loading the test widget…

After eleven periods15-8-eleven-periodsvalid

Loading the test widget…

At the twelfth due height the market cannot pay and is pruned15-8-prunedvalid

Loading the test widget…

The deposit cap: 24 periods of rent15-8-capvalid

Loading the test widget…

An order whose expiry is not after the previous block's timestamp expires15-8-expiryvalid

Loading the test widget…

Defects to match. Swap offers are never swept (no rent, no expiry sweep).

9. Ledger rows, views and the consensus/local split

Event Row (asset 0 legs only) Written by
54 / 55 maker −give / +give CreateSwapOffer / CancelSwapOffer
56 −want, +want, +give; fills: +base or +quote per party AcceptSwapOffer, PlaceOrder
57 creator −cost CreateMarket
58 / 59 maker −hold / +refund PlaceOrder hold; refund at placement, CancelOrder, expiry, a pruned market; a maker-buyer's rounding unit at a fill
60 blocksmith (or lottery carry) +fee PlaceOrder fills
72 sender −contribution an order's or a cancel's 20 % fee share fed to the market (market_rent)
19 pool +rent / +deposit market rent and a pruned market's deposit (market_rent)
1, 22, 47 per 04 §5 every type here

Views (local, archival and node): /exchange/markets (markets[]: id (string), base_token_id, quote_token_id, deposit; Active only), /exchange/orderbook?market=<id> (bids/asks as [price, Σ remaining] per price level, best first), /exchange/trades?market=<id>&limit=N (trades[]: price, amount, ts), /exchange/offers (Open offers, expired ones included: id, maker, give_token_id, give_amount, want_token_id, want_amount, counterparty, expiry, status), /accounts/<a>/offers (all statuses), /exchange/orders?account=<a> and /accounts/<a>/orders (orders[]: id, market_id, side, price, amount, remaining, status, ts).

Consensus: every row of the four tables, the matching order and arithmetic, the holds and refunds, the taker fee and its recipient, the market rent and pruning, the accept/no-op/invalid outcome of each type. Local: the ledger rows except event 22 (04), the views.

A question about this chapter, or a statement that does not match the network? Discuss on zoobc.pro.