Skip to content

Commit 2717a84

Browse files
codchenshemnonclaude
authored
feat(params): add the staking subspace (#4727)
## Summary Adds staking's params to the giga params precompile's storage, for the staking precompile to read. - A `Staking` struct in `ParamsStorage` at slot 16: `unbondingTime`, `maxValidators`, `maxEntries`, `maxVotingPowerRatio` and `maxVotingPowerEnforcementThreshold`. - `ReadStaking`, `HasStaking` and `WriteStaking`. They are written once at genesis; later changes go through gov. - Bounds, so a change can't wedge staking: unbonding time within the period bounds, 1 to 100 bonded validators (the most an autobahn committee can hold), at least one entry, and a ratio in (0, 1]. - Regenerated harness and layout testdata. Gov's param-change test now uses only gov's own keys. ## Test plan - [x] `go test -race ./giga/evmonly/precompiles/...` - [x] Layout pinned against solc output; the harness's writes are read back through Go. ## Stack Replaces #4713. Each PR's base is the one above it; review and merge from the top. 1. #4726 docs(giga-storage): keep only the staking structures an on-chain path reads 2. #4727 feat(params): add the staking subspace **← this PR** 3. #4728 feat(staking): read and write the staking precompile's storage 4. #4729 feat(staking): delegate, redelegate and undelegate in a giga evmonly precompile 5. #4730 test(staking): check delegations and EndBlock against x/staking 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Danno Ferrin <danno@seinetwork.io> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 0a76a7c commit 2717a84

13 files changed

Lines changed: 426 additions & 57 deletions

‎docs/giga-storage/ParamsStorage.sol‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ pragma solidity 0.8.30;
88
/// - Dec: uint256, fixed point with 18 decimal places (1e18 is 1).
99
/// - Duration: uint64 nanoseconds.
1010
/// - Coins: uint256 wei, a whole number of usei; only the usei denom exists.
11+
/// - Int: uint256.
12+
/// - uint32: uint32.
1113
/// Other V2 types have no stored form until a param needs one.
1214
///
1315
/// Once a public network runs this, the layout only grows: a new param takes
@@ -29,5 +31,16 @@ contract ParamsStorage {
2931
uint256[8] __gap;
3032
}
3133

34+
/// @dev x/staking's params. The enforcement threshold is consensus power.
35+
struct Staking {
36+
uint64 unbondingTime; // UnbondingTime
37+
uint32 maxValidators; // MaxValidators
38+
uint32 maxEntries; // MaxEntries
39+
uint256 maxVotingPowerRatio; // MaxVotingPower
40+
uint256 maxVotingPowerEnforcementThreshold; // MaxVotingPowerEnforcementThreshold
41+
uint256[8] __gap;
42+
}
43+
3244
Gov internal gov; // subspace "gov"
45+
Staking internal staking; // subspace "staking"
3346
}

‎docs/giga-storage/params-design.md‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,18 +28,21 @@ subspace.
2828
| Dec | `uint256`, fixed point with 18 decimal places |
2929
| Duration | `uint64` nanoseconds; every period, read or written, is nanoseconds |
3030
| Coins | `uint256` wei, a whole number of usei; only the usei denom exists |
31+
| Int | `uint256` |
32+
| uint32 | `uint32` |
3133

3234
Another V2 type gets a stored form when a param first needs one. A value of
3335
any unsigned width is stored in the bytes of its slot that solc gives its
3436
field, so packed fields keep their neighbours. Values decode as unsigned: a
3537
signed type needs a decoder before a param can use it.
3638

