!5297odin/luvi-guards-reward → develop8cbf0412c4

EndBlock LUVI scopes ignore rejected inner losses

AI-generatedEverything on this page was written by an AI agent from the diff: the summaries, the narration, the diagrams, the flags and the glossary. It can be wrong or incomplete, so check it against the code before you rely on it.

4commits
4files
38lines changed
8lines to read
5logic lines
+1 eventnarrow consensus path

Where the diff is

2-minute explainer

What changed

Before: hidden step loss

A rejected inner luvi_loss made the scope skip its own report

inner flow rejectedluvi_loss rejected=trueReported[pool]=truestep loss dropped

Fix: skip rejected reports

NewLuviStepEvents ignores luvi_loss with rejected=true

inner flow rejectedskippedstep emits luvi_loss excess=true

Tests, docs, CI

Regression test, nil-equality test, luvi_reward doc, GO-2026-6859 allowlisted

TestEndBlockScopeIgnoresRejectedInnerReportsTestLuviStatesEqualNildocs/mimir.md.govulncheck-ignore

Look here first

Rejected luvi_loss no longer suppresses step reportConsensus-visible: blocks with a rejected flow plus a step loss on the same pool gain a luvi_loss event.type_luvi.go:415 ↗verify
406406 out.Withdrawn[e["pool"]] = append(out.Withdrawn[e["pool"]], u)
407407 }
408408 case ErrataEventType:
409409 out.Errata[e["asset"]] = true
410410 case SwapEventType:
411411 out.Swaps[e["pool"]]++
412412 case LuviLossEventType:
413+ // a rejected flow's state changes were reverted, so its loss is
414+ // not part of the enclosing step's change in G
415+ if e["rejected"] == "true" {
416+ continue
417+ }
413418 out.Reported[e["pool"]] = true
414419 if e["excess"] == "true" {
415420 out.ReportedExcess[e["pool"]] = true
416421 }
417422 }
418423 }
419424 return out
420425 }
421426
422427 // AssetPaidOf returns the asset paid by gas and slashes for a pool.
423428 func (e LuviStepEvents) AssetPaidOf(pool string) cosmos.Uint {
Non-excess losses of rejected flows still countRejected=rejected&&Excess: a reverted flow's non-excess losses emit rejected=false and still mark pools Reported.luvi_guard.go:236 ↗verify
unchanged in this MR · context
227227 }
228228 }
229229 return losses, excess && s.enforce
230230 }
231231
232232 // emitLuviLosses emits the loss events on ctx, marking them rejected when the
233233 // scope's changes were reverted.
234234 func emitLuviLosses(ctx cosmos.Context, mgr Manager, losses []*types.EventLuviLoss, rejected bool) {
235235 for _, l := range losses {
236236 l.Rejected = rejected && l.Excess
237237 if err := mgr.EventMgr().EmitEvent(ctx, l); err != nil {
238238 ctx.Logger().Error("fail to emit luvi loss event", "error", err)
239239 }
240240 if l.Excess {
241241 ctx.Logger().Error("luvi: pool LP value dropped beyond the allowance",
242242 "pool", l.Pool, "scope", l.Scope, "tx", l.TxID, "kind", l.Kind,
243243 "normalized_delta_g", l.NormalizedDeltaG, "allowed", l.Allowed, "rejected", l.Rejected)
244244 }
245245 }
246246 }
247247
248248 // end finishes a report-only scope that ran directly in ctx (an EndBlock step).
249249 func (s *luviScope) end(ctx cosmos.Context, mgr Manager) {
Suppression rule the fix feedsReported/ReportedExcess decide whether the EndBlock scope repeats a loss; only consumer of NewLuviStepEvents.luvi_guard.go:171 ↗careful
unchanged in this MR · context
162162 }
163163 if virtualSynthDepth > int64(constants.MaxBasisPts) {
164164 continue
165165 }
166166 }
167167 loss := func(kind string, dG, norm, allowed cosmos.Dec, over bool) {
168168 // an inner scope (a handler run inside this EndBlock step) already
169169 // reported this pool: repeat it only if this step is the first to
170170 // find an excess
171171 if ev.Reported[pool] && (!over || ev.ReportedExcess[pool]) {
172172 excess = excess || over
173173 return
174174 }
175175 losses = append(losses, &types.EventLuviLoss{
176176 Pool: asset,
177177 Scope: s.name,
178178 TxID: s.txID,
179179 DeltaG: dG,
180180 NormalizedDeltaG: norm,
181181 Allowed: allowed,
182182 Kind: kind,
183183 Excess: over,
184184 LpUnitsBefore: pre.LPUnits,
Regression test covers excess path onlyTheft is excess, so rejected=true; the non-excess-on-another-pool case is untested.luvi_guard_test.go:613 ↗look
604604
605605 // with the overhang guard off, the commit goes through as before
606606 e.mgr.Keeper().SetMimir(e.ctx, constants.LUVIOverhangGuard.String(), 0)
607607 c.Assert(newPoolMgr().commitPendingLiquidity(e.ctx, e.pool(), e.mgr), IsNil)
608608 got, err = e.mgr.Keeper().GetLiquidityProvider(e.ctx, e.asset, lp.GetAddress())
609609 c.Assert(err, IsNil)
610610 c.Check(got.PendingRune.IsZero(), Equals, true)
611611 }
612+
613+func (s *LuviGuardSuite) TestEndBlockScopeIgnoresRejectedInnerReports(c *C) {
614+ e := newLuviEnv(c, luviRegime{"no synths", 0})
615+ ctx, outer := beginLuviScope(e.ctx, e.mgr.Keeper(), "endblock/test", "", false)
616+ // a user flow inside the step is rejected: its loss is reported on the
617+ // step context, but its changes are reverted
618+ cacheCtx, _ := ctx.CacheContext()
619+ err := runLuviGuarded(ctx, cacheCtx, e.mgr, e.guardMsg(), func(runCtx cosmos.Context) error { e.steal(runCtx, 10); return nil })
620+ c.Assert(errors.Is(err, errLuviGuard), Equals, true)
621+ c.Assert(luviLossEvents(e.ctx), HasLen, 1)
622+ // a loss the step itself causes is still reported
623+ e.steal(ctx, 10)
624+ outer.end(ctx, e.mgr)
625+ evts := luviLossEvents(e.ctx)
626+ c.Assert(evts, HasLen, 2)
Doc: luvi_reward sample every 600 blocksMatches luviRewardSampleBlocks = 600 in luvi_reward.go.mimir.md:132 ↗look
124124 - `PauseLP`#: Pauses the ability for LPs to add/remove liquidity
125125 - `PauseLP<chain>`#: Pauses the ability for LPs to add/remove liquidity, per chain
126126 - `MaximumLiquidityRune`#: Maximum RUNE capped on the pools known as the ‘soft cap’
127127 - `LiquidityLockUpBlocks`: The number of blocks an LP must wait before they can withdraw their liquidity
128128 - `PendingLiquidityAgeLimit`: The number of blocks the network waits before initiating pending liquidity cleanup. Cleanup of all pools lasts for the same duration.
129129 - `PauseAsymWithdrawal-<Chain>`#: Forces dual-address liquidity providers to withdraw symmetrically rather than asymmetrically.
130130 - `PauseLPDeposit-<Asset>`#: pauses the ability to add liquidity into that pool. E.g. `PAUSELPDEPOSIT-BTC-BTC=1` suspends deposits for the BTC pool
131131 - `LUVIOverhangGuard`\*: When above `0` (the default is `1`), rejects liquidity adds, from users and from POL, into a pool in synth overhang (synth supply at least twice the pool's asset depth). POL skips such pools, and aged pending liquidity in them stays pending (and withdrawable) instead of being committed. Withdrawals are unaffected. `0` turns the guard off
132−- `LUVIGuard`\*: When above `0` (the default is `1`), checks every handler run dispatched through the internal handler (including the swap queue and the messages that observed txs and deposits dispatch) and the wrapped EndBlock steps for drops in the hedged LP equity G of the pools it wrote (see `x/thorchain/types/type_luvi.go`). A user value flow (swap, add or withdraw liquidity, donate, trade/secured asset, RUNEPool and TCY messages) that lowers a pool's G beyond the computed allowance for gas, slashes, LP-flow rounding and synth mints is rejected and refunded. Other handlers, the same messages when the protocol sends them itself (POL, ragnarok, saver ejects, pending liquidity commits), and EndBlock steps only report. Messages handled directly by the external msg server (for example `MsgErrataTx` and errata quorum), BeginBlock, and the EndBlock steps that are not wrapped (observation tallies, volume, dynamic fees, scheduled migrations) are outside the guard: their pool changes reach only the accumulator, with no `luvi_loss` event. Within the guard, every drop beyond the allowance, and every LP-unit change without matching add/withdraw events, emits a `luvi_loss` event naming the pool, the scope and the inbound tx; covered drops are only recorded by the accumulator. With a virtual synth depth above 1x (`VirtualMultSynthsBasisPoints` above 10000, as on mocknet), pools whose synth supply moved are skipped. `0` turns the guard and the events off; the per-pool G accumulator on the pool endpoints always runs
132+- `LUVIGuard`\*: When above `0` (the default is `1`), checks every handler run dispatched through the internal handler (including the swap queue and the messages that observed txs and deposits dispatch) and the wrapped EndBlock steps for drops in the hedged LP equity G of the pools it wrote (see `x/thorchain/types/type_luvi.go`). A user value flow (swap, add or withdraw liquidity, donate, trade/secured asset, RUNEPool and TCY messages) that lowers a pool's G beyond the computed allowance for gas, slashes, LP-flow rounding and synth mints is rejected and refunded. Other handlers, the same messages when the protocol sends them itself (POL, ragnarok, saver ejects, pending liquidity commits), and EndBlock steps only report. Messages handled directly by the external msg server (for example `MsgErrataTx` and errata quorum), BeginBlock, and the EndBlock steps that are not wrapped (observation tallies, volume, dynamic fees, scheduled migrations) are outside the guard: their pool changes reach only the accumulator, with no `luvi_loss` event. Within the guard, every drop beyond the allowance, and every LP-unit change without matching add/withdraw events, emits a `luvi_loss` event naming the pool, the scope and the inbound tx; covered drops are only recorded by the accumulator. With a virtual synth depth above 1x (`VirtualMultSynthsBasisPoints` above 10000, as on mocknet), pools whose synth supply moved are skipped. The same Mimir gates a report-only check around the pool reward payout: for each rewarded pool it compares the change in G with the expected LP share of the reward, and checks that the pool rewards add up to the rewards event and to the RUNE Asgard received. It emits a `luvi_reward` event for every failure, plus one per rewarded pool every 600 blocks as a sample. `0` turns the guards, the reward check and their events off; the per-pool G accumulator on the pool endpoints always runs
133133
134134 ## RunePool
135135
136136 - `RUNEPoolEnabled`: Enable/disable RUNE Pool
137137 - `RUNEPoolDepositMaturityBlocks`: Minimum number of blocks from last RUNEPool deposit when a withdraw is allowed.
138138 - `RUNEPoolMaxReserveBackstop`: Max amount of RUNE above the `POLMaxNetworkDeposit` that the reserve can enter RunePool before withdrawals are disabled.
139139
140140 ## Chain Management
141141
142142 - `HaltChainGlobal`#: Pause observations on all chains (chain clients)
143143 - `HaltTrading`: Stops swaps and additions, if done, will result in refunds. Observations still occur.
144144 - `Halt<chain>Chain`#: Pause a specific blockchain
145145 - `SolvencyHalt<Chain>`# Halts a chain if the solvency checker for that chain fails.

Ask an AI about this change

Chat assistantClaude, ChatGPT, … (reads a link)

Coding agentClaude Code, Cursor, … (reads the repo)

The context file is context.md. Use Copy with context for an AI that can't open links; it pastes the whole file in.

Glossary

G
Hedged LP equity of a pool, the quantity the guard tracks per pool. type_luvi.go ↗
LUVI
LP unit value invariant: a pool's LP equity must not drop beyond an allowance during a flow. type_luvi.go ↗
luvi_loss
Event emitted when a scope finds a drop in G; carries scope, excess and rejected. luvi_guard.go ↗
luvi_reward
Report-only event checking each rewarded pool's change in G against its expected LP reward share. luvi_reward.go ↗
LUVIGuard
Mimir that enables the guard, its events and the luvi_reward check; 0 turns them off. docs/mimir.md ↗
Scope
A guarded region: a handler run or a wrapped EndBlock step. Inner scopes nest inside EndBlock scopes. luvi_guard.go ↗