Skip to content

Commit 5f5562f

Browse files
manav2401claude
andauthored
staking: branch precompile views and validate redelegations filters (#4527)
This PR addresses 2 things associated with staking precompile. - The staking precompile (which serves Cosmos module queries) runs it's view methods on live EVM context instead of a cached context. While no methods update state (`pool` does but not on a live chain), a method added in future isn't prevented from writing to the EVM context. Hence, this PR uses a temporary state (like other precompiles) so that queries can't persist from a view or static call. `PrecompileExecutor.IsTransaction` now lists the ten state-changing staking methods, and `Execute` runs every other method on a branched context, matching the sibling precompiles. `TestIsTransactionMatchesABI` ties that list to the ABI's `stateMutability`, so a method added later cannot be misclassified without failing CI. ` - `redelegations` now accepts only the filter combinations the staking module can answer: delegator, source validator and destination validator together, source validator alone, or delegator alone. Any other combination reverts with a clear error, and `Staking.sol` now documents the supported combinations. Supporting the remaining combinations would need new query paths and would change gRPC/REST answers, so it is left for a follow-up. This is state-machine breaking change, so this must ship only in the v6.8 coordinated upgrade and must not be backported to `release/v6.7`. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent c719251 commit 5f5562f

4 files changed

Lines changed: 164 additions & 4 deletions

File tree

‎precompiles/staking/Staking.sol‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -289,10 +289,11 @@ interface IStaking {
289289
) external view returns (UnbondingDelegationsResponse memory response);
290290

291291
/**
292-
* @notice Get redelegations
293-
* @param delegator The delegator's address (empty string for all)
294-
* @param srcValidator The source validator address (empty string for all)
295-
* @param dstValidator The destination validator address (empty string for all)
292+
* @notice Get redelegations. Supported filters: delegator, srcValidator and dstValidator
293+
* together; srcValidator alone; or delegator alone. Any other combination reverts.
294+
* @param delegator The delegator's address, or empty when filtering by srcValidator alone
295+
* @param srcValidator The source validator address, or empty when filtering by delegator alone
296+
* @param dstValidator The destination validator address, set only with delegator and srcValidator
296297
* @param nextKey Pagination key
297298
* @return response Redelegations response with pagination
298299
*/

‎precompiles/staking/legacy/v68/staking.go‎

Lines changed: 35 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎precompiles/staking/staking.go‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,10 +171,28 @@ func (p PrecompileExecutor) EVMKeeper() utils.EVMKeeper {
171171
return p.evmKeeper
172172
}
173173

174+
// IsTransaction returns true for methods that mutate state; all other
175+
// staking methods are views.
176+
func (PrecompileExecutor) IsTransaction(method string) bool {
177+
switch method {
178+
case DelegateMethod, RedelegateMethod, UndelegateMethod, GrantStakingMethod, DelegateWithAuthzMethod,
179+
RedelegateWithAuthzMethod, UndelegateWithAuthzMethod, RevokeStakingMethod, CreateValidatorMethod, EditValidatorMethod:
180+
return true
181+
default:
182+
return false
183+
}
184+
}
185+
174186
func (p PrecompileExecutor) Execute(ctx sdk.Context, method *abi.Method, caller common.Address, callingContract common.Address, args []interface{}, value *big.Int, readOnly bool, evm *vm.EVM, suppliedGas uint64, hooks *tracing.Hooks) (ret []byte, remainingGas uint64, err error) {
175187
if ctx.EVMPrecompileCalledFromDelegateCall() {
176188
return nil, 0, errors.New("cannot delegatecall staking")
177189
}
190+
if !p.IsTransaction(method.Name) {
191+
// Queries must not mutate state even when the underlying querier has
192+
// side effects (e.g. Pool creates a missing pool module account), so
193+
// run every view on a branched context and discard the writes.
194+
ctx, _ = ctx.CacheContext()
195+
}
178196
switch method.Name {
179197
case DelegateMethod:
180198
if readOnly {
@@ -1295,6 +1313,9 @@ func (p PrecompileExecutor) redelegations(ctx sdk.Context, method *abi.Method, a
12951313
srcValidatorStr := args[1].(string)
12961314
dstValidatorStr := args[2].(string)
12971315
nextKey := args[3].([]byte)
1316+
if err := validateRedelegationsFilter(delegatorStr, srcValidatorStr, dstValidatorStr); err != nil {
1317+
return nil, 0, err
1318+
}
12981319

12991320
request := &stakingtypes.QueryRedelegationsRequest{
13001321
DelegatorAddr: delegatorStr,
@@ -1341,6 +1362,20 @@ func (p PrecompileExecutor) redelegations(ctx sdk.Context, method *abi.Method, a
13411362
return bz, pcommon.GetRemainingGas(ctx, p.evmKeeper), nil
13421363
}
13431364

1365+
// validateRedelegationsFilter rejects filter combinations the staking querier does not
1366+
// honour. It supports delegator, srcValidator and dstValidator together, srcValidator
1367+
// alone, and delegator alone.
1368+
func validateRedelegationsFilter(delegator, srcValidator, dstValidator string) error {
1369+
switch {
1370+
case delegator != "" && srcValidator != "" && dstValidator != "":
1371+
case delegator == "" && srcValidator != "" && dstValidator == "":
1372+
case delegator != "" && srcValidator == "" && dstValidator == "":
1373+
default:
1374+
return errors.New("unsupported redelegations filter: set delegator, srcValidator and dstValidator; srcValidator only; or delegator only")
1375+
}
1376+
return nil
1377+
}
1378+
13441379
func (p PrecompileExecutor) delegatorValidators(ctx sdk.Context, method *abi.Method, args []interface{}, value *big.Int) ([]byte, uint64, error) {
13451380
if err := pcommon.ValidateNonPayable(value); err != nil {
13461381
return nil, 0, err

‎precompiles/staking/staking_test.go‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import (
2626
crptotypes "github.com/sei-protocol/sei-chain/sei-cosmos/crypto/types"
2727
sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types"
2828
"github.com/sei-protocol/sei-chain/sei-cosmos/types/query"
29+
authtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/auth/types"
2930
slashingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/slashing/types"
3031
"github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/teststaking"
3132
stakingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/types"
@@ -1545,6 +1546,60 @@ func TestPrecompile_Run_Redelegations(t *testing.T) {
15451546
wantRet: happyPathPackedOutput,
15461547
wantErr: false,
15471548
},
1549+
{
1550+
name: "should return redelegations filtered by source validator only",
1551+
fields: &TestStakingQuerier{
1552+
RedelegationsResponse: redelegationsResponse,
1553+
},
1554+
args: []interface{}{"", srcValidatorAddress, "", []byte{}},
1555+
wantRet: happyPathPackedOutput,
1556+
wantErr: false,
1557+
},
1558+
{
1559+
name: "should return redelegations filtered by delegator only",
1560+
fields: &TestStakingQuerier{
1561+
RedelegationsResponse: redelegationsResponse,
1562+
},
1563+
args: []interface{}{callerSeiAddress.String(), "", "", []byte{}},
1564+
wantRet: happyPathPackedOutput,
1565+
wantErr: false,
1566+
},
1567+
{
1568+
name: "fails with delegator and source validator only",
1569+
fields: &TestStakingQuerier{
1570+
RedelegationsResponse: redelegationsResponse,
1571+
},
1572+
args: []interface{}{callerSeiAddress.String(), srcValidatorAddress, "", []byte{}},
1573+
wantErr: true,
1574+
wantErrMsg: "unsupported redelegations filter",
1575+
},
1576+
{
1577+
name: "fails with delegator and destination validator only",
1578+
fields: &TestStakingQuerier{
1579+
RedelegationsResponse: redelegationsResponse,
1580+
},
1581+
args: []interface{}{callerSeiAddress.String(), "", dstValidatorAddress, []byte{}},
1582+
wantErr: true,
1583+
wantErrMsg: "unsupported redelegations filter",
1584+
},
1585+
{
1586+
name: "fails with destination validator only",
1587+
fields: &TestStakingQuerier{
1588+
RedelegationsResponse: redelegationsResponse,
1589+
},
1590+
args: []interface{}{"", "", dstValidatorAddress, []byte{}},
1591+
wantErr: true,
1592+
wantErrMsg: "unsupported redelegations filter",
1593+
},
1594+
{
1595+
name: "fails with no filter",
1596+
fields: &TestStakingQuerier{
1597+
RedelegationsResponse: redelegationsResponse,
1598+
},
1599+
args: []interface{}{"", "", "", []byte{}},
1600+
wantErr: true,
1601+
wantErrMsg: "unsupported redelegations filter",
1602+
},
15481603
}
15491604

15501605
for _, tt := range tests {
@@ -2601,3 +2656,37 @@ func TestStakingPrecompileStaticCallPrevention(t *testing.T) {
26012656
_ = err
26022657
})
26032658
}
2659+
2660+
func TestIsTransactionMatchesABI(t *testing.T) {
2661+
p, err := staking.NewPrecompile(&utils.EmptyKeepers{})
2662+
require.NoError(t, err)
2663+
executor := p.GetExecutor().(*staking.PrecompileExecutor)
2664+
for name, method := range p.ABI.Methods {
2665+
require.Equal(t, method.StateMutability != "view", executor.IsTransaction(name), name)
2666+
}
2667+
}
2668+
2669+
func TestPoolQueryDoesNotPersistWrites(t *testing.T) {
2670+
testApp := testkeeper.EVMTestApp
2671+
ctx, _ := testApp.NewContext(false, tmtypes.Header{}).WithBlockHeight(2).CacheContext()
2672+
authKey := testApp.GetKey(authtypes.StoreKey)
2673+
2674+
// Pool creates the bonded pool module account when it is missing.
2675+
bondedAddr := testApp.AccountKeeper.GetModuleAddress(stakingtypes.BondedPoolName)
2676+
acc := testApp.AccountKeeper.GetAccount(ctx, bondedAddr)
2677+
require.NotNil(t, acc)
2678+
testApp.AccountKeeper.RemoveAccount(ctx, acc)
2679+
accountNumber := ctx.KVStore(authKey).Get(authtypes.GlobalAccountNumberKey)
2680+
2681+
p, err := staking.NewPrecompile(testApp.GetPrecompileKeepers())
2682+
require.NoError(t, err)
2683+
stateDb := state.NewDBImpl(ctx, &testApp.EvmKeeper, true)
2684+
evm := vm.EVM{StateDB: stateDb}
2685+
poolID := p.GetExecutor().(*staking.PrecompileExecutor).PoolID
2686+
_, _, err = p.RunAndCalculateGas(&evm, common.Address{}, common.Address{}, poolID, math.MaxUint64, nil, nil, true, false)
2687+
require.NoError(t, err)
2688+
2689+
after := stateDb.Ctx()
2690+
require.False(t, testApp.AccountKeeper.HasAccount(after, bondedAddr))
2691+
require.Equal(t, accountNumber, after.KVStore(authKey).Get(authtypes.GlobalAccountNumberKey))
2692+
}

0 commit comments

Comments
 (0)