3739
- Owners read their params from 0x1013's storage with the `params` package's
38-
Go readers (`ReadGov`). Gov reads `gov`. Nothing keeps a second copy.
40+
Go readers (`ReadGov`, `ReadStaking`). Gov reads `gov` and staking reads
41+
`staking`. Nothing keeps a second copy.
3942
Planned readers for other subspaces are in *Later subspaces*.
40-
- Params are written only at genesis (`WriteGov`, which refuses once gov's
41-
params exist) and by a passed gov proposal (`Apply`). Both check the whole
42-
subspace first.
43+
- Params are written only at genesis (`WriteGov` and `WriteStaking`, which
44+
refuse once their subspace's params exist) and by a passed gov proposal
45+
(`Apply`). Both check the whole subspace first.
4346

4447
## Declaration table
4548

@@ -165,6 +168,19 @@ naming `param`.
165168
- Autobahn registers the params precompile next to gov when `evm_governance`
166169
is set. Like gov, it refuses calls until the first block writes gov's params.
167170

171+
## Staking
172+
173+
- `staking` holds x/staking's `UnbondingTime`, `MaxValidators`, `MaxEntries`,
174+
`MaxVotingPower` (the max voting power ratio) and
175+
`MaxVotingPowerEnforcementThreshold`, in consensus power. `BondDenom` has no
176+
param, since only usei exists; `HistoricalEntries` has none, since giga keeps
177+
no historical info; `MinCommissionRate` comes with validator creation.
178+
- Its check is x/staking's validation plus an unbonding time of `MinPeriod` to
179+
`MaxPeriod`, and `MaxValidators` at most 100 (`MaxBondedValidators`), the
180+
most members an autobahn committee holds.
181+
- `HasStaking` reads `UnbondingTime`, which the check keeps nonzero. Staking
182+
refuses calls, and its EndBlock does nothing, until the params are written.
183+
168184
## Tests
169185

170186
- Layout: every `ParamsStorage.sol` slot, offset and field type, and values the
@@ -193,5 +209,4 @@ has eleven today.
193209
| baseapp | `BlockParams.max_gas` (and the other BlockParams fields) | evmonlyapp, per block |
194210
| evm | `KeyMinFeePerGas`, `KeySeiSstoreSetGasEIP2200`, later the EIP-1559 set | executor, per block |
195211
| migration | `NumKeysToMigratePerBlock`, `MigrateCosmosEnabled` | as needed |
196-
| staking | the staking params | native staking |
197212
| slashing | the slashing params | native slashing |

‎giga/evmonly/client/cli/paramchange.go‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,8 @@ func flatChanges(v2 []v2ParamChange) ([]paramChange, error) {
117117

118118
// encodeParam returns raw, a V2 JSON value, as the 32-byte abi.encode of k's
119119
// value. A Dec is a decimal string or number, a Duration nanoseconds or a Go
120-
// duration string such as "30s", and Coins a usei coin string or V2's coin
121-
// array.
120+
// duration string such as "30s", Coins a usei coin string or V2's coin array,
121+
// and an Int a whole-number string or number.
122122
func encodeParam(k chainparams.Key, raw json.RawMessage) ([]byte, error) {
123123
var v *big.Int
124124
var err error
@@ -129,6 +129,8 @@ func encodeParam(k chainparams.Key, raw json.RawMessage) ([]byte, error) {
129129
v, err = parseDurationValue(raw)
130130
case chainparams.KindCoins:
131131
v, err = parseCoinsValue(raw)
132+
case chainparams.KindInt:
133+
v, err = parseIntValue(raw)
132134
default:
133135
err = fmt.Errorf("unknown param kind %d", k.Kind)
134136
}
@@ -216,8 +218,21 @@ func parseCoinsValue(raw json.RawMessage) (*big.Int, error) {
216218
return depositWei(s)
217219
}
218220

221+
func parseIntValue(raw json.RawMessage) (*big.Int, error) {
222+
s, err := jsonScalar(raw)
223+
if err != nil {
224+
return nil, err
225+
}
226+
v, ok := new(big.Int).SetString(s, 10)
227+
if !ok {
228+
return nil, fmt.Errorf("integer %q: want a whole number", s)
229+
}
230+
return v, nil
231+
}
232+
219233
// formatParam returns v, a value of k, as V2 JSON: a Dec as a decimal string,
220-
// a Duration as nanoseconds, and Coins as a usei coin array.
234+
// a Duration as nanoseconds, Coins as a usei coin array, and an Int as a
235+
// number when it is a uint32 and a string otherwise.
221236
func formatParam(k chainparams.Key, v *big.Int) (json.RawMessage, error) {
222237
switch k.Kind {
223238
case chainparams.KindDec:
@@ -229,6 +244,12 @@ func formatParam(k chainparams.Key, v *big.Int) (json.RawMessage, error) {
229244
return json.Marshal(strconv.FormatUint(v.Uint64(), 10))
230245
case chainparams.KindCoins:
231246
return json.Marshal(weiToCoins(v))
247+
case chainparams.KindInt:
248+
// V2's amino JSON writes uint32 as a number, and sdk.Int as a string.
249+
if k.SolType == "uint32" && v.IsUint64() {
250+
return json.Marshal(v.Uint64())
251+
}
252+
return json.Marshal(v.String())
232253
default:
233254
return nil, fmt.Errorf("unknown param kind %d", k.Kind)
234255
}

‎giga/evmonly/client/cli/paramchange_test.go‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,21 @@ func TestParamChangesRoundTrip(t *testing.T) {
2222
require.JSONEq(t, `{"max_deposit_period":"172800000000000","min_deposit":[{"denom":"usei","amount":"10"}]}`, v2[1].Value)
2323
}
2424

25+
func TestStakingParamChangesRoundTrip(t *testing.T) {
26+
changes, err := flatChanges([]v2ParamChange{
27+
{Subspace: "staking", Key: "MaxValidators", Value: json.RawMessage(`40`)},
28+
{Subspace: "staking", Key: "MaxVotingPowerEnforcementThreshold", Value: json.RawMessage(`"2000000"`)},
29+
{Subspace: "staking", Key: "MaxVotingPower", Value: json.RawMessage(`"0.25"`)},
30+
})
31+
require.NoError(t, err)
32+
v2, err := v2ParamChanges(changes)
33+
require.NoError(t, err)
34+
require.Len(t, v2, 3)
35+
require.JSONEq(t, `40`, v2[0].Value)
36+
require.JSONEq(t, `"2000000"`, v2[1].Value)
37+
require.JSONEq(t, `"0.250000000000000000"`, v2[2].Value)
38+
}
39+
2540
func TestFlatChangesRejects(t *testing.T) {
2641
for name, c := range map[string]struct {
2742
changes []v2ParamChange
@@ -38,6 +53,8 @@ func TestFlatChangesRejects(t *testing.T) {
3853
"other denom": {[]v2ParamChange{{Subspace: "gov", Key: "depositparams.min_deposit", Value: json.RawMessage(`"10uatom"`)}}, "only usei"},
3954
"blank coins": {[]v2ParamChange{{Subspace: "gov", Key: "depositparams.min_deposit", Value: json.RawMessage(`""`)}}, "want a coin amount"},
4055
"null coins": {[]v2ParamChange{{Subspace: "gov", Key: "depositparams.min_deposit", Value: json.RawMessage(`null`)}}, "want a coin amount"},
56+
"fractional int": {[]v2ParamChange{{Subspace: "staking", Key: "MaxValidators", Value: json.RawMessage(`"1.5"`)}}, "want a whole number"},
57+
"negative int": {[]v2ParamChange{{Subspace: "staking", Key: "MaxEntries", Value: json.RawMessage(`-1`)}}, "out of range"},
4158
"none": {nil, "no param changes"},
4259
} {
4360
_, err := flatChanges(c.changes)

‎giga/evmonly/precompiles/gov/paramchange_test.go‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,9 @@ func TestEveryGovParamChangesThroughAProposal(t *testing.T) {
280280
}
281281
var changes []paramChange
282282
for _, k := range chainparams.Keys() {
283-
changes = append(changes, paramChange{k.Subspace, k.Key, wantValues[k.Key]})
283+
if k.Subspace == "gov" {
284+
changes = append(changes, paramChange{k.Subspace, k.Key, wantValues[k.Key]})
285+
}
284286
}
285287
require.Len(t, changes, len(wantValues), "every declared gov param")
286288
id, err := h.submitParamChange(false, changes...)

‎giga/evmonly/precompiles/params/layout.go‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ var Address = common.HexToAddress("0x0000000000000000000000000000000000001013")
99

1010
// Top-level slots of docs/giga-storage/ParamsStorage.sol.
1111
const (
12-
slotGov = 0
12+
slotGov = 0
13+
slotStaking = 16
1314
)
1415

1516
// member is a struct member's position relative to the struct's base slot.
@@ -31,3 +32,12 @@ var (
3132
govExpeditedQuorum = member{6, 0}
3233
govExpeditedThreshold = member{7, 0}
3334
)
35+
36+
// ParamsStorage.Staking members.
37+
var (
38+
stakingUnbondingTime = member{0, 0}
39+
stakingMaxValidators = member{0, 8}
40+
stakingMaxEntries = member{0, 12}
41+
stakingMaxVotingPowerRatio = member{1, 0}
42+
stakingMaxVotingPowerEnforcementThreshold = member{2, 0}
43+
)

‎giga/evmonly/precompiles/params/layout_test.go‎

Lines changed: 38 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func TestLayoutMatchesForge(t *testing.T) {
4343
for _, e := range layout.Storage {
4444
got[e.Label] = member{slot: mustUint(t, e.Slot), offset: e.Offset}
4545
}
46-
require.Equal(t, map[string]member{"gov": {slotGov, 0}}, got)
46+
require.Equal(t, map[string]member{"gov": {slotGov, 0}, "staking": {slotStaking, 0}}, got)
4747

4848
structs := map[string]map[string]member{
4949
"Gov": {
@@ -59,7 +59,16 @@ func TestLayoutMatchesForge(t *testing.T) {
5959
"expeditedThreshold": govExpeditedThreshold,
6060
"__gap": {8, 0},
6161
},
62+
"Staking": {
63+
"unbondingTime": stakingUnbondingTime,
64+
"maxValidators": stakingMaxValidators,
65+
"maxEntries": stakingMaxEntries,
66+
"maxVotingPowerRatio": stakingMaxVotingPowerRatio,
67+
"maxVotingPowerEnforcementThreshold": stakingMaxVotingPowerEnforcementThreshold,
68+
"__gap": {3, 0},
69+
},
6270
}
71+
subspaceOf := map[string]*subspace{"Gov": &govSubspace, "Staking": &stakingSubspace}
6372
seen := 0
6473
for typeID, typ := range layout.Types {
6574
name, ok := strings.CutPrefix(typeID, "t_struct(")
@@ -73,7 +82,7 @@ func TestLayoutMatchesForge(t *testing.T) {
7382
for _, e := range typ.Members {
7483
at := member{slot: mustUint(t, e.Slot), offset: e.Offset}
7584
got[e.Label] = at
76-
for _, p := range govSubspace.params {
85+
for _, p := range subspaceOf[name].params {
7786
if p.at == at {
7887
require.Equal(t, "t_"+p.kind.solType, e.Type, p.key)
7988
}
@@ -88,16 +97,23 @@ func TestLayoutMatchesForge(t *testing.T) {
8897
// TestLayoutCoversEveryDeclaredParam checks each declared param sits at a
8998
// member of its subspace's struct.
9099
func TestLayoutCoversEveryDeclaredParam(t *testing.T) {
91-
members := map[member]bool{
92-
govMaxDepositPeriod: true, govVotingPeriod: true, govExpeditedVotingPeriod: true,
93-
govMinDeposit: true, govMinExpeditedDeposit: true, govQuorum: true, govThreshold: true,
94-
govVetoThreshold: true, govExpeditedQuorum: true, govExpeditedThreshold: true,
95-
}
96-
for _, p := range govSubspace.params {
97-
require.True(t, members[p.at], p.key)
98-
delete(members, p.at)
100+
for ss, members := range map[*subspace]map[member]bool{
101+
&govSubspace: {
102+
govMaxDepositPeriod: true, govVotingPeriod: true, govExpeditedVotingPeriod: true,
103+
govMinDeposit: true, govMinExpeditedDeposit: true, govQuorum: true, govThreshold: true,
104+
govVetoThreshold: true, govExpeditedQuorum: true, govExpeditedThreshold: true,
105+
},
106+
&stakingSubspace: {
107+
stakingUnbondingTime: true, stakingMaxValidators: true, stakingMaxEntries: true,
108+
stakingMaxVotingPowerRatio: true, stakingMaxVotingPowerEnforcementThreshold: true,
109+
},
110+
} {
111+
for _, p := range ss.params {
112+
require.True(t, members[p.at], p.key)
113+
delete(members, p.at)
114+
}
115+
require.Empty(t, members, "every %s member is declared once", ss.name)
99116
}
100-
require.Empty(t, members, "every member is declared once")
101117
}
102118

103119
func mustUint(t *testing.T, s string) uint64 {
@@ -108,16 +124,16 @@ func mustUint(t *testing.T, s string) uint64 {
108124

109125
// TestReadsCompilerWrites runs ParamsStorageHarness, which writes
110126
// ParamsStorage with solc's codegen, and reads the result back. Rebuild
111-
// testdata with `forge inspect ParamsStorageHarness deployedBytecode` and the
112-
// remapping giga-storage/=docs/giga-storage/.
127+
// testdata from the repository root with solc 0.8.30 and
128+
// `solc --bin-runtime giga-storage/=docs/giga-storage/ giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.sol`.
113129
func TestReadsCompilerWrites(t *testing.T) {
114130
code, err := os.ReadFile("testdata/ParamsStorageHarness.bin-runtime")
115131
require.NoError(t, err)
116132
seed := common.FromHex("0x7d94792a") // seed()
117133
_, db, err := runtime.Execute(common.FromHex(strings.TrimSpace(string(code))), seed, &runtime.Config{GasLimit: 10_000_000})
118134
require.NoError(t, err)
119135
// runtime.Execute deploys the code at the zero-padded address of "contract".
120-
values := govSubspace.read(solstorage.Store{State: stateDBView{db}, Address: common.BytesToAddress([]byte("contract"))})
136+
s := solstorage.Store{State: stateDBView{db}, Address: common.BytesToAddress([]byte("contract"))}
121137
require.Equal(t, Gov{
122138
MaxDepositPeriod: 172_800_000_000_000,
123139
VotingPeriod: 259_200_000_000_000,
@@ -129,5 +145,12 @@ func TestReadsCompilerWrites(t *testing.T) {
129145
VetoThreshold: big.NewInt(334_000_000_000_000_000),
130146
ExpeditedQuorum: big.NewInt(667_000_000_000_000_000),
131147
ExpeditedThreshold: big.NewInt(667_000_000_000_000_000),
132-
}, govFrom(values))
148+
}, govFrom(govSubspace.read(s)))
149+
require.Equal(t, Staking{
150+
UnbondingTime: 1_814_400_000_000_000,
151+
MaxValidators: 35,
152+
MaxEntries: 7,
153+
MaxVotingPowerRatio: big.NewInt(200_000_000_000_000_000),
154+
MaxVotingPowerEnforcementThreshold: big.NewInt(1_000_001),
155+
}, stakingFrom(stakingSubspace.read(s)))
133156
}

‎giga/evmonly/precompiles/params/params_test.go‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,11 @@ func TestKeys(t *testing.T) {
7979
{"gov", "tallyparams.veto_threshold", KindDec, "uint256"},
8080
{"gov", "tallyparams.expedited_quorum", KindDec, "uint256"},
8181
{"gov", "tallyparams.expedited_threshold", KindDec, "uint256"},
82+
{"staking", "UnbondingTime", KindDuration, "uint64"},
83+
{"staking", "MaxValidators", KindInt, "uint32"},
84+
{"staking", "MaxEntries", KindInt, "uint32"},
85+
{"staking", "MaxVotingPower", KindDec, "uint256"},
86+
{"staking", "MaxVotingPowerEnforcementThreshold", KindInt, "uint256"},
8287
}, Keys())
8388
}
8489

@@ -351,3 +356,65 @@ func TestABIKeepsV2Methods(t *testing.T) {
351356
require.Equal(t, m.ID, ABI.Methods[m.Name].ID, m.Sig)
352357
}
353358
}
359+
360+
// testStaking is x/staking's default params.
361+
var testStaking = Staking{
362+
UnbondingTime: 1_814_400_000_000_000,
363+
MaxValidators: 35,
364+
MaxEntries: 7,
365+
MaxVotingPowerRatio: big.NewInt(200_000_000_000_000_000),
366+
MaxVotingPowerEnforcementThreshold: big.NewInt(1_000_000),
367+
}
368+
369+
func TestStakingValuesRoundTrip(t *testing.T) {
370+
v := testStaking.values()
371+
require.Len(t, v, len(stakingSubspace.params), "values() has one entry per declared staking param")
372+
for _, p := range stakingSubspace.params {
373+
require.Contains(t, v, p.key)
374+
}
375+
require.Equal(t, testStaking, stakingFrom(v), "Staking, the table, stakingFrom and values() agree")
376+
}
377+
378+
func TestWriteStakingRefusesOnceWritten(t *testing.T) {
379+
state := newMemState()
380+
require.False(t, HasStaking(state))
381+
require.NoError(t, WriteStaking(state, testStaking))
382+
require.True(t, HasStaking(state))
383+
require.Equal(t, testStaking, ReadStaking(state))
384+
require.ErrorIs(t, WriteStaking(state, testStaking), errStakingWritten)
385+
}
386+
387+
func TestStakingBounds(t *testing.T) {
388+
for name, edit := range map[string]func(*Staking){
389+
"zero unbonding time": func(s *Staking) { s.UnbondingTime = 0 },
390+
"unbonding time too long": func(s *Staking) { s.UnbondingTime = MaxPeriod + 1 },
391+
"no validators": func(s *Staking) { s.MaxValidators = 0 },
392+
"more than a committee": func(s *Staking) { s.MaxValidators = MaxBondedValidators + 1 },
393+
"no entries": func(s *Staking) { s.MaxEntries = 0 },
394+
"zero voting power ratio": func(s *Staking) { s.MaxVotingPowerRatio = new(big.Int) },
395+
"voting power ratio above": func(s *Staking) { s.MaxVotingPowerRatio = new(big.Int).Add(decOne, big.NewInt(1)) },
396+
} {
397+
s := testStaking
398+
edit(&s)
399+
require.Error(t, s.Validate(), name)
400+
state := newMemState()
401+
require.Error(t, WriteStaking(state, s), name)
402+
require.False(t, HasStaking(state), "%s: nothing is written", name)
403+
}
404+
s := testStaking
405+
s.MaxValidators = MaxBondedValidators
406+
s.MaxVotingPowerRatio = decOne
407+
s.MaxVotingPowerEnforcementThreshold = new(big.Int)
408+
require.NoError(t, s.Validate())
409+
}
410+
411+
func TestApplyChangesAStakingParam(t *testing.T) {
412+
state := newMemState()
413+
require.NoError(t, WriteStaking(state, testStaking))
414+
require.NoError(t, Apply(state, []Change{{"staking", "MaxValidators", word(50)}}))
415+
want := testStaking
416+
want.MaxValidators = 50
417+
require.Equal(t, want, ReadStaking(state))
418+
require.ErrorIs(t, Apply(state, []Change{{"staking", "MaxValidators", word(uint64(MaxBondedValidators) + 1)}}), errInvalidValue)
419+
require.Equal(t, want, ReadStaking(state), "a change failing the whole-struct check writes nothing")
420+
}

0 commit comments

Comments
 (0)