!5283odin/pol-add-lazy-value → develop9199ae73cd

POL add reads the RUNEPool value only after the deposit succeeds

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.

1commits
2files
95lines changed
29lines to read
−77%addPOLLiquidity CPU
−5.5%FinalizeBlock CPU

Where the diff is

Tests1 files · 66 lines

x/thorchain/manager_network_current_test.go+66 −0
1paused add: memo untouched2reserve balance restored3unpaused add succeeds4units priced pre-deposit5memo reset after commit

2-minute explainer

What changed

Before: value first

Costly POL value computed, then thrown away when the deposit fails

value ✗balancesenddeposit failsrefund

After: deposit in a cache context

Value read only after the deposit succeeds, then the deposit is committed

balancesenddeposit (cache)value from ctxcommit

Same value, same events

ctx can't see the uncommitted deposit; the send touches nothing the value reads

pre-deposit statesend-independentevent order keptedge: value error → extra transfer pair

Evidence

Mainnet replay: POLCycle −55% CPU; 2,481 regtest outputs identical

Look here first

Value read from ctx before commitUnits must use pre-deposit value; correct only because depositCtx is uncommitted here. Reordering commitDeposit above would change consensus.manager_network_current.go:1448 ↗verify
1440+depositCtx, commitDeposit := ctx.CacheContext()
14461441 tx := common.NewTx(common.BlankTxID, polAddress, asgardAddress, coins, nil, "THOR-POL-ADD")
14471442 msg := NewMsgAddLiquidity(tx, pool.Asset, runeAmt, cosmos.ZeroUint(), polAddress, common.NoAddress, common.NoAddress, cosmos.ZeroUint(), signer)
1448−_, err = handler(ctx, msg)
1443+_, err = handler(depositCtx, msg)
1444+
1445+// compute the new provider units
1446+if err == nil && !runePool.TotalUnits().IsZero() {
1447+ var rpValue cosmos.Uint
1448+ rpValue, err = polValue.runePoolValue(ctx, mgr)
1449+ if err != nil {
1450+ err = fmt.Errorf("fail to get rune pool value: %s", err)
1451+ } else {
1452+ depositUnits = common.GetSafeShare(runeAmt, rpValue, runePool.TotalUnits())
1453+ }
1454+}
14491455 if err != nil {
14501456 handlerErr := err
14511457 // revert the rune back to the reserve
14521458 if err = mgr.Keeper().SendFromModuleToModule(ctx, AsgardName, ReserveName, coins); err != nil {
14531459 return err
14541460 }
14551461 return handlerErr
Send now precedes the value readSafe only while runePoolValue ignores reserve/asgard balances: it reads pools, synth supply, reserve LP, rune_pool balance.manager_network_current.go:1432 ↗verify
1433− }
1434− depositUnits = common.GetSafeShare(runeAmt, rpValue, runePool.TotalUnits())
1435−}
1436−
14371427 // check balance
14381428 bal := mgr.Keeper().GetRuneBalanceOfModule(ctx, ReserveName)
14391429 if runeAmt.GT(bal) {
14401430 return nil
14411431 }
14421432 if err = mgr.Keeper().SendFromModuleToModule(ctx, ReserveName, AsgardName, coins); err != nil {
14431433 return err
14441434 }
14451435
1436+// Most adds fail validation (e.g. paused deposits), so the rune pool value
1437+// is read only once the deposit succeeds. The deposit runs in a cache
1438+// context, so ctx still holds the pools, synth supply and POL position from
1439+// before it; the reserve to asgard send above changes none of them.
1440+depositCtx, commitDeposit := ctx.CacheContext()
14461441 tx := common.NewTx(common.BlankTxID, polAddress, asgardAddress, coins, nil, "THOR-POL-ADD")
14471442 msg := NewMsgAddLiquidity(tx, pool.Asset, runeAmt, cosmos.ZeroUint(), polAddress, common.NoAddress, common.NoAddress, cosmos.ZeroUint(), signer)
1448−_, err = handler(ctx, msg)
1443+_, err = handler(depositCtx, msg)
1444+
Value error now refunds a good depositIf polPoolValue errors, deposit is discarded and send refunded: same state, one extra transfer-event pair in EndBlock.manager_network_current.go:1450 ↗careful
14471442 msg := NewMsgAddLiquidity(tx, pool.Asset, runeAmt, cosmos.ZeroUint(), polAddress, common.NoAddress, common.NoAddress, cosmos.ZeroUint(), signer)
1448−_, err = handler(ctx, msg)
1443+_, err = handler(depositCtx, msg)
1444+
1445+// compute the new provider units
1446+if err == nil && !runePool.TotalUnits().IsZero() {
1447+ var rpValue cosmos.Uint
1448+ rpValue, err = polValue.runePoolValue(ctx, mgr)
1449+ if err != nil {
1450+ err = fmt.Errorf("fail to get rune pool value: %s", err)
1451+ } else {
1452+ depositUnits = common.GetSafeShare(runeAmt, rpValue, runePool.TotalUnits())
1453+ }
1454+}
14491455 if err != nil {
14501456 handlerErr := err
14511457 // revert the rune back to the reserve
14521458 if err = mgr.Keeper().SendFromModuleToModule(ctx, AsgardName, ReserveName, coins); err != nil {
14531459 return err
14541460 }
14551461 return handlerErr
14561462 }
1463+commitDeposit()
commitDeposit re-emits deposit eventsSDK CacheContext writeCache emits cached events into ctx, so event order matches the old direct-ctx handler call.manager_network_current.go:1463 ↗careful
1454+ }
14491455 if err != nil {
14501456 handlerErr := err
14511457 // revert the rune back to the reserve
14521458 if err = mgr.Keeper().SendFromModuleToModule(ctx, AsgardName, ReserveName, coins); err != nil {
14531459 return err
14541460 }
14551461 return handlerErr
14561462 }
1463+ commitDeposit()
14571464 polValue.reset()
14581465
14591466 // deposit was successful, update the rune pool units accordingly
14601467 runePool.ReserveUnits = runePool.ReserveUnits.Add(depositUnits)
14611468 mgr.Keeper().SetRUNEPool(ctx, runePool)
14621469
14631470 // rebalance ownership from reserve to poolers if able
14641471 err = reserveExitRUNEPool(ctx, mgr)
14651472 if err != nil {
14661473 return fmt.Errorf("fail to exit runepool: %s", err)
14671474 }
14681475 return nil
14691476 }
Nested cache contextNewInternalHandler already wraps in its own CacheContext and discards on error; this outer layer adds a cheap extra level.manager_network_current.go:1440 ↗look
14411431 }
14421432 if err = mgr.Keeper().SendFromModuleToModule(ctx, ReserveName, AsgardName, coins); err != nil {
14431433 return err
14441434 }
14451435
1436+// Most adds fail validation (e.g. paused deposits), so the rune pool value
1437+// is read only once the deposit succeeds. The deposit runs in a cache
1438+// context, so ctx still holds the pools, synth supply and POL position from
1439+// before it; the reserve to asgard send above changes none of them.
1440+depositCtx, commitDeposit := ctx.CacheContext()
14461441 tx := common.NewTx(common.BlankTxID, polAddress, asgardAddress, coins, nil, "THOR-POL-ADD")
14471442 msg := NewMsgAddLiquidity(tx, pool.Asset, runeAmt, cosmos.ZeroUint(), polAddress, common.NoAddress, common.NoAddress, cosmos.ZeroUint(), signer)
1448−_, err = handler(ctx, msg)
1443+_, err = handler(depositCtx, msg)
1444+
1445+// compute the new provider units
1446+if err == nil && !runePool.TotalUnits().IsZero() {
1447+ var rpValue cosmos.Uint
1448+ rpValue, err = polValue.runePoolValue(ctx, mgr)
1449+ if err != nil {
1450+ err = fmt.Errorf("fail to get rune pool value: %s", err)
1451+ } else {
1452+ depositUnits = common.GetSafeShare(runeAmt, rpValue, runePool.TotalUnits())
Low balance skips value entirelyReturns nil before any value computation now; previously a value error could surface first. Errors only reach a log line.manager_network_current.go:1430 ↗look
1431− if err != nil {
1432− return fmt.Errorf("fail to get rune pool value: %s", err)
1433− }
1434− depositUnits = common.GetSafeShare(runeAmt, rpValue, runePool.TotalUnits())
1435−}
1436−
14371427 // check balance
14381428 bal := mgr.Keeper().GetRuneBalanceOfModule(ctx, ReserveName)
14391429 if runeAmt.GT(bal) {
14401430 return nil
14411431 }
14421432 if err = mgr.Keeper().SendFromModuleToModule(ctx, ReserveName, AsgardName, coins); err != nil {
14431433 return err
14441434 }
14451435
1436+// Most adds fail validation (e.g. paused deposits), so the rune pool value
1437+// is read only once the deposit succeeds. The deposit runs in a cache
1438+// context, so ctx still holds the pools, synth supply and POL position from
1439+// before it; the reserve to asgard send above changes none of them.
1440+depositCtx, commitDeposit := ctx.CacheContext()
14461441 tx := common.NewTx(common.BlankTxID, polAddress, asgardAddress, coins, nil, "THOR-POL-ADD")
14471442 msg := NewMsgAddLiquidity(tx, pool.Asset, runeAmt, cosmos.ZeroUint(), polAddress, common.NoAddress, common.NoAddress, cosmos.ZeroUint(), signer)
1448−_, err = handler(ctx, msg)
Test pins memo untouched on failurePaused add must leave polValue.ok false and reserve balance unchanged; successful add priced at valueBefore.manager_network_current_test.go:2549 ↗look
2540+util := cosmos.NewUint(1500)
2541+target := cosmos.NewUint(1000)
2542+runeAmt := common.GetSafeShare(max, cosmos.NewUint(1000_000), btcPool.BalanceRune)
2543+reserveBefore := k.GetRuneBalanceOfModule(ctx, ReserveName)
2544+
2545+// a failed add leaves everything as it was and never computes the value
2546+k.SetMimir(ctx, fmt.Sprintf(constants.MimirTemplatePauseLPDeposit, common.BTCAsset.MimirString()), 1)
2547+polValue := &polValueMemo{}
2548+c.Assert(net.addPOLLiquidity(ctx, btcPool, polAddress, asgardAddress, na.NodeAddress, max, util, target, mgr, polValue), NotNil)
2549+c.Check(polValue.ok, Equals, false)
2550+c.Check(k.GetRuneBalanceOfModule(ctx, ReserveName).String(), Equals, reserveBefore.String())
2551+runePool, err := k.GetRUNEPool(ctx)
2552+c.Assert(err, IsNil)
2553+c.Check(runePool.ReserveUnits.String(), Equals, cosmos.NewUint(900*common.One).String())
2554+
2555+// a successful add prices the reserve's units at the value before the deposit
2556+k.SetMimir(ctx, fmt.Sprintf(constants.MimirTemplatePauseLPDeposit, common.BTCAsset.MimirString()), 0)
2557+valueBefore, err := runePoolValue(ctx, mgr)
2558+c.Assert(err, IsNil)
2559+c.Assert(valueBefore.IsZero(), Equals, false)
2560+c.Assert(net.addPOLLiquidity(ctx, btcPool, polAddress, asgardAddress, na.NodeAddress, max, util, target, mgr, polValue), IsNil)
2561+valueAfter, err := runePoolValue(ctx, mgr)
2562+c.Assert(err, IsNil)

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

CacheContext
Cosmos SDK context whose writes and events stay buffered until its commit function runs.
POL
Protocol-owned liquidity: RUNE the reserve deposits into pools whose synth utilisation is above target. manager_network_current.go ↗
POLCycle
NetworkMgr's per-block step that adds or withdraws POL for each enabled pool. manager_network_current.go ↗
polPoolValue
RUNE value of the reserve's LP positions across all pools, including synth supply; the costly read this MR defers. helpers.go ↗
polValueMemo
Per-block cache of polPoolValue, reset after any committed POL add or withdraw. helpers.go ↗
RUNEPool
Pool tracking reserve and pooler units sharing the POL position; new reserve units are priced by the RUNEPool value. helpers.go ↗