Skip to content

Commit b625eff

Browse files
amir-deriscursoragentclaude
authored
PLT-980: Index delegations by validator at the v6.8 upgrade (#4518)
The staking precompile's `validatorDelegations` reverts for most validators on atlantic-2, including bonded ones with thousands of delegators ([PLT-1447](https://linear.app/seilabs/issue/PLT-1447)). Delegations are stored by delegator, so listing one validator's delegations scans the whole delegation store. The precompile path keeps the v6.6 paginator for consensus safety, and that paginator fails once it has scanned 10,000 entries without collecting a full page of 100. Any validator whose delegations are sparse in that keyspace can never return a page, and the caller gets a bare revert with no cursor. This adds a delegation-by-validator index under prefix `0x37` (`validator | delegator`, empty value), a ready marker at `0x38`, and a backfill cursor at `0x39`. Once the marker is present, `Querier.ValidatorDelegations` pages over a single validator's prefix, so each page costs about one read per result; before that it keeps the full scan. The marker is versioned state, so replaying or tracing heights before the index is ready still takes the old path and reproduces the old result, and the frozen v6.6/v6.7 precompiles behave as before. The query serves the staking precompile and REST/gRPC alike, so REST/gRPC callers also get the index once it is ready. **Populating the index.** The v6.8 upgrade handler does not build the index; it only writes the cursor, which starts a backfill. From then on `SetDelegation` and `RemoveDelegation` maintain the index (their marker reads are gasless, so pre-upgrade delegation gas is unchanged), and the staking `EndBlocker` indexes the next 1,000 delegations after the cursor each block. When the cursor reaches the end it is deleted and the ready marker is set. Building it in one pass inside the handler would make the upgrade block's work and memory grow with the delegation count, which anyone can inflate ahead of a known upgrade height. Pending writes also slow every staking iterator created in that block, since the cache store rescans them per iterator. The batch runs in EndBlock rather than BeginBlock so that no transaction iterates the staking store while a batch is pending. `InitGenesis` still builds the index in one pass with `MigrateDelegationByValIndex`, so fresh chains start with it ready. **Pagination across the switch.** The index path returns `next_key` as a length-prefixed delegator rather than a full delegation key. A forward cursor obtained from the scan before the index was ready resumes at the delegation it names, so a client paging across that height neither skips nor repeats a delegator. A reverse page cannot resume from such a cursor and is rejected with `InvalidArgument`. This changes consensus at v6.8: from the upgrade height, delegation writes also write index entries, each block runs a backfill batch until the index is ready, and precompile results change once it is. Coverage: staking keeper and genesis tests for the index, the batched backfill (including delegations written and removed on either side of the cursor) and scan-cursor resumption; `upgrade_v68` in-process tests that the handler only starts the backfill and the EndBlocker completes it; and `make upgrade-test-offline FROM_REF=release/v6.7 TO_REF=<this branch>`, whose v6.7 source phase now seeds delegations and whose target phase requires exactly one index entry per delegation after the upgrade block. The existing size of the index seems to be around 80k, which the backfill covers in about 80 blocks: <img width="2130" height="972" alt="image" src="https://github.com/user-attachments/assets/15b0d51e-d678-4db0-bf4d-2e5bb5f875e9" /> **Mainnet shadow test (pacific-1).** A stock v6.7.1 node state-synced pacific-1 and halted at H-1. A `mock_chain_validation` build of this branch then ran the real v6.8 handler at H = 237,808,668, on an r7i.8xlarge, the same type as the mainnet RPC nodes. The build had two test-only commits on `amir/plt-980-mainnet-shadow`: one forces v6.8 from `upgrade-info.json`, the other adds batch logging and a full index audit. - **Backfill:** 80,832 delegations in 81 blocks (80 × 1,000 + 832), at about 4.5 ms per batch. Before the upgrade, the staking EndBlocker averaged 0.48 ms. The node caught up after the switch and then stayed at the tip. - **Index audit at the ready height (237,808,748):** 80,832 delegations and 80,832 index entries, with 0 missing and 0 orphaned. - **Correctness:** at height 237,811,970, `ValidatorDelegations` for all 40 bonded validators matched a stock mainnet node exactly (delegator, shares and balance). Offset paging matched too. - **Latency** (local REST, `limit=1000`): - Walking every bonded validator through `next_key` took 86 pages and 23 s, against 327 pages and 52 s on the scan path. - A validator with 2 delegations now takes 1 page (44 ms) instead of 8 (0.86 s). - A full page of 1,000 results costs about the same as before: p50 around 285 ms, against 174–278 ms. The p99 dropped from up to 424 ms to at most 315 ms. - `count_total` now returns the real total (6,961 for one validator). The scan path returns 0 once a query hits its iteration limit. - **Not exercised on mainnet data:** the backfill ran while the node was catching up after the switch, so it finished in about 2 seconds of wall time. A restart in the middle of the backfill, and diffs while the cursor moves, were not tested here. The unit tests cover both. --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 2f85895 commit b625eff

14 files changed

Lines changed: 825 additions & 20 deletions

‎app/testdata/upgrade_v68_offline_source_test.go‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
vestingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/auth/vesting/types"
2323
banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types"
2424
govtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/gov/types"
25+
stakingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/types"
2526
upgradetypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/upgrade/types"
2627
abci "github.com/sei-protocol/sei-chain/sei-tendermint/abci/types"
2728
tmproto "github.com/sei-protocol/sei-chain/sei-tendermint/proto/tendermint/types"
@@ -60,6 +61,7 @@ func TestV68OfflineUpgradeSource(t *testing.T) {
6061
seedV68IBCProposal(t, testApp, ctx, &retained)
6162
seedV68UpgradedIBCState(t, testApp, ctx, &retained)
6263
seedV68Voucher(t, testApp, ctx, &retained)
64+
seedV68OfflineDelegations(testApp, ctx)
6365
requireV68OfflineBalancesLocked(t, testApp, ctx, retained)
6466
upgradeHeight := ctx.BlockHeight() + 2
6567
require.NoError(t, testApp.UpgradeKeeper.ScheduleUpgrade(ctx, upgradetypes.Plan{
@@ -204,6 +206,20 @@ func seedV68Voucher(t *testing.T, testApp *App, ctx sdk.Context, retained *offli
204206
retained.VoucherSupply = testApp.BankKeeper.GetSupply(ctx, voucher.Denom).Amount.String()
205207
}
206208

209+
// seedV68OfflineDelegations stores delegations to two validators, which v6.7
210+
// writes without any delegation-by-validator index entry.
211+
func seedV68OfflineDelegations(testApp *App, ctx sdk.Context) {
212+
validators := []sdk.ValAddress{
213+
sdk.ValAddress(secp256k1.GenPrivKey().PubKey().Address()),
214+
sdk.ValAddress(secp256k1.GenPrivKey().PubKey().Address()),
215+
}
216+
for i := 0; i < 3; i++ {
217+
delegator := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address())
218+
testApp.StakingKeeper.SetDelegation(ctx,
219+
stakingtypes.NewDelegation(delegator, validators[i%len(validators)], sdk.NewDec(int64(i+1))))
220+
}
221+
}
222+
207223
// seedV68OfflineVestingAccounts writes one account of every vesting type
208224
// through the v6.7 keepers, each keyed and holding a balance its schedule
209225
// locks. The delayed vesting account is recorded as the sender of a

‎app/upgrade_v68_offline_target_test.go‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
distrtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution/types"
2424
govtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/gov/types"
2525
paramstypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/params/types"
26+
stakingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/types"
2627
upgradetypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/upgrade/types"
2728
"github.com/sei-protocol/sei-chain/sei-db/state_db/sc/memiavl"
2829
abci "github.com/sei-protocol/sei-chain/sei-tendermint/abci/types"
@@ -137,7 +138,8 @@ func applyV68OfflineUpgradeCrashReplay(t *testing.T, root string, artifact offli
137138
// accounts are rewritten, the retired IBC proposal reads back as a text
138139
// proposal, the upgraded IBC client record, the denom allowlists and the
139140
// tokenfactory parameters are pruned, the IBC voucher balance and supply are
140-
// intact and spendable, and nothing else in the retained stores changed.
141+
// intact and spendable, every delegation is indexed by validator, and nothing
142+
// else in the retained stores changed.
141143
func requireV68OfflineMigrated(t *testing.T, testApp *App, artifact offlineUpgradeArtifact) {
142144
t.Helper()
143145
requireV68OfflineAppliedName(t, testApp, artifact)
@@ -149,6 +151,7 @@ func requireV68OfflineMigrated(t *testing.T, testApp *App, artifact offlineUpgra
149151
requireV68OfflineDenomAllowListsPruned(t, testApp, artifact.Stores[banktypes.StoreKey])
150152
requireV68OfflineTokenfactoryParamsPruned(t, testApp, artifact.Stores[paramstypes.StoreKey])
151153
requireV68OfflineVoucher(t, testApp, artifact.Retained)
154+
requireV68OfflineDelegationIndex(t, testApp)
152155
requireOfflineUpgradeRetainedStoresExcept(t, testApp, artifact.Stores, v68OfflineTouchedKey(t, artifact))
153156
}
154157

@@ -281,6 +284,31 @@ func requireV68OfflineStoresDeleted(t *testing.T, testApp *App) {
281284
}
282285
}
283286

287+
// requireV68OfflineDelegationIndex requires the delegation-by-validator index
288+
// to be ready and to hold exactly one entry per stored delegation.
289+
func requireV68OfflineDelegationIndex(t *testing.T, testApp *App) {
290+
t.Helper()
291+
ctx := offlineUpgradeReadContext(testApp, testApp.LastBlockHeight())
292+
require.True(t, testApp.StakingKeeper.DelegationByValIndexReady(ctx))
293+
store := ctx.KVStore(testApp.GetKey(stakingtypes.StoreKey))
294+
295+
delegations := map[string]struct{}{}
296+
iterator := sdk.KVStorePrefixIterator(store, stakingtypes.DelegationKey)
297+
for ; iterator.Valid(); iterator.Next() {
298+
delegations[string(iterator.Key())] = struct{}{}
299+
}
300+
require.NoError(t, iterator.Close())
301+
require.NotEmpty(t, delegations, "the source phase stored no delegations")
302+
303+
indexed := map[string]struct{}{}
304+
iterator = sdk.KVStorePrefixIterator(store, stakingtypes.DelegationByValIndexKey)
305+
for ; iterator.Valid(); iterator.Next() {
306+
indexed[string(stakingtypes.GetDelegationKeyFromValIndexKey(iterator.Key()))] = struct{}{}
307+
}
308+
require.NoError(t, iterator.Close())
309+
require.Equal(t, delegations, indexed, "the index does not hold exactly one entry per delegation")
310+
}
311+
284312
func requireV68OfflineProposalRewritten(t *testing.T, testApp *App, retained offlineUpgradeRetainedState) {
285313
t.Helper()
286314
ctx := offlineUpgradeReadContext(testApp, testApp.LastBlockHeight())

‎app/upgrade_v68_test.go‎

Lines changed: 87 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ import (
2323
banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types"
2424
govtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/gov/types"
2525
paramstypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/params/types"
26+
"github.com/sei-protocol/sei-chain/sei-cosmos/x/staking"
27+
stakingkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/keeper"
28+
stakingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/types"
2629
upgradetypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/upgrade/types"
2730
abci "github.com/sei-protocol/sei-chain/sei-tendermint/abci/types"
2831
"github.com/sei-protocol/sei-chain/testutil/processblock"
@@ -41,7 +44,9 @@ import (
4144
// base accounts they embed. These tests cover the rewrite of every vesting
4245
// account type, spending a balance a schedule had locked, the messages the
4346
// removed modules served, the allowlist and parameter pruning, genesis export
44-
// over the migrated store, and the handler itself.
47+
// over the migrated store, and the handler itself. The handler also starts the
48+
// staking delegation-by-validator index backfill, which the staking EndBlocker
49+
// completes.
4550

4651
// v68RemovedStoreModules are the module version map entries the v6.8 handler
4752
// deletes along with their stores.
@@ -331,6 +336,87 @@ func TestV68ApplyUpgradeTwice(t *testing.T) {
331336
"second ApplyUpgrade is not a no-op: ApplyUpgrade increments protocol version on every call")
332337
}
333338

339+
// unreadyV68DelegationIndex deletes the delegation-by-validator index and its
340+
// markers, leaving the staking store as v6.7 left it.
341+
func unreadyV68DelegationIndex(t *testing.T, a *processblock.App) {
342+
t.Helper()
343+
store := a.Ctx().KVStore(a.GetKey(stakingtypes.StoreKey))
344+
iterator := sdk.KVStorePrefixIterator(store, stakingtypes.DelegationByValIndexKey)
345+
var keys [][]byte
346+
for ; iterator.Valid(); iterator.Next() {
347+
keys = append(keys, iterator.Key())
348+
}
349+
require.NoError(t, iterator.Close())
350+
for _, key := range keys {
351+
store.Delete(key)
352+
}
353+
store.Delete(stakingtypes.DelegationByValIndexReadyKey)
354+
store.Delete(stakingtypes.DelegationByValIndexCursorKey)
355+
}
356+
357+
// v68DelegationKeys returns the keys of every stored delegation.
358+
func v68DelegationKeys(t *testing.T, store sdk.KVStore) map[string]struct{} {
359+
t.Helper()
360+
return v68PrefixKeys(t, store, stakingtypes.DelegationKey, func(key []byte) []byte { return key })
361+
}
362+
363+
// v68IndexedDelegationKeys returns the delegation key every index entry points at.
364+
func v68IndexedDelegationKeys(t *testing.T, store sdk.KVStore) map[string]struct{} {
365+
t.Helper()
366+
return v68PrefixKeys(t, store, stakingtypes.DelegationByValIndexKey, stakingtypes.GetDelegationKeyFromValIndexKey)
367+
}
368+
369+
func v68PrefixKeys(t *testing.T, store sdk.KVStore, prefix []byte, resolve func([]byte) []byte) map[string]struct{} {
370+
t.Helper()
371+
iterator := sdk.KVStorePrefixIterator(store, prefix)
372+
defer func() { require.NoError(t, iterator.Close()) }()
373+
keys := map[string]struct{}{}
374+
for ; iterator.Valid(); iterator.Next() {
375+
keys[string(resolve(iterator.Key()))] = struct{}{}
376+
}
377+
return keys
378+
}
379+
380+
func TestV68PopulatesDelegationByValIndex(t *testing.T) {
381+
a := newV68Chain(t)
382+
unreadyV68DelegationIndex(t, a)
383+
ctx := a.Ctx()
384+
store := ctx.KVStore(a.GetKey(stakingtypes.StoreKey))
385+
386+
validators := a.StakingKeeper.GetAllValidators(ctx)
387+
require.NotEmpty(t, validators)
388+
valAddr := validators[0].GetOperator()
389+
delAddr := a.NewAccount()
390+
a.StakingKeeper.SetDelegation(ctx, stakingtypes.NewDelegation(delAddr, valAddr, sdk.NewDec(68)))
391+
require.False(t, store.Has(stakingtypes.GetDelegationByValIndexKey(delAddr, valAddr)),
392+
"a delegation written before v6.8 is indexed")
393+
394+
applyV68(t, a)
395+
396+
require.False(t, a.StakingKeeper.DelegationByValIndexReady(ctx),
397+
"v6.8 populated the index inside the upgrade handler")
398+
require.True(t, store.Has(stakingtypes.DelegationByValIndexCursorKey),
399+
"v6.8 did not start the index backfill")
400+
staking.EndBlocker(ctx, a.StakingKeeper)
401+
402+
require.True(t, a.StakingKeeper.DelegationByValIndexReady(ctx))
403+
require.False(t, store.Has(stakingtypes.DelegationByValIndexCursorKey))
404+
delegations := v68DelegationKeys(t, store)
405+
require.Contains(t, delegations, string(stakingtypes.GetDelegationKey(delAddr, valAddr)))
406+
require.Equal(t, delegations, v68IndexedDelegationKeys(t, store),
407+
"the index does not hold exactly one entry per delegation")
408+
409+
querier := stakingkeeper.Querier{Keeper: a.StakingKeeper}
410+
res, err := querier.ValidatorDelegations(sdk.WrapSDKContext(ctx),
411+
&stakingtypes.QueryValidatorDelegationsRequest{ValidatorAddr: valAddr.String()})
412+
require.NoError(t, err)
413+
var delegators []string
414+
for _, response := range res.DelegationResponses {
415+
delegators = append(delegators, response.Delegation.DelegatorAddress)
416+
}
417+
require.Contains(t, delegators, delAddr.String())
418+
}
419+
334420
// TestV68RejectsOracleTxsWithoutCharging pins that retired oracle transactions
335421
// are refused before fees are charged.
336422
func TestV68RejectsOracleTxsWithoutCharging(t *testing.T) {

‎app/upgrades.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,7 @@ func (app *App) RegisterUpgradeHandlers() {
169169
app.pruneUpgradedIBCState(ctx)
170170
app.pruneDenomAllowLists(ctx)
171171
app.pruneTokenfactoryParams(ctx)
172+
app.StakingKeeper.StartDelegationByValIndexBackfill(ctx)
172173
return newVM, nil
173174
}
174175

‎evmrpc/tests/regression_test.go‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"github.com/sei-protocol/sei-chain/evmrpc"
1414
sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types"
1515
govtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/gov/types"
16+
stakingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/types"
1617
tmproto "github.com/sei-protocol/sei-chain/sei-tendermint/proto/tendermint/types"
1718
"github.com/stretchr/testify/require"
1819
)
@@ -387,7 +388,7 @@ func testTx(t *testing.T, txHash string, version string, expectedGasUsed string,
387388
blockHeight := mockStatesFromTxJson(ctx, txHash, a, mc)
388389
ctx = setLegacySstoreIfNeeded(ctx, a, version)
389390
ctx = withCapturedConsensusParams(ctx, mc, blockHeight)
390-
removeFutureGovernanceActivation(ctx, a, version)
391+
removeFutureActivations(ctx, a, version)
391392
return ctx.WithBlockHeight(blockHeight)
392393
})
393394
s.Run(
@@ -428,7 +429,7 @@ func testBlock(
428429
)
429430
ctx = setLegacySstoreIfNeeded(ctx, a, version)
430431
ctx = withCapturedConsensusParams(ctx, mc, blockHeight)
431-
removeFutureGovernanceActivation(ctx, a, version)
432+
removeFutureActivations(ctx, a, version)
432433
return ctx.WithBlockHeight(blockHeight)
433434
},
434435
)
@@ -460,9 +461,12 @@ func setLegacySstoreIfNeeded(ctx sdk.Context, a *app.App, version string) sdk.Co
460461
return ctx
461462
}
462463

463-
func removeFutureGovernanceActivation(ctx sdk.Context, a *app.App, version string) {
464+
// removeFutureActivations clears the markers genesis sets for features that mainnet
465+
// only turns on at a later upgrade than version.
466+
func removeFutureActivations(ctx sdk.Context, a *app.App, version string) {
464467
if semver.Compare(version, "v6.8") < 0 {
465468
ctx.KVStore(a.GetKey(govtypes.StoreKey)).Delete(govtypes.IncrementalTallyEnabledKey)
469+
ctx.KVStore(a.GetKey(stakingtypes.StoreKey)).Delete(stakingtypes.DelegationByValIndexReadyKey)
466470
}
467471
}
468472

‎sei-cosmos/x/staking/abci.go‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,28 @@ func BeginBlocker(ctx sdk.Context, k keeper.Keeper) {
1919
k.TrackHistoricalInfo(ctx)
2020
}
2121

22-
// Called every block, update validator set
22+
// backfillDelegationByValIndex indexes the next batch of delegations while the
23+
// delegation-by-validator index is backfilled. It runs after every transaction in the
24+
// block, so no transaction iterates the staking store while the batch's writes are
25+
// pending in it. A delegation that cannot be decoded halts the chain, as it would at
26+
// any other read.
27+
func backfillDelegationByValIndex(ctx sdk.Context, k keeper.Keeper) {
28+
// The batch is block-level work, so it is not charged to any gas meter.
29+
ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter(1, 1))
30+
if _, err := k.BackfillDelegationByValIndex(ctx, keeper.DelegationByValIndexBackfillBatchSize); err != nil {
31+
panic(err)
32+
}
33+
}
34+
35+
// Called every block, update validator set. It also advances the
36+
// delegation-by-validator index backfill while one is in progress.
2337
func EndBlocker(ctx sdk.Context, k keeper.Keeper) []abci.ValidatorUpdate {
2438
endBlockerStart := time.Now()
2539
defer func() {
2640
stakingMetrics.endBlockerDuration.Record(ctx.Context(), time.Since(endBlockerStart).Seconds())
2741
}()
2842

29-
return k.BlockValidatorUpdates(ctx)
43+
updates := k.BlockValidatorUpdates(ctx)
44+
backfillDelegationByValIndex(ctx, k)
45+
return updates
3046
}

‎sei-cosmos/x/staking/genesis.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,10 @@ func InitGenesis(
7676
}
7777
}
7878

79+
if _, err := keeper.MigrateDelegationByValIndex(ctx); err != nil {
80+
panic(err)
81+
}
82+
7983
for _, ubd := range data.UnbondingDelegations {
8084
keeper.SetUnbondingDelegation(ctx, ubd)
8185

‎sei-cosmos/x/staking/genesis_test.go‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,36 @@ func TestInitGenesis(t *testing.T) {
9797
require.Equal(t, abcivals, vals)
9898
}
9999

100+
func TestInitGenesisIndexesDelegationsByValidator(t *testing.T) {
101+
app, ctx, addrs := bootstrapGenesisTest(t, 2)
102+
store := ctx.KVStore(app.StakingKeeper.GetStoreKey())
103+
store.Delete(types.DelegationByValIndexReadyKey)
104+
105+
valTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 1)
106+
params := app.StakingKeeper.GetParams(ctx)
107+
pk, err := codectypes.NewAnyWithValue(PKs[0])
108+
require.NoError(t, err)
109+
valAddr := sdk.ValAddress(addrs[0])
110+
validator := types.Validator{
111+
OperatorAddress: valAddr.String(),
112+
ConsensusPubkey: pk,
113+
Status: types.Bonded,
114+
Tokens: valTokens,
115+
DelegatorShares: valTokens.ToDec(),
116+
Description: types.NewDescription("hoop", "", "", "", ""),
117+
}
118+
validators := append(app.StakingKeeper.GetAllValidators(ctx), validator)
119+
require.NoError(t, apptesting.FundModuleAccount(app.BankKeeper, ctx, types.BondedPoolName,
120+
sdk.NewCoins(sdk.NewCoin(params.BondDenom, valTokens.MulRaw(int64(len(validators)))))))
121+
delegation := types.NewDelegation(addrs[1], valAddr, valTokens.ToDec())
122+
123+
staking.InitGenesis(ctx, app.StakingKeeper, app.AccountKeeper, app.BankKeeper,
124+
types.NewGenesisState(params, validators, []types.Delegation{delegation}))
125+
126+
require.True(t, app.StakingKeeper.DelegationByValIndexReady(ctx))
127+
require.True(t, store.Has(types.GetDelegationByValIndexKey(addrs[1], valAddr)))
128+
}
129+
100130
func TestInitGenesis_PoolsBalanceMismatch(t *testing.T) {
101131
app := seiapp.Setup(t, false, false, false)
102132
ctx := app.NewContext(false, tmproto.Header{})

‎sei-cosmos/x/staking/keeper/delegation.go‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,19 +98,27 @@ func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddres
9898
// SetDelegation sets a delegation.
9999
func (k Keeper) SetDelegation(ctx sdk.Context, delegation types.Delegation) {
100100
delegatorAddress := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress)
101+
valAddr := delegation.GetValidatorAddr()
101102

102103
store := ctx.KVStore(k.storeKey)
103104
b := types.MustMarshalDelegation(k.cdc, delegation)
104-
store.Set(types.GetDelegationKey(delegatorAddress, delegation.GetValidatorAddr()), b)
105+
store.Set(types.GetDelegationKey(delegatorAddress, valAddr), b)
106+
if k.delegationByValIndexMaintained(ctx) {
107+
store.Set(types.GetDelegationByValIndexKey(delegatorAddress, valAddr), []byte{}) // index, store empty bytes
108+
}
105109
}
106110

107111
// RemoveDelegation removes a delegation.
108112
func (k Keeper) RemoveDelegation(ctx sdk.Context, delegation types.Delegation) {
109113
delegatorAddress := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress)
114+
valAddr := delegation.GetValidatorAddr()
110115

111-
k.BeforeDelegationRemoved(ctx, delegatorAddress, delegation.GetValidatorAddr())
116+
k.BeforeDelegationRemoved(ctx, delegatorAddress, valAddr)
112117
store := ctx.KVStore(k.storeKey)
113-
store.Delete(types.GetDelegationKey(delegatorAddress, delegation.GetValidatorAddr()))
118+
store.Delete(types.GetDelegationKey(delegatorAddress, valAddr))
119+
if k.delegationByValIndexMaintained(ctx) {
120+
store.Delete(types.GetDelegationByValIndexKey(delegatorAddress, valAddr))
121+
}
114122
}
115123

116124
// GetUnbondingDelegations returns a given amount of all the delegator unbonding-delegations.

0 commit comments

Comments
 (0)