feat(thorchain): LUVI guard, G accumulator, overhang/overflow guard, migration gate, reward check and fair LP pricing

🔎 Visual review of 1398c5d4: 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:

  1. Per-tx LUVI guard (luvi_guard.go). Every NewInternalHandler run, 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 are SetPool, 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.
  2. Overhang and overflow guard:
    • calculatePoolUnits returns errPoolUnitsOverflow instead 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.
  3. Migration and upgrade gate (luvi_migration.go):
    • Every registered store migration runs in a report-only migration/<from>to<to> scope.
    • The CI suites LuviMigrateGateSuite and LuviMigrateMainnetGateSuite run the migrations against a mainnet pool fixture. They fail on any undeclared LP-value drop.
    • Intended write-downs go in luviDeclaredWriteDowns with 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.
  4. Fuzzing and formal-verification oracle:
    • FuzzLuviPoolOps drives real handlers and checks G, the ledger, and no panics.
    • FuzzLuviTracker checks the math.
    • Both use the standard testing.F signature, compatible with OSS-Fuzz.
    • The invariants are stated in docs/concepts/luvi-invariant.md.
  5. G accumulator per pool, on chain (luvi_accumulator.go):
    • A PoolLuvi record is advanced at the end of every EndBlock.
    • /pool and /pools gain luvi_g, luvi_c, luvi_star, luvi_last_normalized_delta_g and luvi_height.
    • Pool queries from CosmWasm don't get these fields, so contract responses and gas are unchanged.
  6. Loss events: EventLuviLoss (luvi_loss) carries the pool, the scope (message type URL, endblock/<step>, or migration/...), 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.
  7. Forensics: tc-debug/luvi_forensics.py maps luvi_loss events to tx hashes or EndBlock steps over a block range, and the tc-debug skill has a new step 1c'.
  8. Reward allocation check (luvi_reward.go), around payPoolRewards:
    • 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.
    • EventLuviReward is emitted on every failed check, plus a per-pool sample every 600 blocks.
  9. Manipulation-resistant LP unit pricing (type_luvi_fair.go):
    • Fair LP-side value = 2·sqrt(A·R·P) − S·P at 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.

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 LUVIGuard Mimir. On the first write to each pool, the guard also reads that pool's pre-state and synth supply. These reads count toward gas_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 PAUSELPDEPOSIT Mimirs 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=mainnet for 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-ci and make generate are clean.

  • Fuzzing: FuzzLuviPoolOps ran 10 minutes clean (about 490k inputs) and FuzzLuviTracker about 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.

🤖 Generated with Claude Code

Edited by Huginn Ai

Merge request reports

Loading
Loading