feat(thorchain): LUVI guard, G accumulator, overhang/overflow guard, migration gate, reward check and fair LP pricing
🔎 Visual review of1398c5d4: explainer, review flags and prompts to ask an AI about the change
I'm checking the current diff against each claim in the MR description. Next I'll look at the migration, reward, overhang and fair-value code.
Summary
Puts the synth-aware LUVI index G (x/thorchain/types/type_luvi.go, from !5135 (merged)) to work inside the protocol. G is the pool's hedged LP equity. Swaps are k-neutral (the fee RUNE goes to the Reserve), so G moves only on rewards, LP flows, gas, slashes and write-downs. A drop that the allowance (gas and slash reimbursement, rounding, synth mints) does not cover means LPs lost value in a way the protocol does not intend.
Nine pieces:
- Per-tx LUVI guard (
luvi_guard.go). EveryNewInternalHandlerrun, and every advanced swap queue execution, is a scope. A context-scoped journal records each layer-1 pool the scope writes, with its state before the first write. The store hooks areSetPool,RemovePool, and synth mint/burn.- User value flows are rejected and refunded when a pool's G drops beyond the allowance. These are swap, switch, add/withdraw liquidity, donate, trade/secured asset, RUNEPool, TCY and limit-swap modify messages.
- Protocol messages and EndBlock steps only report. So do the user message types above when the protocol sends them itself (POL, ragnarok, saver ejects, pending liquidity commits, via
newLuviProtocolHandler): a ragnarok withdraw may drain one side of a pool on purpose, and rejecting it would stall the wind-down. - The LP-unit ledger is checked too: LP units must change only with matching add_liquidity/withdraw events.
- With a virtual synth depth above 1x (mocknet), pools whose synth supply moved are skipped. That depth is a configured subsidy the allowance does not model.
- Operational Mimir
LUVIGuard, on by default (1); setting it to 0 turns the guard and the events off.
- Overhang and overflow guard:
calculatePoolUnitsreturnserrPoolUnitsOverflowinstead of panicking on LegacyDec overflow. This was a latent halt: repeated POL deposits into an overhang pool panicked on the 7th POLCycle. Results for inputs that don't overflow are bit-identical (checked against the old function on 20k random inputs).- Liquidity adds, from users and from POL, into a pool in synth overhang (S ≥ 2A) are rejected. POL and the POL reserve skip those pools, and the aged pending-liquidity commit leaves their pending liquidity pending (still withdrawable).
- Mimir
LUVIOverhangGuard, default 1.
- Migration and upgrade gate (
luvi_migration.go):- Every registered store migration runs in a report-only
migration/<from>to<to>scope. - The CI suites
LuviMigrateGateSuiteandLuviMigrateMainnetGateSuiterun the migrations against a mainnet pool fixture. They fail on any undeclared LP-value drop. - Intended write-downs go in
luviDeclaredWriteDownswith a justification. Declared so far:- 17to18: the ADR-028 phantom-depth write-downs of DOGE.DOGE and GAIA.ATOM.
- 19to20: two slash reversals found by the gate, SOL at −0.53% and TRON at −0.16 bp, at today's depths.
- Documented in
docs/release.md.
- Every registered store migration runs in a report-only
- Fuzzing and formal-verification oracle:
FuzzLuviPoolOpsdrives real handlers and checks G, the ledger, and no panics.FuzzLuviTrackerchecks the math.- Both use the standard
testing.Fsignature, compatible with OSS-Fuzz. - The invariants are stated in
docs/concepts/luvi-invariant.md.
- G accumulator per pool, on chain (
luvi_accumulator.go):- A
PoolLuvirecord is advanced at the end of every EndBlock. /pooland/poolsgainluvi_g,luvi_c,luvi_star,luvi_last_normalized_delta_gandluvi_height.- Pool queries from CosmWasm don't get these fields, so contract responses and gas are unchanged.
- A
- Loss events:
EventLuviLoss(luvi_loss) carries the pool, the scope (message type URL,endblock/<step>, ormigration/...), the inbound tx, dG, normalized dG and the allowance. It is emitted for excess drops and ledger mismatches. EndBlock scopes don't repeat what an inner handler scope already reported. - Forensics:
tc-debug/luvi_forensics.pymapsluvi_lossevents to tx hashes or EndBlock steps over a block range, and the tc-debug skill has a new step 1c'. - Reward allocation check (
luvi_reward.go), aroundpayPoolRewards:- For each pool, dG must equal
sqrt(A(R+r)) − sqrt(AR). The rewards event must match what was paid, and Asgard must receive the RUNE. - The LP share is 1 − S/(2A). The rest of the reward accrues to synth holders.
EventLuviRewardis emitted on every failed check, plus a per-pool sample every 600 blocks.
- For each pool, dG must equal
- Manipulation-resistant LP unit pricing (
type_luvi_fair.go):- Fair LP-side value =
2·sqrt(A·R·P) − S·Pat the oracle price P. A swap or sandwich can't move it. - New pool fields 40–45 hold the fair value and the spot-vs-fair deviation, populated only when the oracle has a current price.
- Reachable from CosmWasm through the existing whitelisted pool query, covered by the new regression suite
wasm/bindings-fair-value.
- Fair LP-side value =
Consensus and gas impact
- New store keys: the per-pool
pool_luvi/accumulator, written once per block per pool whose state changed. - Every guarded handler reads the
LUVIGuardMimir. On the first write to each pool, the guard also reads that pool's pre-state and synth supply. These reads count towardgas_used, which is consensus-visible, so this needs a coordinated release. - Contract pool queries now read two oracle prices (item 9), so CosmWasm gas for pool queries rises slightly.
- Behavior change on mainnet: BTC.BTC and BSC.BNB are in overhang with POL enabled. POL will skip them even if the
PAUSELPDEPOSITMimirs are lifted.
Testing
-
Mainnet-state probe (not committed): all 44 mainnet pools at block 28,406,107 (depths, LP units, synth supply, 1x virtual synth depth) through the real swapper and add/withdraw handlers with the guard on. Of 1,896 swaps, withdrawals and adds, none was rejected by the guard, none emitted
luvi_loss, and none panicked, including BTC.BTC and BSC.BNB in deep overhang. -
Unit tests pass:
go test -tags=mocknet ./x/thorchain/... ./app/... ./constants/ ./test/luvicheck/. Also-tags=mainnetfor the migration gate. -
Full regression: 193/193 suites pass (
make test-regression CI=1 EXPORT=1 DEBUG=1). No existing golden or export changes; one new suite is added. -
make lint-ciandmake generateare clean. -
Fuzzing:
FuzzLuviPoolOpsran 10 minutes clean (about 490k inputs) andFuzzLuviTrackerabout 7 minutes. -
Simulation tests were not run locally.
Review notes
- The guard is calibrated against the real swapper: a synth mint at the swap formula's price reads as a cubic drop of about y³/30, where y = ΔS/A. The allowance is y³·(1/16 + 2y). Rounding allows 1/A + 1/R per swap leg and LP flow.
- Blind spots: G can't see L1 vault drains or phantom inbound credits, so pair it with solvency checks.
- Fuzz findings: synth swaps at a virtual depth above 1x lose LP value (mocknet only). The overhang overflow panic is fixed here. Both are pinned in
luvi_fuzz_findings_test.go.