Per-Block Global Money Conservation and On-Chain Perpetual Liquidation in Go
When spot balances, perpetual margins, funding rates, insurance funds, and staking bonds all share one L1 StateDB, a single 1-unit rounding bug turns into silent inflation. Here is how FrostBit enforces a cross-system zero-delta conservation panic on every block, alongside orderbook-first liquidation, funding clearing pools, and deterministic two-phase joint ADL.
Table of Contents
- 1. The Core Invariant: A Hard Accounting Check on Every Block
- Avoiding Read Amplification on High-Throughput Blocks
- 2. Zero-Inflation Fee Splitting: Atomic per Fill
- 3. Mark Price Hardening and the Funding Clearing Pool
- 1. Three-Source Median Mark Price and the "Idle-Side EMA Freeze" Bug
- 2. Funding as a Strict Clearing Pool
- 4. Liquidation: K+X Index, Self-Maker Rescue, and Orderbook-First Execution
- 1. Conservative Liquidation Index + Read-Only K+X Pre-Check
- 2. Orderbook Liquidation Without Self-Match Suicide
- 5. Deterministic Two-Phase Joint ADL for Bilateral Bankruptcy
- 6. Explicit Boundaries and Verification Scope
The scariest bug in an on-chain trading engine is never a crash. It is silent accounting drift.
A perpetual exchange touches spot balances, frozen order collateral, open position margins, unrealized PnL, funding rates, insurance funds, fee rebates, and bankruptcy shortfalls inside the same state machine. Round up once in the wrong direction, forget to debit a pool on one error branch, or let a UI-estimated funding number leak into withdrawal math, and the chain will not crash—it will quietly accumulate unbacked liabilities for hundreds of thousands of blocks until the system is insolvent.
While building FrostBit—a full on-chain spot and perpetual L1 written from scratch in ~455k lines of Go (commonstate-labs/frostbit, GPL-3.0-only)—we stopped treating money conservation as an after-the-fact audit checklist and built two hard rules straight into the VM:
- Per-block cross-system conservation assertion: Every finalized block diff runs through a global token-conservation check before commit. A net discrepancy of even
1base unit on any token triggers an immediatepanic. - Closed-loop integer accounting across perpetuals: Funding settlement, liquidations, realized PnL, maker rebates, and auto-deleveraging (ADL) are all pure integer transfers with explicit sources and sinks—zero unbacked minting paths.
Here is how the five core pieces work in production code.
1. The Core Invariant: A Hard Accounting Check on Every Block
Checking that "no account balance goes negative" does not catch conservation bugs. Drop a closed position's margin without crediting anyone, or credit two traders from thin air, and every balance stays non-negative while total supply silently drifts.
In vm/global_conservation_audit.go (AuditGlobalConservationDiffWithStats), FrostBit classifies every value-bearing key in StateDB into five buckets and asserts the following identity for every token touched in the block diff:
ΔBalance(Available + Locked + OrderFrozen)
+ ΔOpenPosition.Margin
+ ΔFutureInsuranceFund
+ ΔActiveChallengeRecord.StakeAmount
- ΔToken.TotalSupply
──────────────────────────────────────────
== 0 (must hold strictly for every touched token)If any token's net delta is non-zero, the VM logs per-bucket delta breakdowns (balance / position / insurance / challenge / supplyAdj) with offending key samples and halts block execution immediately:
// vm/global_conservation_audit.go — AuditGlobalConservationDiffWithStats
for _, token := range tokens {
delta := deltas[token]
if delta.Sign() != 0 {
logs.Error("[VM][GlobalConservationDiff][Trace] height=%d token=%s unbalanced delta=%s detail{%s}",
height, token, delta.String(), formatConservationDeltaDetail(details[token]))
panic(fmt.Sprintf("[VM][GlobalConservationDiff] UNBALANCED token=%s delta=%s height=%d",
token, delta.String(), height))
}
}Two clean architectural consequences fall directly out of this rule:
- Runtime fees are never "pretend burned": Transaction runtime fees flow into a real protocol bucket (
__runtime_fee_pool__). Protocol-duty transactions (withdraw claim/signed, witness votes, arbitration votes) refund their runtime fee from that pool only on successful execution; failed or invalid transactions keep the debit. Because the pool is an ordinary balance bucket, fee collection and refunds satisfy conservation automatically. - Mints and burns must be same-block atomic: Bridge deposits, withdrawal burns, and slashed-bond burns must update
Token.TotalSupplyin the exact same block diff—no delayed reconciliation.
Avoiding Read Amplification on High-Throughput Blocks
Running a naive diff audit that queries PebbleDB for the oldValue of every modified key will crush block latency under heavy order traffic. We eliminate that overhead in three steps:
- Coalesce first:
coalesceWriteOpsForConservationfolds multiple overwrites to the same key within a block into a single transition (initial old value → final new value). - Ignore non-monetary keys completely:
planConservationAuditOpinspects key prefixes so orderbook indices, trade history, nonces, and archive writes (OtherOps) never trigger old-value reads. - Inline old values + sharded parallel reduction:
StateViewattachesOldValueInlinetoWriteOpon write, keeping storage fallback reads near zero. When a coalesced block exceeds2048ops,runConservationAuditShardssplits the slice acrossGOMAXPROCSworkers, accumulates per-shard deltas, and merges them deterministically in sorted token order.
2. Zero-Inflation Fee Splitting: Atomic per Fill
Many perpetual DEXs bootstrap liquidity by minting governance tokens to subsidize market makers—liquidity disappears the day emissions drop. FrostBit encodes a strictly zero-sum negative-maker-fee split at the protocol layer:
| Market | Maker Fee | Taker Fee | Exact Same-Fill Split of Taker Fee |
|---|---|---|---|
| Spot (protocol/spot_trading_fee.go) | 0 bps | 5 bps | 4 bps paid instantly to Maker (floor(takerFee * 4 / 5)), remainder (1 bps) to block proposer |
| Perpetuals (referral/engine.go) | 0 bps | 5 bps | 3 bps paid instantly to Maker; if referred, taker receives 10% discount and referrer receives 20% of full fee permanently; remainder (0.5 bps, or 2 bps without referrer) deposits into the pair's FutureInsuranceFund |
| Liquidation / ADL | 0 | 0 | Zero fee, zero rebate—the protocol never profits from liquidations |
Every ratio uses integer floor division, and the final sink receives total - sum(others). No floats, no 1-unit dust leak, and zero token inflation.
3. Mark Price Hardening and the Funding Clearing Pool
1. Three-Source Median Mark Price and the "Idle-Side EMA Freeze" Bug
Mark price (future/markprice.go) is the median of three sources:
MarkPrice = median(spotEMA, futureEMA, lastMark) // DefaultEMAWindow = 20We hit a subtle production bug early on: if a block had perpetual trades but no spot trades, feeding the unchanged KeySpotLastPrice back into CalcEMA triggered CalcEMA(x, x) = x, freezing the spot EMA at a stale price and pinning the funding rate to its ±75 bps clamp.
In vm/future_hooks.go, spotChanged and futureChanged pair sets are now tracked separately—each EMA advances only when that side actually traded in the current block. Funding reads the smoothed KeyFutureSpotEMA and KeyFutureEMA rather than spot/future last prices, scaling the cost of single-block funding manipulation by EMAWindow.
2. Funding as a Strict Clearing Pool
Textbook perpetual formulas say "longs pay shorts." On a real chain, open notional across accounts is not always symmetric after partial liquidations, and a payer may run out of margin plus wallet balance before covering their owed funding. Crediting receivers from a theoretical formula immediately breaks conservation.
FrostBit (future/funding.go) routes all funding strictly through each pair's FutureInsuranceFund as a clearing pool:
Payer position ──(actual deducted amount; margin=0 triggers liq)──▶ FutureInsuranceFund ──(available pool balance)──▶ Receiver position- Only what is actually collected from payers enters the pool; if funding drains a payer's margin to zero, liquidation fires automatically.
- Receivers draw strictly from the pool. If the pool cannot cover full payouts, receivers get the covered portion and the unpaid remainder accumulates in
KeyFutureInsuranceShortfall(pair). - One-sided markets: If there are receivers with zero payers on the opposite side, receivers advance
LastCumulativeFundingwithout minting free tokens. - Strict UI vs. risk separation:
PositionView(future/view.go) exposes both true unsettledPendingFundingand a window-onlyDisplayFundingfor frontend UX.EffectiveMargin = max(0, Margin + PendingFunding)and liquidation checks never readDisplayFunding.
4. Liquidation: K+X Index, Self-Maker Rescue, and Orderbook-First Execution
Running liquidations entirely on-chain poses two engineering constraints: you cannot full-scan every open position on every block, and you want real orderbook depth to absorb distressed positions before falling back to mark-price ADL.
1. Conservative Liquidation Index + Read-Only K+X Pre-Check
We maintain an ordered PebbleDB index KeyFutureLiqIndex(sideTag, pair, liqPrice67, positionID) where PriceToKey128 encodes prices as 67-digit zero-padded decimals so lexicographical order equals numeric order.
The index stores a conservative liquidation price (excluding unsettled pending funding, so it errs on the side of scanning early rather than missing a liquidation). On price change or funding settlement, the engine reads a K+X slice:
K(cap10,000): positions whose conservative liquidation price has crossedmarkPrice.X(buffer1,000): top near-threshold positions just shy ofmarkPricethat accumulated funding might have pushed into danger.
Crucially, every candidate first runs a read-only PreviewPendingFunding + ShouldLiquidatePosition check:
- If healthy: we do not call
ApplyPendingFunding(which would wipe unsettled funding to zero on every block); instead we lazily refresh the position's index key so cold positions converge smoothly as funding accrues. - If truly liquidatable: we settle funding inside a
StateViewsnapshot and enter orderbook liquidation.
2. Orderbook Liquidation Without Self-Match Suicide
Ordinary spot and perpetual orders allow self-matching, but liquidation must never fill a distressed trader against their own resting maker orders—doing so wastes margin on self-execution instead of rescuing the position.
tryOrderbookLiquidate (vm/future_liquidation_orderbook.go) handles this directly inside the block:
At-risk position (virtual opposing market order, 500 bps slippage cap)
│
├─ Hits the liquidated owner's OWN resting maker order
│ └─ Cancel that maker, move OrderFrozen directly into Position.Margin
│ └─ Recompute health immediately: healthy again → STOP liquidation!
│
└─ Still unhealthy → match external makers (strictly CreateHeight < currentHeight)
├─ Full fill → LiquidateAtPrice using adversely rounded average price
├─ Partial fill → LiquidatePartial splits margin via MulDivFloor(margin, sumQty, qty); remainder falls back to markPrice/ADL
└─ Zero fill → Revert snapshot; full position falls back to markPrice/ADLTwo anti-exploitation details built into this path:
- Adverse integer rounding (
liquidationClosePrice): A liquidated Long sells, so average close price rounds down (never overstating proceeds); a liquidated Short buys, so close price rounds up (never understating cost). - Prior-block makers only: Liquidation ignores makers created in the current block (
CreateHeight < height) and enforcesLiquidationOrderbookBufferBps = 500(5%), blocking a block proposer from stuffing off-market bait orders in the same block to snipe liquidations.
5. Deterministic Two-Phase Joint ADL for Bilateral Bankruptcy
When orderbook liquidity cannot absorb a violent wick and liquidation crosses the bankruptcy price, the shortfall cannot silently become an unbacked insurance-fund IOU.
In future/adl.go, bilateral shortfalls run through a deterministic two-phase deleveraging engine:
- Deterministic total order (
RankDeleverageCandidates):
- Tier 1 (profitable counterparties,
pnl > 0):margin <= 0profitable positions rank highest, followed by descending ADL score, tie-broken by ascendingpositionID. - Tier 2 (losing counterparties,
pnl <= 0): ranked by smallest loss per unit using exact signed cross-multiplication (pnl_i * Q_j > pnl_j * Q_i, tie-broken by ascendingpositionID)—zero floating-point division.
- Joint withhold budget + collect-before-pay settlement:
- Using post-liquidation insurance balance
iAfter, bilateral shortfalldTotal, Tier 2 collectable losseslColl, and Tier 1 gross profitgTotal, the engine computes both solvency deficitwSolvencyand liquidity deficitwLiquidity, setting total withhold targetwTarget = min(max(wSolvency, wLiquidity), gTotal). - Phase A deposits all Tier 2 losses from both sides into the insurance fund first.
- Phase B pays out Tier 1 net profits (
gross - withheld) from the replenished insurance fund. - If even withholding 100% of counterparty profits cannot cover an extreme gap, the uncovered remainder is recorded explicitly via
recordADLShortfall—never silently minted.
Once orders or positions reach terminal states (CLOSED / LIQUIDATED / ADL_CLOSED with zero quantity and margin), they are archived to KV-only history tables (future_acc_order_, future_pos_history_) and deleted from StateDB so historical churn never bloats state roots or snapshot sync.
6. Explicit Boundaries and Verification Scope
Good engineering documentation states what a mechanism does not prove:
- Conservation catches value creation/destruction, not misallocation:
AuditGlobalConservationDiffguarantees zero net token drift across all modules, but verifying that the right account received3 bpsinstead of2 bpsstill relies on property tests (future/engine_property_test.go), unit tests, and specification models. - Bounded formal verification is not an unbounded proof: Our private verification suite runs nearly 50 Quint state-machine models paired with Go differential and mutation tests. Those verify bounded domains and modeled transitions—not every possible production parameter scale or external market regime.
- Deterministic ordering vs. microsecond matching: On-chain consensus matching trades centralized microsecond latency for full-node reproducibility and zero private queue-jumping. Cross-block compact orderbook snapshots (vm/hot_future_orderbook.go, bypassing repeated protobuf marshal/unmarshal on the hot path) and the
K+Xindex keep execution comfortably inside multi-second block budgets.
Source entry points (GPL-3.0-only):
- Global conservation audit: vm/global_conservation_audit.go
- Orderbook liquidation: vm/future_liquidation_orderbook.go
- Two-phase joint ADL: future/adl.go
- Funding clearing pool: future/funding.go
GPL-3.0-only) at github.com/commonstate-labs/frostbit. Issues and adversarial edge cases are welcome.